id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,877 |
Hello everyone, welcome to my channel here they solve problems Lead code today task number 1877 minimize the maximum sum of pairs in an array sum of pairs sum of pair A and b is respectively the sum of a n B so the maximum value of the sum of a pair is the maximum this is su among all pairs we are given an array us of even length N divided into pairs of elements in such a way that each element of us is contained in exactly one pair and the maximum sum of pairs is minimized, that is, we need to return the minimized maximum sum of pairs after optimally dividing the elements into pairs Let's look at the example in the first example we have four numbers 3 5 2 and 3 the sum is expected the maximum sum will be obtained if you look at the elements we see that for example if we take the maximum element, that is, in this case it is five, then in order to minimize the pair we need to supplement it with the minimum element in the array, that is, in our case, a pair To the number p will be d as the minimum element, then the second pair is just triplets, also look at for example d there are already six numbers and Similarly, if we take the maximum number 6, then for it the Pair that will be minimal is the minimum element 2, then we take the second maximum Emen This is similar for him zhed occupied then the pair for the second largest element will be the second smallest, that is, roughly speaking, we need to create pairs in such a way that, accordingly, we take some element in size from to the maximum begins with the maximum That is, the largest element is the second in size, and so on the corresponding element goes to it as a pair if we count from the smallest elements, that is, the third largest element for it, the pair is the third smallest element, so the sum of pairs will be minimized. The task is to find the maximum sum With such a partition, what we need first of all we need to get a sorted array so that we can take the maximum and minimum elements to sort, we simply call the sort method, then we need to define our define a variable for the result in which the maximum sum will be returned, it will also be useful to create a variable to determine the length of the array N and now we need to go through it in a loop by indexes of the array to the middle and accordingly we will take pairs, that is, the current element starting from the minimum and from the maximum, as we will do this, that is, for and in the range from zero to n, we calculate the current sum in half, that is, let's say the variable PR Well, or it itself is equal to us with we add and now we need to supplement the pair with the corresponding element from the other end of the list, this is done in the same way as -1, that is, for example, for the zero -1, that is, for example, for the zero -1, that is, for example, for the zero element it will be N - 1, that is, the element it will be N - 1, that is, the element it will be N - 1, that is, the last element and, accordingly, for the first it will be the penultimate And the last thing left for us is to update the result that is, take the maximum value From the current and the current sum of the pair since we went through the entire loop, the result will be the maximum sum of the pair that we return Let's try to run the tests So we have some kind of typo Yes, MASI is called uss and not for us, we run the tests again tests passed we send the decision is accepted it is quite optimal Now let's estimate the complexity of the algorithm first the first action we have is sorting the complexity of sorting is from nlog N so in this way we write further we go through the loop to the middle of our array since this action depends on the length of the array then this action has a complexity of o from N, respectively, with That is, our total complexity is obtained from N L N n according to the rules for evaluating sorting and using the notation O large this is equal to the largest of the two components, that is, in our case it is N L, that is, the total time complexity N L N That's all for today Thank you all for your attention Bye everyone
|
Minimize Maximum Pair Sum in Array
|
find-followers-count
|
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
494 |
okay let's talk about target sum so you are given integer read nums and the integer target return a number of different expressions that you can build so in this example there are uh lists in the rate and a target three so you have five different ways so in this situation i mean in this question you can actually use recursion but you need to do it smartly because every single integer it has two options it's either plus or minus right and if you're just using recursion without uh memorizing this will dictate you to the n and if you memorize it this will cost you i mean you're reduced to n times s and represent the length of the array and s represents the sum of the thumbs which is the grid so in this case i'm going to use hashmap map stream integer i'm going to talk i'm going to explain why i use string so just give me a moment so i need a helper function so helper function will help you to memorize every single step and then you uh basically just return um all right if i want to check if length the if n is equal to zero i will just return zero if not i would you just use the hover function so help a function what i do i will have an index so the base case is if the index is equal to a number and then if so i need to actually check if the property is actually equal to zero and then if not i would nothing okay i mean if actually equal to zero then i would become one else return view all right so uh for every single recursion i will just probably minus nums at index and move my index that's fine for every single time but you have to know like sometimes you need to have a plus because this could be what this could be two way right and then still in the exposure for every single index it could be plus or minus right and this i mean you just have to making sure you know what to do so find the index um sorry find the target some way right you have the nums you have a target the inlet stop on zero and if the index is actually equal to a number length um you have to return pretend when probably it's actually zero this will become one else return zero and now we need to have a key so wait all right so let me have a key go string key so this keys actually represent the target i'm going to use common separation and also so for every single um for foreign index i will memorize what is my actual value in this case so if my map does contain this t right i would just return the value okay so um i haven't do this way right so i haven't do this let me start doing this so this will be one this will be your answer when you want to store in the into your value into a map right so for every single time you have a plus or minus right so num and target minus denominator i which is index sorry x plus one and anytime you have a plus and i will tell you why so for every single way um this will give you one answer and this will give you another insert and both of answers will actually um combine together to resort and i will add into the map and this will give you the unique uh value for the current index beyond current that's with this remaining target right and i'll just put uh put my key to my resort and return results and this will be the solution and this will be a little bit hard to explain but uh let me um okay um and here we go so all the time and space complexity and let me just go over it so you call this function and in this function you actually traverse every single index so at least all the plan right and then you need to have a sum right you need to keep adding so in this output function you're calling helper function so it's actually the summation of the numbs be honest because you are just keep adding the um negative and positive number so i would say the time will be time s and s represent the sum of the nums and also for the space they're actually the same so for every single uh for every single key right you actually put into it right and then this is pretty much the same so the timing space i'll send i'm chinese so i'm just quickly tell you if you don't use a um microphone i mean you if you don't use a memorized way this is actually the solution so follow a helper function and then for each hover function you just recursion yourself and this will pause the test for sure right so let me just run it but this will give you 2 to the n which is crazy and for every single value you i mean for plus and minus they actually act differently and you have to subtract and then add them back and then adding that and then subtract so just giving the two different ways but this is uh this will cost you more time and in complexity and i finished the video and if you want to subscribe like leave a comment if you want and i'll see you next time bye
|
Target Sum
|
target-sum
|
You are given an integer array `nums` and an integer `target`.
You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers.
* For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1 "`.
Return the number of different **expressions** that you can build, which evaluates to `target`.
**Example 1:**
**Input:** nums = \[1,1,1,1,1\], target = 3
**Output:** 5
**Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
**Example 2:**
**Input:** nums = \[1\], target = 1
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 20`
* `0 <= nums[i] <= 1000`
* `0 <= sum(nums[i]) <= 1000`
* `-1000 <= target <= 1000`
| null |
Array,Dynamic Programming,Backtracking
|
Medium
|
282
|
744 |
next problem is called find smallest letter greater than the target we are given an array of characters uh called letters that sorted in non-creasing letters that sorted in non-creasing letters that sorted in non-creasing orderorder and the character Target uh there are at least two different characters in the letters uh and we have to return the smallest character in The Letter that's that is lexicographically greater than the target if such character does not exist we have to return the first uh character in layers so for example here we have Target a and the first letter that's uh that's larger than the target is uh the letter c and it's the smallest uh lexicographically smallest letter in the input array so we just return uh the letter c next for the letter c uh we are checking basically the first element and it's the same one so we have to move forward in the array because it we know it's non decreasing so it either will have a duplicate or a larger uh Lea and in this case we will have F which is larger than C and it's the first smallest letter than it's larger than C so we just return it in the last example we have uh tar Zed and we know that there's no uh letter that's larger looks rly than Zed so we will just return uh basically the first element whatever the element is in this case is X so we just return it as the uh out for function output uh the uh constraints are the following the letters uh input array is R size is ranging from 2 to 10 4 uh all letters inside the letters input array are lowercase English letter they are sorted as we said they are not in decreasing order and the letters contain at least two different characters uh and one important note the target is also a lowercase English letter so to solve this we first know the nature of the array uh because we are searching and the uh array is in a non decreasing order a natural choice is to try binary search uh for this problem but we will in uh there will be some modifications to the regular binary search uh to make it work for this uh problem first thing to note is that we are not searching for the exact uh Target we are searching for the closest one that's greater uh greater than the Target and whenever we have this closest and not the exact uh I use the following boundaries I use the low I set it to the start of the uh of the array of the uh exploration space and for the uh end boundary I put the uh basically the length of the uh input array so it's basically the uh the high boundar is pointing uh out of the array uh and that reflects are invariant uh instead of having low equal uh smaller or equal to high we have to make the invariant that low is small is always smaller than the high because we will be checking the we will be uh checking the elements of spe specific indices and if we have low is equal to high uh we might be out of boundary next we will do the calculation for the met and we will check if the current element at the mid is larger than Target and if it is we don't just skip the whole right half we skip the right the almost the whole right half the side but we accept for the uh element at the uh index mid why do we keep the index mid because we know it's the low it's currently the lowest possible uh letter than it's that is higher than our Target so it might be the best candidate that we have uh so we have to keep our high at the mid uh we have to keep set it at the med index but if we uh find at the index mid is uh smaller then basically all the elements before are smaller than the than our current Target so we can skip the whole uh the whole left side and if we are done with the with our traversal and we didn't find the element that's that is larger than our uh that is larger than our Target uh the low and high will be pointing to the same element that element will be out of boundary it will be the initial value of the high and because it's out of boundary we know that we haven't found uh the T the element that's larger than the Target and uh because we know that we will just uh do modulo of low and in a case where low is um uh where low is equal to high and they're pointing to the first element inside the boundaries of the uh input array that's larger than the target then we will have a valid index and we will just return that letter but if low and high are pointing to the out of boundary with the they will be pointing to the index that's equal to the Letter's uh input array length so when we apply modulo that will basically revert back to the zero and we will just return uh the first element because the index uh zero corresponds to the first element and because we are using the binary search the time complex logarithmic in this case and for a space complexity we are not uh creating any additional dat structure so we have a constant space complexity
|
Find Smallest Letter Greater Than Target
|
network-delay-time
|
You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`.
Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`.
**Example 1:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "a "
**Output:** "c "
**Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'.
**Example 2:**
**Input:** letters = \[ "c ", "f ", "j "\], target = "c "
**Output:** "f "
**Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'.
**Example 3:**
**Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z "
**Output:** "x "
**Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\].
**Constraints:**
* `2 <= letters.length <= 104`
* `letters[i]` is a lowercase English letter.
* `letters` is sorted in **non-decreasing** order.
* `letters` contains at least two different characters.
* `target` is a lowercase English letter.
|
We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.
|
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
|
Medium
|
2151,2171
|
1,791 |
hey what is going on it is thursday april 21st 2022 welcome to coding with chef and yeah uh i'm ready on this fine lovely thursday hitting up uh the close to the end of the week point um i'm ready today to do a graph problem and you know graph problems to me are fundamentals of computer science and they um i think they're fundamentals of computer science to everybody but what's really interesting is that um i it's really nice when you have a graph problem that seems pretty straightforward to do because they can get quite complicated right like try solving the traveling salesman problem and you need uh but ton of computer science to do that um in all different kinds of ways and optimizations right so um yeah let's you know get some good practice with a very simple one and that one is 1791 find center star find center of a star graph and i'm going to like this problem because i think it's a cool problem even though it's simple um this is an undirected star graph containing of n node labels from one to n a star graph is a graph where there is one center node and exactly n minus one edges that connect to the center node with every other node you're given a 2d integer array edges where edges of i equals u of i v of i indicating that there is an edge between the nodes u sub i and v sub i return the center of the given star graph and this is one of those problems where it's like well i mean clearly the picture uh it gives you everything you need to interpret about the solution and it's much easier to understand than the description though the description isn't actually that hard to understand okay so let's get to it so here's the example you have an edge from one to two to three four to two right and i just have to find that the center is two okay um this is pretty straightforward i mean like literally i think you can you don't even have to really think about it too much that uh every um every node except the center has only one vertex uh coming out of it so pretty much just find the node that has two vertices or more than one vertice more than one vertex attached to it i think that's pretty much the easiest way to go here so what we can do is uh first there's like a ton of ways to do this like in a super efficient way but i'm gonna approach this as a standard graph problem uh where we are given an input as an edge list okay an edge list again is a list of edges between vertices and i think to me i like to convert everything that is an edge list into an adjacency list because an adjacent adjacency list to me is a much easier data structure to work with when it comes to graphs and that's basically there's a number of ways to do an adjacency list but it's basically a map of vertices um that like for example if you have vertex one two uh three right then your map of what vertices are attached to so three is attached to two uh two is attached to nothing uh one is attached to two okay uh actually two could be attached so you know it depends on how you wanna do this because sometimes you can make an edge list that's attached to a uh in both directions right so this is it for a directed graph right if this was a directed graph one and four would be attached to one uh equals one right so you know again basically um you could do it a number of ways if you treat this as a directed graph in this particular problem constraint then you could say that well okay you know um anything that doesn't have any edges attached to it right is a center note that's one way to do it in my way i like to just uh look at whose edge list has something greater than one because in this scenario um right you'll see so let's iterate and create our adjacency list quoting code or adjacency map however you want to be more formal about it okay um so i'm going to iterate through all the edges and then again this is just more of an exercise in doing this adjacency map grading so hash set integer items equals star graph that's what i named the graph data structure get or default edges i zero new okay bam all right so that's basically how you would um go to iterate this is this items is going to be the list of things that the graph is connected to i guess a better name would be um destination let's call it dust okay um okay then dusts that add edges of eye one now i'm just adding the edge because remember an edge list is the first vertices of an edge list here is the source and the second vertex of the edge list is the destination so i'm just adding the destination vertices of all the edges to the sources uh that they're corresponding to and just you know if you're not familiar with this map data structure the way that it's updated you know this first parameter is going to be what i'm doing is getting the list that's associated with this destination uh or sorry this associate associated with this source this is the source uh and if there's no list yet associated with the source during this iteration then i'm making that list i'm creating a new instance of the list okay and if you have kotlin or any other languages there are a lot more syntactically shorter ways of doing this but we're just doing this right now for um java my favorite language items um not items i call it dests okay cool and then for tests that size greater than one edges so basically this is the condition i was talking about if the size of the destinations is larger than one then we know that we're at a center node because the destination can only be really connected in one direction or can be that destination is the center of all the other uh elements right so uh if it's equal to one uh or if it's larger than one right if it's equal to one and if every other edge has a value that's equal to one then there can't be any center right so the number of nodes has to be at least um three in order for there to be a star graph right like uh that could be a good edge case um that we want to try to uh in the future handle if the problem i don't think requires that so dest equals star graph dot get or default edges i1 okay again so this is a bi-directional each of the this is a bi-directional each of the this is a bi-directional each of the edges is a bi-directional edge so edges is a bi-directional edge so edges is a bi-directional edge so what i'm doing here is i'm just changing the source and destination up and reversing that so that the edge is connected in both directions and that represent is represented here so i'm not just doing a directed graph i'm doing an undirected graph okay you have to put edges i one let's see tests so i'm reusing this dust value right i don't have to but saving some space i guess you know minor really um if dust dot size is greater than one return edges i one so the beauty of this or this little bit of beauty right is that we don't even have to wait for the algorithm to uh finish right because as soon as we get uh the constraints of these graphs are very tight right as soon as we get something with edges that are larger than you know or destinations that are more than one then we know that vertex has to be the star vertex because every other vertex or the center vertex because every other vertex in the star graph is only connected to one other element which is the center okay so let's try running this let's see if i put 4 and line 14 this is the fun part about correcting all my little inconsistencies by running the program line 14 again and let's see what i did wrong okay so um ah what i need to do i have to actually add this edge to the edge list okay um so here because sorry edge is zero okay so i'm adding the destination the old source to the destination okay i need to make this let's try this again okay come on let's work and there you go it worked okay and yeah again i don't trust the time but we'll say we average let's average the three runs about 50 uh so let's you know there are faster ways of doing this but i thought this was semantically nice okay well that's uh yep that is the solution if you like this uh simple solution to the simple problem uh leave me a like comment uh comment in the link below put the bell icon on i'm going to try to do these every day and let me know how i'm doing all right i will see you later have a good day and peace
|
Find Center of Star Graph
|
richest-customer-wealth
|
There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph.
|
Calculate the wealth of each customer Find the maximum element in array.
|
Array,Matrix
|
Easy
| null |
122 |
okay so hello guys let's try to solve question number one will do uh from lead code the best time for buying and selling the stock part two okay so about this question uh so they have given us a vector and we have to find the maximum profit that uh we can buy and buy buying then selling the uh stocks but the difference between the previous and this question is that they have told us we can buy and sell it any number of times okay so let's see the test case so they have given nums is equal to 7 1 5 3 6 and 4. so wait so what I think this question is pretty easy than the previous one okay why because what we have to see we have to just see that uh if us we have to see the current value of the stock and we have to see the next value of this talk if the next value of the stock goes is greater then buy the stock at that point okay now go to the next value if then uh at the next value check if the next value is greater or smaller if this goes down then sell it so you will get this profit now again check add this point if the stock is going down then don't buy it if it is going up then buy at this point now again check it if it is going upside uh then don't sell it keep it as it check again check here again if it is going downside then sell it okay so now and if we keep so what will you do we will just add this part We'll add this part and so on and if it is end here and then when we add these two we'll get the profit let's see that if it is true for this condition okay so 7 so after 7 it is going downwards so there is no point in buying it at this point now go to one now after one is it increasing yes it is increasing then buy it at that point okay at five it going downwards means it is decreasing then select that five so your profit becomes like profit your profit will become like uh five minus one will be four now at Pi we have uh you have selled it now sold it now at three so C at three is it going upwards yes it is going upwards so buy it at three again uh now at six see this is going up or downward it is going downward so sell it at six so six minus three plus three you get 7 as the profit okay so and that's the answer they have given so what you have to see you have to check if the next value is going downwards then sell it if next value is going upwards then don't sell it that's it so now let's try to code this approach okay so this is the question we're going to do let's try to solve it as we have this first so let's first create a variable profit 0 okay so now uh let's create the for Loop for H is equal to I is equal to zero to I is decimal size and increment then what you have to check if the offer I is greater than I minus 1 Okay so just a second so we have either I minus one so let's start with one if we don't then it will give us error so if it is greater than what we have to do so just do profit okay through is equal to rho Plus the difference between these two terms we just copy this copy now and at the end just return them perfect let's try to run it okay yes so the test is have been passed now stop it so yes so we have some Services submitted so let's meet in the next video
|
Best Time to Buy and Sell Stock II
|
best-time-to-buy-and-sell-stock-ii
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
121,123,188,309,714
|
1,631 |
hello and welcome to another video today we're going to be working on path with minimum effort so in this problem you're hiker preparing for a hike you're given an array of rows and columns and so the height of a particular square is just the row in the column and you want to get from the top left to the bottom right and you want to get the maximum absolute or the minimum absolute difference between the height of two consecutive cells and what I mean by that is every time you move there's going to be some height difference here so like here there's two and for any route you want to take the maximum possible difference and that's the path with that's like the that's the effort of the hike so essentially here there's a difference two so the effort of the hike would be two but let's say you go this way right so here we would have one zero three so you take the maximum one out of all those so the effort for this route would actually be three so you take all the efforts combined and the biggest one is the effort and you want to return the path with the minimal efforts a little bit confusing but that's what it is so in this case like I said we would go this way because the effort here is two where if you want something like this it would actually be three because here's three now we have another example over here so let's figure out the effort here so the effort here is one right because every single Square the effort's one and one let's take a look at some other routes so essentially you want to be one and you can't beat one because the effort would have to be zero for every single Square which obviously there's nothing there right so it would have to be like one so therefore here's one now here the effort is zero because the whole path of difference is zero so essentially we need to figure out how we can do this and it's kind of like a shortest path problem except it's a little bit different because you know let's say this was like a problem where the numbers maybe like how far you have to travel right so you start here you travel one you travel three and so on and you want to get like the shortest path so we know how to do that problem right that problem is pretty straightforward and the way to do that would be jigster's algorithm so let me write a little bigger extra large so it would be jigstros and I don't really know how to spell it but something like that and it's basically it's a pretty straightforward algorithm you simply make a heap and you put all of your paths in there so like here you'd make a heap you'd put your starting path in you know so let's say it's like row column and the distance so it'd be like one and then the row column would be something like this you would put that in and essentially what would happen is you would have all of them in there right so you'd have some other distance and you'd have some other like current cell you're on and essentially you would always keep popping out the one with the smallest distance and whichever one gave you the results first would be the answer right so you just put in like your current rows and columns and you want to make sure that you don't go to the same one twice and that's how you do a shortest path problem right you just literally keep track of what's the current distance of the path I'm in and you're just greedily taking okay what's the shortest path so far let's Traverse that path and then once you get to the end that would be your path but here we're not really keeping track of distance we are more keeping track of this effort so it's a very similar way of doing this so what we're going to actually do is we are going to give the row in the column but instead of giving the distance we're going to give the effort so let's just go through this example here so essentially what's going to happen here is let's actually move this down maybe a little bit more so we have a lot more space right so just put that down over here I'm going to go over this example here using the jigster's algorithm so essentially we're going to make a heap we're going to put it over here so we have more space like I said and we're actually just gonna even get rid of this closing thing okay or we can make it like all the way over here so we have a lot of space so we're going to make a heap and our Heap is going to have the effort which is zero starting off right so we're going to start right over here zero and it's going to have the row and the column so we could also label these as zero one two let's get rid of this zero one two so essentially we start at zero first right because we want to have a heap and the we want it sorted by the effort so the effort's gonna be zero at first okay so now what we're going to do is we're literally gonna pop and then we're gonna try to go in every single direction from where we're at and we're also going to add this to a visited set just to make sure we don't go to the same place twice because like if you visit this you don't want to go to the same place twice right you don't want to keep revisiting the same route over and over otherwise that would be like an infinite Loop right so the way we're gonna do that is we're gonna have a set as well and I'm just gonna in this example every time I pop something I'll just maybe like cross it out or something right something along those lines would be fine too okay so what we're gonna do is we are actually going to yeah do that so let's see what that looks like so essentially we're going to pop this zero and we are going to go in every single direction from here so we're going to pop which means we're going to kind of like this is visited we'll Circle it meaning visited we're gonna pop this so we're gonna get rid of this and we're gonna put in new things so from here we have to go to every possible Direction so up is out of bounds left is out of bounds right is inbounds so four right we're going to need to put that in so our effort was Zero but now what's our effort here well it's one so we're going to put in one and we are going to put in the coordinates here so this is row 0 column one right and also we can go down that's valid as well right so we are going to put that in as well so it's effort two and that's Row one column zero okay and now we're going to mark this as visited and we'll just like cross it out or something to make sure really care so now we are going to pop out the smallest effort right we're doing jixtures so we're just being greedy so we're going to pop out this one which corresponds over here and this is going to so we're going to pop this out so we'll get rid of it and now we have to travel in every single direction from here so from here we can go in two ways so first we can go right which is effort zero but we originally had effort one right so we need to say if we had effort one we need to keep track of the maximum current effort along the path right because that's what we're going to be returning so this is effort zero but we're going to keep the max of the current one and the last one so we're going to put in one and then we're simply going to put in the row in the column here so this is going to be row 0 column two and we can also go down which is effort six so we're going to put that in effort six and this is Row one column one okay cool so now these are the two that we visited or they're not really visited we haven't really visited those yet but now this is essentially what we have and we got we visited this one over here so now we're going to do the same thing we're going to pop out this first value so this first value corresponds to where right so it is effort zero or effort one and then it's row zero column two which is this value over here so we're going to pop that out and we're going to try to visit everywhere from here so we're gonna get rid of this and we are going to try to visit oh it's actually instead of just getting rid of it let's just move it down here because we do need to check the effort so the only place we can go is down right so if we go down the effort is like I said it's zero but we want to keep track of the biggest number we've seen so far and we've seen one so we want to put in one and then this is Row one column two so there we go now we can actually get rid of this because we've just used it now we can also you know say we're completely done here so now we do the next one and we're gonna pop this one out for the next one let's do that so we'll just put it down here so that's this value here now we can go left right so that's going to be effort six gonna be the same and you can't Mark something visited until you're actually there because let's say the effort is less than so the effort is also six here so six one and we can also go down right and the effort is three there so let's do that so we're gonna add f for three and it's going to be 2 -2 and it's going to be 2 -2 and it's going to be 2 -2 okay and now we are going to actually get rid of this we're completely done with it and we can mark it like so okay so now we're going to pop the smallest effort again which is this one over here right two one zero that's the smallest effort we have so let's add that in so I'm not showing this heap of sorted but obviously it's going to be a Min Heap so we'll be sorted and it will give us the smallest value so two one zero what value is that's actually this one over here so from here we can go this way so let's add that in so that's effort five and it is one okay now we can also go down and that is effort two so we'll add that in so it's effort two and it is row two column zero there we go now we fully used it so we can get rid of it and if I get rid of it I just mean like we're gonna add it to the visited set so we're completely done here now we're going to pop the smallest again which is this one here smallest effort which represents where again so that's going to represent effort two chat two zero which is right over here and we can go here from here so this is going to be effort to again and it's going to be 2 1. now we're completely done with it and then we can mark this as visited now from here we're going to pop this one again because that's the smallest effort again and now where can we go from here this is this value here so we can go up we still haven't visited that yet so that's going to be effort five and it's gonna be one and we can also go right which is effort two and that is our greatest value so far so two and then two right so now finally for our last step we are going to pull this value here because this is a smallish effort again so we're going to pull this value here and we're going to say oh look this is our actual This Is the End so then we can just return the effort here so you see how like even though we took this pace we took this path first because this was so expensive we kept pulling out these the cheapest effort first so we actually got this path first right and that effort was two so that's pretty much it so you essentially you make a heap you put it you keep track of your maximum efforts seen so far and as soon as you get to the end you're guaranteed to get the minimum effort to get to the end and that's pretty much the algorithm so the structures algorithm with a heap pretty straightforward you just instead of keeping track of you know the current distance you just keep track of the maximum efforts in so far every time you go down the path and then every time you add a new node you just say okay for this current node with this current effort what's the maximum effort here is it this is this new one that I've seen or is it the old one and keep track of that and you're guaranteed to have the minimal effort once you get to the end that if you use a heap so let's actually code that up now it's actually I believe we can full screen this so there we go you can see it a little better so we are going to make an M by n so we can say m n equals line Heights zero now we are also going to make a directions right so let's do that as always because we can go in every single Direction so one zero and you can make this two pools or array I'll make a tuples this time but you can make it in Array of arrays if you want as well so zero one and zero negative one and there we go now we're going to have a visited set visited and finally we're gonna have a heap with some default value right and the default value will be the actual value of the like what do we want to call that the uh effort right so it's going to be zero and then index zero here okay so we can say wall Heap we're guaranteed to find a result we can say effort and then the X and Y coordinates effort x y equals default keep and we can say if x y equals the end values right which is M minus 1. n minus 1 that means we actually got to the last node we can just return the effort because we got the last node which is where we want to be otherwise we can check if x y invisited then we've already seen it so we don't have to do anything we can just continue here otherwise we need to add to visited so we'll add x y here and so I guess that's why you also want to have actually that part would matter now this is okay so we need to add x y and then we need to actually get new directions right so we can say for something new so we can call it like DX d y or we can call it like n row or whatever you want to call it right I guess maybe we can also rename these if you wanted to you could so you could say like four row call and then this could be row so it's like a better variable name right instead of X Y it seems a little better so there we go call now we can say for something so we can say like r c or something maybe in directions new row equals row Plus R and new column equals call plus C something like that now we need to check if these new rows as new columns are actually in bounds right so we're going to say if 0 is less than or equal to new row less than M so maybe this is also should be renamed so this should be like rows and calls or something right it's probably better so we can do that as well so this is rows Halls which is better variable name why not right so if new row is less than rows and zero it's less than or equal to new call is less than columns and we could say new row mu all not invisited right we don't want to add things that we've already visited no point there we could say new effort equals maximum of the old effort or the absolute value of and then this is going to be Heights new row new column minus Heights of the old row and row column right so row column so we're going to get the difference there get the absolute value see if it's bigger than the effort and store the biggest effort there now we have to heat push and we need to do we're pushing to the Heap and what are we pushing so we're pushing new effort and we are pushing as well um new row and you call also like I said you can push a tuple you can push an array it doesn't really matter and you are guaranteed I believe you're guaranteed to get a result here I don't think you'll ever get anything that wouldn't work but just in case let's return negative one here but we shouldn't really get anything that never works so let's see what we have it's actually stopped the minimize so we can actually see if we've got an answer it looks like it's accepted okay so it looks like it's accepted and as you can see it's reasonably efficient so let's go through the time and space complexity for it's full screen again so let's go through that so for the time what are we doing right you always want to think about it so we make rows we make columns that's nothing okay while Heap so how many elements can we have in the heat maximum well we're always checking if it's not visited so we can add something multiple times but it's not that many times so realistically we're going to add something roughly M by n times right if M and N are the rows in the columns like we can't add something multiple times technically but it could be a little bit over but it can't be like you know an order of magnitude over so it's going to be M by n that you like that's going to be as many items as you can have right but also for every single one of these elements we do a heat push and a heat pop so that's also going to be log M by n because if the Heap is M by n every time you do a heat push it's log of the size of the Heap so it's m by n Times log M by n for the time and for the space also pretty straightforward right our Heap and our visited set are going to have roughly M by n items so yeah that's actually going to be it for this problem hopefully you liked it not too bad normal dijkstra's problem you just have to change you know calculating the distance instead of that you have to calculate the maximum efforts seen so far but it's basically the same thing so hopefully you like this problem and if you did please like the video and subscribe to the channel and I'll see in the next one thanks for watching
|
Path With Minimum Effort
|
number-of-sub-arrays-with-odd-sum
|
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**.
A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route.
Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._
**Example 1:**
**Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\]
**Output:** 2
**Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3.
**Example 2:**
**Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\]
**Output:** 1
**Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\].
**Example 3:**
**Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\]
**Output:** 0
**Explanation:** This route does not require any effort.
**Constraints:**
* `rows == heights.length`
* `columns == heights[i].length`
* `1 <= rows, columns <= 100`
* `1 <= heights[i][j] <= 106`
|
Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.
|
Array,Math,Dynamic Programming,Prefix Sum
|
Medium
|
2242
|
509 |
hello everyone welcome to another one of my lead code videos in this one I'm doing lead code 509 Fibonacci number and it's part of an effort that I want to make more dynamic programming videos so that any of you doing the lead code study plan on dynamic programming can benefit from these videos so let's get right into it so lead code 509 says that Fibonacci numbers are donated by this equation so the Fibonacci of 0 is zero the Fibonacci of 1 is 1 and the Fibonacci of n is n -1 + N - 2 Fibonacci of n is n -1 + N - 2 Fibonacci of n is n -1 + N - 2 Fibonacci so given n we need to calculate the Fibonacci number now this is kind of dynamic programming because this is kind of the recurrence relation where you have the Fibonacci number defined as a function of previous FIB Fibonacci numbers right so as long as in this case we have the previous two Fibonacci numbers we can calculate the nth Fibonacci number and N can be anywhere from 0 to 30 right so first let's take care of our basic cases where if it's either zero or one right so if n is less than two that means it's either zero or one then we just return n right so we if it's zero we return zero if it's one we return one now the Fibonacci of n is n minus1 + n now the Fibonacci of n is n minus1 + n now the Fibonacci of n is n minus1 + n minus 2 in a typical dynamic programming you have to store like an array or something to remember the past values but in this case since we only care about the past two we can just say store those so we can say int like n- 2 those so we can say int like n- 2 those so we can say int like n- 2 Fibonacci which initially will be zero right because uh we'll start our n at two so for any n greater than equal to 2 we'll start our n minus 2 at zero and our nus1 will be one right because that's the F of one so then we can have a for Loop where we start n or I equal 2 I less than equal to n i ++ equal 2 I less than equal to n i ++ equal 2 I less than equal to n i ++ right so this will be our kind of loop to go all the way up to F of n now we know that int feibo of n is equal to basically the nus 2 feibo plus n minus1 right that's our equation over here now that's the feeo of n so basically if I is 2 we go N - 2 + N - 1 so 0 + one and 2 we go N - 2 + N - 1 so 0 + one and 2 we go N - 2 + N - 1 so 0 + one and then we need to adjust this right so the N minus 2 feibo now equals = nus1 for N minus 2 feibo now equals = nus1 for N minus 2 feibo now equals = nus1 for the next round right because in the next round n will be I will be like three so 3 - two is actually one now so we are 3 - two is actually one now so we are 3 - two is actually one now so we are kind of Shifting this is basically our second La last a second previous value and this is our previous value right so as n increases the second previous value now becomes which was in this iteration the previous value and our previous value actually becomes fibo n which is the value we just computed right because in the next iteration I will be three so this fibo n for I equal 2 will be um now our n minus one so we'll keep doing this until we hit n right so at the end of this Loop whatever the fibo N this maybe is more accurately fibo I right because we're calculating the I Fibonacci number but at the end of this Loop the fibo I will be equal to n because We're looping up to n and we're going to be storing that in N minus one right because n minus one equal fibo n or fibo I they should be so at the end of the loop whatever is an N minus one will be our final answer right because that's what we stored the last computation of the loop in so let's run this code and see how this does oops I made a typo over here this is nus 2 + nus1 so let's run that is nus 2 + nus1 so let's run that is nus 2 + nus1 so let's run that again all right accepted let's submit perfect so this beats 100% of submit perfect so this beats 100% of submit perfect so this beats 100% of runtime I hope you enjoyed this video I'll see you in the next one cheers
|
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
|
417 |
It was well mixed with your arrow, I wash you guys welcome back to my channel again suhag question a question number 417 the name of this is Pacific Atlantic Water Flop so let's make it clear we have our antique tone in a set a ok so this Till the announcement, we will understand it very well first and then solve it is a very good question and if it is asked then considering the importance of the question, we will give it well, we are ready, let's read the question first, it's a minute. Enrique Regular Iceland Border Very Updater Border Wisdom Pacific And The Atlantic Ocean Saw First Eminem Speaking Means More And Key Value Will Be Different Was Happened The Public Auction Touch Right Cylinder Left End Top 50 Atlantic Admission Test Ireland Rate Of The Water Match Meaning This Iceland If this one then this Pacific Ocean bole see top-left channel Iceland Left toe stomach top-left channel Iceland Left toe stomach top-left channel Iceland Left toe stomach Pacific is touching the edges of the left and left laptop Atlantic Simar Ali Atlantic is touching the fans of the bottom and right Sudhir Ojha Length is this partition Into A Grade Of Yourself Thank You Are Giver 9 Age Mintu And Teacher Matrix Height Veer Height Row And Column Represent The Height Of The Sea Level Means It Is Number One Or Grade 2 Years Keep It Is Great Cigarette Me Job Salary That Item Present It means making one height thin, ignoring the height like this is one, this is two, if it is three, then this is three, this is 414, but now understand this much, I now understand as much time as you, one of your colleagues, try now as we need. Explained to her that if you understand that such shares are yours, then do you have any problem with them, it means that while doing edification, it is just ladies, if you see nothing like this, then it is okay here, after that Dada said, that is why Diplotop then and the water. And water can go forward to the neighboring track. Clean note. South East and West means water can go in all four directions. The place of rain water is that which is the evening flight is less than or equal to. Grand slam and laga hai if less. If it is done or equal to then water can flow. Different people have different nature, how water will flow. Muslims may not be able to understand what is happening. If they consider you as bad and move ahead then Holi will be elected to 20 of lower courts. Have the current next to it should say that flowed in the water where it has its value in the prince l which is equal to that then garlic has become water here if water has fallen here if a drop of water has fallen here it will go here Will it go down or will it go up if its value is its value in it if the value of any of these four is equal to or less than this then the question now is chicken which is just equal to this is less than this so like here it has increased by the fifth. It will not go here 3 This is smaller than 3 So it will go here Okay, now we just enter water flow away from any salary * Don't Roshan Okay, okay after that when * Don't Roshan Okay, okay after that when * Don't Roshan Okay, okay after that when Internet Motivated List 2nd Grade Coordinator Result b.a. The result itself is Coordinator Result b.a. The result itself is Coordinator Result b.a. The result itself is equal to the result of a personal problem, meaning a to-do list, meaning a list of lists, meaning a to-do list, meaning a list of lists, meaning a to-do list, meaning a list of lists, speak in lift canal list, resort to that result in which you have to find the cord, you have to find out if this water is complete. If the whole of the fast goes to the sister's place in this sea, if it falls from here to here, then the whole cloth here goes here, then August Job, the drop of water is going in both the sides, can it flow in both the sides and Of course, it can be used on both sides. Poem is specific in Atlantic Oration and a little in Atlantic, so you have to return it, that is, it is okay to return it by putting it in the list of lists, otherwise it will be a very dense and violent campaign. What is there in the question? He is saying, I have given him a reed and it was said, put it like this in Lallan, how many buildings are there are very big buildings, one of them has to move away, some of them have 5138 buildings like this, and there is a lot of rain there. It is happening and one side of the land is surrounded by the Atlantic Ocean and one side is surrounded by the Pacific Ocean, so know that if there is water in this building then water can open left or right from the top of that building. No means water can come from there, otherwise how can it happen if the height of the building is smaller than your old building where it is facing this direction, if this building will hit you from the old building then it can happen now or now that's all Now you understand, I am here I am telling you, now here I am not killing them, I am telling you the answer, now I am telling you to see the answer, now I am telling you just a question, okay, now you have understood, it is very simple. In this, the animal robbery was made two days ago, embezzlement happened two days ago, in the number five land binary number, it was to be told that number 570 was made with water and this was told from many sides. If you are a senior manager, then it is very good, otherwise. If I bring it to the button above, then one and a half face. If you understand well, I mean that I have made it a little bit well, so you can see that, after that you can come here, okay, now let us see, here I am a serious of a pauri. Now I am asking you one thing, if it rains, if a drop of rain falls here, then you. Let me ask you, if water falls here, then in which direction will the water move forward? Will it move ahead in production? Will it move ahead in this convention? It is not a matter of office, this vaccine will move ahead. I have to ask why, because whatever height it is lower than where the water fell. This is just a step of the year. This one is less than this one, this is an less than this one is less than this one, this is an OBC thing, wouldn't it be that if we assume that if any drop has fallen here, it is of water. If it has fallen here, it will reach here. It is impossible that it is found here, but if it has fallen here, it can reach here. After your office, understand that if you take whatever I say and will reach here, then it can reach there or here, but After getting the drop here, it cannot be here or on top of it, okay, he has told them the question only that the height is garlic and a want to but this prostate, if it is believed that ₹ 1 like this, if she had fallen here. So she ₹ 1 like this, if she had fallen here. So she ₹ 1 like this, if she had fallen here. So she can go here and he can go here, it was said equally, but if there was someone like this, then that vehicle can be used in equal form, the drop means water can remain and there will be fear below, okay? I said okay. Understand this much, you can vent up. Hmm, now let me tell Abhinandan one more thing that this is the Pacific Ocean, it is the one from this side, it is smooth from above and fast in the row and is the first in the column, this is what happens or this is what happens. That this is a column, the collar is like this, it cries like this, so it is the first in the row and the first in the column, they told us that Pacific is the Pacific Ocean, where the sea is deaf, this entire ocean is not such a big business from here, friend, I will wait for some time. Well see, I am typing that my pan is a very cheap one and not an apple because you have ours, right, this is the Pacific nutrition, surrounded by here, meaning Reed, he had a land, something was surrounded by here, remember the Atlantic Boys. I didn't know that when I fall asleep, there are millions of messages and photos, so what do we need to know, all we have to say is that it has rained on all the buildings, one drop of rain has fallen on all the buildings. We have to travel only through defense method, DS Mathur means that then how will you know but we have to do metro, he said that here we have that line, a railway officer wrote here, look rank and North South East West direction. All four happened where there are all four tractions, where Forex goes, up, down, right, left, there will be defense, there will be debt. What does this mean, then watch the video of the commission on the button above, neither is this, I have said that we should Speaking Rice Traction To find out that the raindrop is here, this is my to my, tell me this is the raindrop can go here, this can go up, can't go, okay, for here, tell me, can go here Now she can try to find out in this but she told them to tell me only about those idols who have traveled all the way till here, had traveled from here, do it in this option and the same here. If I fall in this option while traveling, then I have to return only that drop in tax. You contest the same. If you have returned Kishore Rungta in tax other than that, then that drop is one drop, meaning drop is fine, I use Hindi for a little. Okay, so you can see by running the campaign here, now you come brother, okay, now one drop of cases fell here, five but smooth, now that's all, whatever I have given the answer, let's take us to this, which if The whole MB was the first avenger, I will do it for 1 hour everywhere, the same urine will go here too, here it will go here, we will go back and forth, up, down, back and forth, it will take an hour, so let me tell you in this way. Let me explain to you and I have been tortured by Vikram, it is okay right here, Giri, go this side only towards the Pacific Ocean, the frying drops, where to go, Pacific Hospital, try to go this side, she can go right now, that is, on the left side. And here it can go, here it has reached the height of Shri Building, here it is 3, from here it will do it, from here it cannot fall, not from here, that is, I swear to you, first here, day one, then it has come to two yards place now. Here, here, this experiment is done here too, if there are two, then it will be equal. He said that equal two will work, you can do it here, wherever the number is less, then you can do the final here, okay, now only this can be done here, Hinge. What is the sticker, it is only marine, if there is Atlantic option, then this one is our answer, then campaign coincidence, we also saw this strike here also, kind of above, kind of active, if it was not here, ours, then we saw while driving down. This is where our picture appeared that here it can fall on both the sides, so these five garlands, wherever this sector is 5, that is, whatever it has become intact, your measurement of zero and smooth 0.1, then here, which is A, which is the first in the answer. 0.1, then here, which is A, which is the first in the answer. 0.1, then here, which is A, which is the first in the answer. Zero is forgiven and has come but right now you I am trying to listen to you comfort erase it that I now let's go here okay now one drop if you know that world Jyoti Jagriti Rally who is this answer now this 20 asked this is them There is an answer, that's why the answer should be striker from here, this drop fell here, it went here, take the simple look, from here to here, if you want, then if it reaches here, then it also reaches here, it will reach this sea, the drop will fall and reach the Pacific coast, but On this side, when this side * here at the officer's place, the side, when this side * here at the officer's place, the side, when this side * here at the officer's place, the height of the building goes, okay, here she could move ahead, then this would not be the answer. Similarly, in this way, all these are also not the answers. Look here, this right here. But the drop fell on 4, Atlantic went here with its previous one, attend Atlantic, that man is absolutely fine, after that there are many equals here, she is less, she will go, from here, she went from she is here, she is less, she will go, from here, she went from 3 to free two. Because it is here that when I went from here to here, then it is not being compared with this and it is not happening simultaneously, it has already traveled from here, it is going from here to here. But on Pauri, if water has fallen here on the seat, here, that water will move from here to here, then half inch of it will be part of the comparison from here, don't you understand what I am saying now, we will have to leave the comparison starting point, comparison will happen here. Travel from here to here, this will travel a section of travel, the drop first fell from here to here, then from here to here, if it falls here, then compassion is the story, so I will take constipation from here to here. After that, you cannot go from here to here, if you do 38 exactly here, it happens, then you would have come, but here the building has become a little big, I am a building, sometimes bad, sometimes Tagore, then understand that it is okay, now I tell you good. When I am asking to go from here, these people have come here in large numbers, they do not give it here, that is why we do not have the equipment, only these two answers have happened, okay, neither is this, now that because how did this answer happen, this is France in this manner except saliva. It happened because here on the ruler side, try it, see this, then I will delete it, friend Buddha, first I have it okay, now we have seen that from here, you can remove the travel, brother, from here, surgery can be done from here to here, it is provided. Let's identify us in the team, this drop, this Patel, she has been identified, you will type from above, we will type from above, here it went from three, okay from 3, let's go here, it will go here, it went here and finally reached here, that's why this one. The answer is ours, if it was here also, then we would type this below, back and forth, up and down, that is why I am saying that if we find out the cells alone and not the letters alone, then it will take a lot of time, so at least understand this much and try the rest. Is it okay? I am trying to explain it very well in the box, there is no such thing, after that we can pure it, this is how we do it, we have done all the traveling and after that we still do n't know the main course or tell us the cash. That how Thakur place of both the countries is the right of readers to vote, just understand the question, it will write its own time and it is exactly similar to the one which you press on the button, scientific reason, simple and beautiful, it is the same point, this is the point, I have passed the Aadhaar number. Salt, both of us are SIM first, there is no code in it, there is no difference in it, only what is the problem in it, now you have understood that we have to find out only that which falls on both the sides, it goes away and we will do whatever we can to do it. The simple idea is that we will have to do something so that this brinjal of ours does not get trapped. It means that if this drop has reached here or has not reached here, then when I talk about this, I have talked about this bill. I have come, while completing it, I am on them, so I should not travel that thing again, that means I should adopt pass 262. If I have done both of these, I have done road travel, then I removed both of them in the answer, which of the two. Sounds can wear may be okay right at that time but I came to the third point further on this the third point my point came to Jyoti's head and from Chhindwara if she is not going up then I so that she gets stuck again So it is definitely there in the purse that if we had a record in it, then we had to know that our point should come to this point and go back and forth like this, how can I tell that when we have hit something and take it here. Whatever point we hit and we have visited it, we will store it in a piece of paper in Agri, we have already visited it, we will start the district of Tru, which we will westernize and make a bride, how will we do that in that? How will we make the destroyers, but you people, what am I saying in this, if you kill him, then what will be the benefit of killing, he got the benefit that we are there twice, he will not respect this thing again, so stop me individually, up, down, on. We will centralize, then we will kill him, then when we come here, we will move forward, back and forth, up and down, then we will kill him, because if you assume, if we did not mark, it is important to understand that if we did not mark, we checked this. Hmm, checked this, we checked this. Hmm, when we reached it, here we did not mark Jaimal Nagar, we made Abhimaan Kwath here, meaning I climbed it, the sign of the cross is installed here, I want you to explain it completely, it happened here, if that is my point Rehman, take that. He is travelling, if he gets sick, then he is going, then he is coming back, then he is going, then he is not coming to the office, he has been next, means to say, he is his mind, to say that he has told me that his Go near the one equal to, take the pole equal to, uncomfortable tan and request to go back to mom, so I am going, then from here, free her, from this point, I am writing to her that this one on the right side, please this point. From left to left and it looks like the nail will be stuck in this look, I told you the product, left to right, a paragraph, look at it, remove the top and bottom one too, how useless it can be to him that I will go here, will he ever go here? Music, that's why it is necessary to make it Kumar, this is the fabric rule, okay now, we will put it, now let's come to the court, let's take a look, then I will go and take a second video, it is too long, okay, let me show the admission, so this is the code today. There is a little bit of kumkum, hey, who is the cheque, how can I post it here, he is not counting my property as his, sorry, I will post a little, okay, it is done with you, okay, now carefully from here. Keep understanding guys, you will get a single line, before that I take this cord a little ahead of this one, if ever the need arises, now I have to go to the injection, then I can take this one, okay, first of all, do it, give a question in this. Is it okay to keep the entry of Pacific Atlantic, here you have dry ginger and this is Maithili, that is my habit, I do shows with dad's co-matters, sometimes it shows with dad's co-matters, sometimes it shows with dad's co-matters, sometimes it is okay, after that, if you keep the list of lists here, our answer will be there inside it. Our answer will be tow, it is a very normal thing, after that we took away the ones we had met, the roll was done in the name of R, the metro length and man should be checked. If it is everyday, it means that if you hit the mattress, not just a few, then you have given an empty box, then it is simple. I swear, we will also organize the empty boxes, okay, if it is not so, then we will check, we will stop and check for the lunch of the column, then we will do a longer check or if you know how or when the young man reaches to your place, then tell me this much, okay after that. Make layer two made one more interesting will do when we call one from here in the Atlantic question so that one made Atlantic that one just of a deep food which will give the crown Rufus and made one it is used to Davis right Manley two kind of a difficult will run Black dog for this portion of mine Let's go on a 21 day That for this portion of mine And let's go on a date That for this nutrition of mine Smooth so I But I have to tag us and both contractors in sewing on a date Check that both Which street in the country is there near me such a program, its drop is being given from both the sides, so we will check this thing, we will do Hmm Kumar, we will answer the question from where the drop is, if we assume that the drop is from here, the water buddhist is from here. This one is setting the whole thing, isn't it? You will make it a Kumar in each confession and in Airtel and in the other one, two drops of Atlantic have fallen in it, meaning it seems that Atlantic is falling in it, so this one Vijay has said in Hey. We will check the film of Kumar doing both of them will travel in both of them, we will check that if any such point is there in both of them, then it is true in both of them, if both the boys are true then they will accept the answer. Do you understand what I said this. Two, I say, Pacific and Atlanta, make them this layer, in one, I will install which point is my fabric, which point from where my drop is falling into the well and which point is mine, where Drops of Atlantic Roshan have fallen, I will do more chillies to find out the reason, I will call Pacific College, Delhi to decide if I will store it in a showroom or as a handkerchief, it is okay, after that I will check for the answer, which of the two addresses- If there is I will check for the answer, which of the two addresses- If there is I will check for the answer, which of the two addresses- If there is such a tweet, then it has happened in both, then what would be the meaning of having both, if not this, then this point has happened, the reason for this is obesity, both will be batter, if it has happened in both, then it would mean that from that point onwards, water has fallen in both of them. There is an alternative to this and I am studying this, I hope you don't understand so much, that's why I took it at two o'clock, on that I called here and leave it difficult, this I, if this, I had found out the answer which we would travel in the address. It is simple, I have traveled like oil for days, I have introduced onion and garlic till my breath, Pacific is equal to control and Atlantic is quite true, I am going to tell you how to do the true path, I am going to tell you as much as I am trying to explain the portion. Get it done or else I checked both the travels, so I made a list, put it in the answers, sent a list to the office, we will have to make a list, made a list, set me as a side class in it, and named it Answers to Test Your Answer. I have made a government by adding it to the return sir, so much fun here, now I will tell you this thing, before making it, I will tell you about the Dell school in the tips, but this is mine, all this is so cool, this is what happens, nothing else can be done in it. I have been here, I have passed it, I have passed Intali DJ, I have passed it, the organizer is IA's ID, this is some new user point, this is the point to watch IPL in 85 Pacific Ocean, which erases the alarms, now I know, this one is Pacific Ocean. Neither did he say that he is linking the money from here nor is he linking from here, I am linking from here and Atlantic and he is linking from here, the meaning of getting is from here, right. Isn't it, hey, there is some job on your face, which is this point, this is the point of five, he is leaving the dear tractor, so we don't mean to question, but we don't even want to see that it is here. When we reach Atlantic O'clock, the change in money is this portion, so we will do this, we will pass this point, when we call the factory guy, we will settle the doctors in this one, by the way, if we take the dough, then we will equalize this point, we will check. Will you tell us whether the water from here can go here or not? If a drop of water has fallen here in the Atlantic, can it go or not? Otherwise everything will be fine automatically. If it comes from here to the school, then there will be a growing virus. It will be spread all over, even by taking the check and contact till this end here, so we have called this point and from here we have called this point, now let's see what we have seen so far in the IPL. That the apps are passed at the time of passing any point so that this or that meal passed on that, give this program, that I took S2 here, Africa Atlantic that in this I have given this to that point, it will make it true or false, matriculation on that. I have given the previous set to those who have kept the matters in Dewar post inside, free website means what is the free website, why did I give more points, then to check, if you believe that I am one of the bowlers, then when a drop of water fell, this is water here. Will the drop of water fall here or not? You people, yes, as if it is erect, from here to here there is an ocean, so I am saying, whom will I contact at this point, you call it here for the track tractor. I will maximize the points, you guys will do it from my previous year, here you guys will do it from the previous one, I will do it because of this reason, you will say saffron, if you click on it, then when we will do it from these ones, then I am that now people from the sea Will you guys do it, brother, how will I describe the ocean in the attached form? I have a sea here, I need some points, neither will I agree to all these points. Why did I refuse because we have been told by the court that There will be an increase in the number of ambulances from one to 200. If there is any ghee in mobile - 200. If there is any ghee in mobile - 200. If there is any ghee in mobile - then you could have come there and taken minus one flight or else you could have asked for these teachers and minimum balance. If you call me Infinity then I have passed the mention here. Now leave it for now, I have mentioned this point so that it means that if the code is traveling from here like this, then this thing will also have to be compared with itself. I am cutting it from here, so it can go from here to here, from here it can go, this way it is fine, now try something in some time, I am going to tell you, made that powder and put it near 12345. Her main which is that while it is in this, a limited one, let me go to the job special, apply that simple that I have lashes, she has given me a beta recruitment job alert mother, so that the roots cigarette, recruitment 201 means that there should be no problem and the strong one is equal through it, brother in this. We have done the audit to see if that happens or Hi I am jobless. The new website means whatever height it gets, whatever hit it gets, it should not be less than its previous value or not because we are doing it this way, this is the way we go. Okay, neither that nor this minimum will turn it, so pass some time and think about what are the conditions written in this thing, from the beginning, you face it. Earlier, he had seen your waist or he must have done it earlier. The institutions will have to understand the story, what is written here is correct, then this is the thing, after that, if none of these things start, then there will be no return and they will do the real thing. Earlier it was said that they will come and stop that position, meaning if this position Why is it not there already? If it comes right down then first of all it will definitely open the conch shell till the next shell is easy for it to do because tell the office number. Started on it simply on the date by the top of the schools or on it up down amazing right- Left people, in this way we will right- Left people, in this way we will right- Left people, in this way we will get only those votes which are the first among the two, will this Amla or this bill pass or will this bill pass, now how is that passed, let's see how in this post. I am talking about this cream, email me in 1 minute that I will bring it on top of this, okay, now how am I talking about this portion, I have to do this one Bimba in the fabric, meaning this one column. Have to pass and this hero has to pass, now which is this zero, whatever is this, be the first and this is the tilak, this is the first kolam, so I passed that, I started from zero and started this disease, okay, one more low flame, I added Let us unite, take lemon juice and report till Kollam only, take one person, I have done the exam of this height to this extent, lemon of this head and in this height, what I show by becoming this in this disease, now tell this thing, what is the similarity between Pacific Ocean and Atlantic Ocean? That's where the corruption is starting, with Reed, that flat is fine, its simulated accounts are so much that both of them are starting from the diseases, one is starting from Rocky End, there is four breads, one is Rockstar, isn't it the letter, after that Atlantis How does Atlantic live in the set? In this set, I am getting through it and starting from the end, there is one volume of fast food and this kind of patience is not right, I have filed a long court for that. Wrote I to long which this is exactly us which I drove these people on a date for school in that I passed this a specific this passed Atlantic Oil Portion passed this portion from zero till today from zero till now in Atlantic I have used this portion from Row Minus One to Romance Lakh Aayi Tak Chikna A that I have set its photo here but now see if it is not in CMC then I have passed this portion in it and this post I have passed in it. That in this case, I have 16, so it's just this simple, in this you have passed it from zero to I, that is, by taking this index here so that its value changes and 10 injection request 30 this one, pass this nutrition decision here, see now this. Let's look at the question and - see now this. Let's look at the question and - see now this. Let's look at the question and - Man Ro - Man Ro - meaning 2012, this one, this Man Ro - Man Ro - meaning 2012, this one, this Man Ro - Man Ro - meaning 2012, this one, this Atlantic, passed here, so I should say around Atlantis in this, so here I have thought that romance is closed, meaning this question which is changing only this festival. This is on a festival, so this column that will run from here to here, na tera na and tips, this one is in fabric, this is steel from here, this is t-20 team, this is changing is steel from here, this is t-20 team, this is changing is steel from here, this is t-20 team, this is changing 012 so Look at this here, you have this here, now look here, many of these, here, let's see, now let's see what is in it, G20 means it has peels, what is left in it. The portion is being changed, so here it is zero till, this portion has been changed here, see what has come, Pacific, this question has come, after that Atlantic youth portion, this is quarter inch, look at this, it has dates in it, you have zero to one to three legs. Tattoo is mail, this portion is changing 012 What is steel here, this portion and this portion is changing, this is in Atlantica starting - that this is in Atlantica starting - that this is in Atlantica starting - that you can keep the internet mill here normally nearby, he told us in the option, no, we don't have anything, this It is said that if any negative balance token has to be activated inside it, then we can take all these in - can take all these in - can take all these in - but we can take all of them in mention so that we can compare with our previous element, we will take the environment element, so in this way all four Should be this one, and this one, smooth. You one, this one, and this one, smooth. You can write this in different parts, meaning I should be a little soft, that's why I wrote that in one call, both of these have passed in this tense and these two have passed in this tense. Passed, okay? After that, this is our answer, the song will come in the trophy. About this statement of ours, both the A's of this food will be broken into the matrix and the proof will come in it. When will we both take it together, brother, which of the two? Which ones are there to celebrate through, start making a list of them, button their contact, Planning Commission, if you like this video, then guys, it takes a lot of hard work to make it, how thick it gets, please give it a little pat, like and subscribe. I want to bring more good content, I am going to bring more good content to help you in the future, okay, everything else is in Hindi and if you want content in English, then message me back and comment so that I can feel that my audience is helping me. And this is it, you are studying as you are, okay, both of us move ahead after studying, okay, look at this in Domestic 229
|
Pacific Atlantic Water Flow
|
pacific-atlantic-water-flow
|
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_.
**Example 1:**
**Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\]
**Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\]
**Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below:
\[0,4\]: \[0,4\] -> Pacific Ocean
\[0,4\] -> Atlantic Ocean
\[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,3\] -> \[1,4\] -> Atlantic Ocean
\[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean
\[1,4\] -> Atlantic Ocean
\[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean
\[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean
\[3,0\]: \[3,0\] -> Pacific Ocean
\[3,0\] -> \[4,0\] -> Atlantic Ocean
\[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean
\[3,1\] -> \[4,1\] -> Atlantic Ocean
\[4,0\]: \[4,0\] -> Pacific Ocean
\[4,0\] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.
**Example 2:**
**Input:** heights = \[\[1\]\]
**Output:** \[\[0,0\]\]
**Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans.
**Constraints:**
* `m == heights.length`
* `n == heights[r].length`
* `1 <= m, n <= 200`
* `0 <= heights[r][c] <= 105`
| null |
Array,Depth-First Search,Breadth-First Search,Matrix
|
Medium
| null |
1,888 |
Sandeep in a favorable month and not avoid discussing beat problem one interested in this problem basically which only acting spring usko se most profit hips operation in the spring to first operations that fictional character of birth and death and simply pink character liquid 1 0 robbers Options Interesting Gift Operation Costs You Nothing But Has Taken To Patients Have To Win Every Flower And Corporation And Up To Type-2 Unit Have One Unit Certificate To Type-2 Unit Have One Unit Certificate To Type-2 Unit Have One Unit Certificate That Number Five Professional Edition Suggesting Begum Alternative Wasting Water Testing Something Like Which Is The Best Wishes 0800 Subscribe Se Sure Subscribe 1000 Subscribe To Hai Na Ho Aur Tumse Drishti Watering Way Can You Tight Operation On The Character Enemy And Elastin Flood Victims 102 Operation District Sambhal Solid Depositing 03392 Liquid Se Z F A Prestigious Directly Into This Invaness Problem Lash Growth Serum Ko 200 Rotations Karenge savere common problem exfoliate so whenever you want to say zinc one character from this and most odd friend 1628 dun karenge is net speed copco rotate vansh welcome to front invalid choice chief ne against rush vansh mode welcome to front and this video channel like this thank You All Possibilities Yes In This In A Program Will Have To Do With Sacrifice And Spirits Of Wood Benefits Services Seed Testing Asal Shifted Excel Sangh Ne BCA BSc Nursing Is Particular image024 image025 Chronic Third President subscribe and subscribe the Channel Please subscribe this Video Already Subscribe Two 200 Gram Actions Will Have A In Hand With Its One Convention Latest Indian Leader In Programming Languages Next This How Do We Programming Languages Next This How Do We Programming Languages Next This How Do We Call The Number Of Class 10th That Rotation In Hand Protests In Have No How Do Complete The Answer Is Famous And Certified In More Products Something of a tomorrow morning something right something that cord sliding window technique sliding window 167 m morning on an empty stomach is that I already have a chance of attack on window and slide window this sample don't again computer ancestor at arvind orange only six different sects and Only remove the index and it's quality left side me example to here were inco 2001 subscribe 2009 subscribe now ke andaroon band uske nature 1010 but one more thing but just focus 1010 ncc cadets 102 aa relative hai pm meeting whatsapp length free 34 lighting windows 7 Windows Simple and User Friendly Backstreet Boys' Answers Simple and User Friendly Backstreet Boys' Answers Simple and User Friendly Backstreet Boys' Answers Distic Collector Smack Like Detergent Mysore Account Is One OK Notice Live Wallpaper and Avoid Them and Welcomes Like This Member Next Rotation That Was Possibly Shift Necessary Swarna Famous and Now They Know the Answers Your Values Which Now They Know the Answers Your Values Which Now They Know the Answers Your Values Which Country Computer Check The Video then subscribe to the Key And One More Thing Person Door Window Viewers Properties Yushno Langar Bring Us Shabd Remove 27 Kidney Account Se Naam Par Is Deep Already Sanctioned And Cleared Your Account Inoperable 30 This Value List Did Not Cleared Up To Something else they can do for now being in power window ahead and width and subscribe the Channel Please subscribe and subscribe the one plate saver mode example south rs.100 can see you will gain 1008 computer rs.100 can see you will gain 1008 computer rs.100 can see you will gain 1008 computer operating systems for counting 1 to 100 in just one Example Subscribe Channel Subscribe Sir Account Sample 1999 One India And Was Not Given Window 10 2009 The Video then subscribe to the Page if you liked The Video then subscribe our Channel 100 A Positive And Always Mudslide In The Head And Went Please Check The current value absolute that is not conducted recently checked for watching prime and simply not doing so The Video then subscribe to The One 103 but most 10101 more possible to create a central character in the area where there is nothing but the alternative to start with that You Cigarette 1010 and Sacrifice for Distinguished Only 10 Entered Cigarette Provisional Loot Sandwich Subscribe and Afton President [ __ ] MP Vilas Name and Afton President [ __ ] MP Vilas Name and Afton President [ __ ] MP Vilas Name Shri Nandishwarai Loot Cutting How Many Types of Forest Land in This Spring A About This Account in Amla Settings Type Minutes Seconds Pages Thank You Want To Convert String To This Product Next 100 Very Time Tea Increment In This Valuable Time For This Channel Subscribe Now And Window Will Not Take Place Value Subscribe Divya Subscribe And Finally Bigg Boss 2014 A Saiya Let's Pretty Much Hai Or Pokemon Story After Proper Like and Comment Free Admission
|
Minimum Number of Flips to Make the Binary String Alternating
|
find-nearest-point-that-has-the-same-x-or-y-coordinate
|
You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'0'` it becomes `'1'` and vice-versa.
Return _the **minimum** number of **type-2** operations you need to perform_ _such that_ `s` _becomes **alternating**._
The string is called **alternating** if no two adjacent characters are equal.
* For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not.
**Example 1:**
**Input:** s = "111000 "
**Output:** 2
**Explanation**: Use the first operation two times to make s = "100011 ".
Then, use the second operation on the third and sixth elements to make s = "101010 ".
**Example 2:**
**Input:** s = "010 "
**Output:** 0
**Explanation**: The string is already alternating.
**Example 3:**
**Input:** s = "1110 "
**Output:** 1
**Explanation**: Use the second operation on the second element to make s = "1010 ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
|
Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location.
|
Array
|
Easy
|
1014
|
49 |
okay this is uh leak code 49 group anagrams they're asking to look through the string and then return an array of arrays that contain all the anagrams in separate arrays so how i approach this what you can do is you can create basically a little object map of this and while you're looping through the input array up here you can sort these different words check to see if the word already exists inside of this object and if it does then you can simply just push on to the array and then from there just return uh all of the values from the object so to code it out looks like this here's our loop so we're looping through all of these input strings and then what we'll do is we'll create a key and we'll use this key for this object here and what we're doing here is we're sorting these words as they come through let's see if i can't show that to you yeah see so e t get sorted to aet ant sorted for tan okay so now that we have the sorted versions of these words what we can do is check to see if they exist in the object okay so if it's not in the object set it to an array right so we're setting the value here in this key value pair to be the actual word because that's i right we're looping through strings so eat sort eat into uh into aet then what we do on this line here does aet exist inside of the object it does not so then oops this needs to be the object so then set the value to an array with just eat in it and the key is uh sorry the value is eat and the key here is uh aet so then from there we'll do an else and we will take that object key and because it's an array we can push onto it another i so if we can let's console log this out right now console log out object let's run this see what we get here we go so you can see it worked our key for aet has uh these values in it the key for a n t has these values in it so all we need to do now is return the values of that object so let's run this make sure i typed everything out correctly it works we'll hit submit all right got to get accepted there that's great and if i can zoom out here a little bit you can see all the code on one screen maybe that's a little small whoa come on chrome okay so that's all the code in one screen hope this was helpful if you like go ahead and subscribe and like all that good stuff otherwise see you next time
|
Group Anagrams
|
group-anagrams
|
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** strs = \["eat","tea","tan","ate","nat","bat"\]
**Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\]
**Example 2:**
**Input:** strs = \[""\]
**Output:** \[\[""\]\]
**Example 3:**
**Input:** strs = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strs.length <= 104`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters.
| null |
Hash Table,String,Sorting
|
Medium
|
242,249
|
233 |
hi it's Saturday June 20th 2020 my name is Noah Seeley and welcome to my channel today we're back with leak code I haven't really been spending too much time on lead code as I was before because I've been a lot more focused on the papers that we've been reviewing but I think a good way to start with it again is devoting Saturdays to solving a few leak code questions every week so welcome to the first official installment of leak code Saturdays today I'll be showing off two solutions to lead code questions one hard one easy the first being called number of digit one and the second being valid anagram so let's just dive right into them and check out what we're gonna be solving today so the first question is called the number of digit one it basically asks us to write code that counts the total amount of one digits that are in each number leading up to the input number so for example if I had the number 11 as input our output would be 4 this comes from adding a 1 from 1 a 1 from 10 and 2 ones from 11 so altogether four ones there are a few methods of doing this but it seems that within the discussion section for this question a brute-force algorithm would usually be brute-force algorithm would usually be brute-force algorithm would usually be accepted in interview like settings which is basically what I have coded here for you guys in Python this little algorithm here will run a Big O of n times log n time complexity and will basically exhaustively check how many ones are contained in each number counting up to the input with these two lines of code highlighted here we can do these checks basically we're casting each digit as a string using pythons string cast function and checking if it's a 1 and then iterating a variable that we have for counting the ones once we run through all of the numbers up to and including the input number we can return that count variable and there you have it so moving on the valid anagram question asks us to write a script that can determine whether two input strings are anagrams or not an anagram occurs when two words use the exact same letters but in different orderings for example the word state and taste so there are a few ways that we're able to solve this but they all have to do with isolating each letter separately in the word and then comparing this isolated set of letters with the other word set if both sets match then we return true and if not we return false so here's the code and basically I went for an approach where we sort each word by letter and then compared the sorting so we can see that those sorting --zz act we can see that those sorting --zz act we can see that those sorting --zz act as the isolated letter sets so as you can see here instead of having to manually sort the words which would be done by running through letters in each word and putting them into an alphabetical list I used pythons string sorting function this will simply sort the input string into its sorted version alphabetically we then compare each sorted string and return the proper corresponding boolean value pretty simple so yeah that's the solutions to the questions number of digit one and valid anagram problems on the code comm it was a short and sweet Saturday video but that wraps it up for today as mentioned I'm going to start making these Saturday videos devoted to solving a few li code questions that I see throughout each week once again we've used leet code comm to find these problems so as always I've linked all resources that I've used in the description below for you guys to check out yourselves if you feel that I've missed anything or got anything wrong please let me know in the comment section below that's it for today thanks for watching see you tomorrow
|
Number of Digit One
|
number-of-digit-one
|
Given an integer `n`, count _the total number of digit_ `1` _appearing in all non-negative integers less than or equal to_ `n`.
**Example 1:**
**Input:** n = 13
**Output:** 6
**Example 2:**
**Input:** n = 0
**Output:** 0
**Constraints:**
* `0 <= n <= 109`
|
Beware of overflow.
|
Math,Dynamic Programming,Recursion
|
Hard
|
172,1068
|
1,694 |
welcome back friends today we are going to solve lead code problem 1694 reformat phone number uh so before we start looking the details of this problem uh i just want to mention that i often create lead code solution videos and if you are like someone who is preparing for a job or you are learning java or you are interested to learn java or preparing for coding interviews so this channel is for you please subscribe to this channel it has a lot of good material so please go through the playlist that i created you know it will definitely help you in your interview preparation so please subscribe so let's look into this problem quickly so you are given a phone number as string number consists of digit spaces and like this apostrophes and dashes right you would like to reformat the phone number in a certain manner firstly remove all spaces and dashes then group the digits from left to right into blocks of length 3 until there are 4 or fewer digits the final digits are then grouped as follows right so we have to group uh the numbers into blocks of three as much as we can until there are four or fewer digits left that's what they are saying so if after uh we are done with creating the blocks of three length so now whatever is left we have to do this with the left leftover characters right if two digits are left then we will create a single block of length two okay if the three digits are left then we will just create a single block of length three and if four digits are left at the end then we will create two blocks of length two each the blocks are then joined by dashes notice that the reformatting process should never reproduce any blocks of length 1 and produce at most 2 blocks of length 2. return the phone number after formatting right so they have given us three examples over here and five examples and uh you know we can uh start looking into this example first and then i will explain you simultaneously how we are going to implement this so basically as the problem states that we have to first continue processing the blocks of three right so the number one step is we will remove all the dash characters right this we have to remove spaces and dashes so what we will do is we will i just took these examples over here so we will actually take this let's say this is our input string right so this is our input string so we will just take this string and we will just remove this character from that string right so we are going to remove this so now our and we will keep these characters uh which are digits right into a list so now our list will have this one two three four five six seven eight right because we removed that dash so it will have five six seven and 8 so this is our list we will create list of characters and we will hold the numbers in the list so once we are done then what they are saying that we have to process three uh digits until uh you know like until four or fewer digits are left right so we will keep until four or five four digits so we will start processing this now so we will first process this one two three then we will have one two three like this right we will use a string builder class so this is a java string builder class we will use because we can create dynamic strings using string builder and it is very fast so we will use string builder class so after every three now uh we will put a dash after uh every three right and then now we will be left with five so which is greater than four right greater than four so it is fine so greater than four means we can continue three again so we will again continue with this three so four five six we will put dash after that now after that two characters are left into our uh list right so um we can use the list dot size method because you know we are actually going to be like for example we are going to be following the list right list.paul be following the list right list.paul be following the list right list.paul method is there so call method will remove the character so when we are doing this one two three we are removing these characters from the list so when we are reaching here then we only will we will be left with character 7 and 8 into our list whose size is 2 right so now the size here size is uh 2 which is not greater than 4 right so we have to take this 2 and make a block of 2 characters and append it here so that's what they are saying right 2 digits means a single block of length of 2 you have to do basically so that's what we have done here so we will take 78 and we'll append it here and we will just use stringbuilder2string method and we will return this string as our answer right so similarly if you look at this another example here also we will have one two three four five six seven so first we will create a list here so again our list will have one two three four five six seven uh four five six seven and then once our this is list of characters and because we will remove this right this is special character we will remove it when we are creating a list and after that we will want to always group it in the block of three right until there is a until size is greater than four right size is greater than four so this is size okay so um so you can consider now the first three characters here because our size is greater than four so we will take one two three we will append it to our string builder and then we will put a dash after that right now our leftover list has a size 4 this is our list leftover list now and its size is 4. so 4 is not greater than 4 so in case of 4 what they are saying see we have to create 2 blocks of length of two each so which means that we will create two blocks four five is one block and six seven will is another block so we will put four five here then dash and then six seven here right so that's what we will do and in this last example that i took here again we will do one two three which is this first one two three we will do and the leftover uh is still three which is uh three is greater than not greater than four right so we will take the three characters and append it here because that is another thing like they are saying that if three digits are left over just create one single block of length three so that's how we are creating this single block of length three and we will just use string builders to string method so this is how we are going to solve this problem of reformatting phone number so this is kind of uh for junior developers position this kind of problems will be asked you know like to understand if you understand and use linked list and you can understand string builder like those things will be tested in this problem so let's go over the code quickly so as you can see first we have created a list of a link list of character here and then we are just reading this number string basically whatever is given and if it is a digit basically we are checking is digit method is there in character class of java so we will just we just want to take digits right one two three four so we will just put those digits into list right so now our list is ready so we will just create a string builder here and while our list is greater than 4 right because that's what they said that it should be here right there are four or fewer digits means we have more than four digits we will just group them in three group of three right so that's what we are doing here so we are taking group of three and we are just list.paul will take we are just list.paul will take we are just list.paul will take each character out so we are looking from 0 to 3 so it will group 3 characters right in every iteration and after that it will put a dash here so it will keep doing it until the list dot size is greater than 4 so once we come out of this while loop then it means that now list has at most four characters left basically so what list can be left with two characters or three characters or four characters so now we will just handle that situation here right so now the if the list is left over has less than four characters right means two or three basically here see so it is less than four so in that case we will just append that leftover characters to our string builder right because for two and three we don't have to do anything like just as it is we can uh just uh append it to our string builder the only thing we have to do is in case when we have four digits left right in that case we have to create two blocks of two basically so that we will do here right in the else part means leaf list dot size is four means leftover list is four so in that case we will just fall two characters here means this is one block we will put a hyphen and again we will put another block of two and at the end here the list will be empty right because we are done with all the characters we will just return sb dot to string so this will give us the answer so let's just look into the test cases here so these are all the test cases so all like as you can see this is also big test case so we'll just quickly run our code and make sure this is working fine so our code is working fine so as you can see like three then here two of four characters are left so it is taking two characters right like that basically and in the first example it is just three characters and in this example one two three and four characters are left so it is creating block of two basically so our solution is getting accepted so we'll just submit it so our solution is 97 percent one ms which is pretty good so this is the way you can solve the problem reformat phone number with the help of a linked list and string builder so just one quick summary so you just created at least first list of characters you created and then using string builder you just processed all the uh blocks of three until you have uh four or less than four characters left in the list and then you just create uh either a block of two or three digits here or in case of four you created two blocks of two digits here right so that's it so that is the way you can for solve the reformat phone number so as you might already know you uh you know i have already created a playlist for lead code solutions which has over 55 problems solved with examples and java code so take a look you will learn a lot there also there are a playlist related to you know java programming skills where you can improve your skills like you know bfs dfs you know breadth first search depth for search uh binary search trees binary trees then dynamic programming link list hash map so all those data structures uh will be helpful for you in your interviews take a look at the list and learning uh playlist and also subscribe to the channel with subscription to the channel will be really helpful thanks for watching the video
|
Reformat Phone Number
|
make-sum-divisible-by-p
|
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or fewer digits. The final digits are then grouped as follows:
* 2 digits: A single block of length 2.
* 3 digits: A single block of length 3.
* 4 digits: Two blocks of length 2 each.
The blocks are then joined by dashes. Notice that the reformatting process should **never** produce any blocks of length 1 and produce **at most** two blocks of length 2.
Return _the phone number after formatting._
**Example 1:**
**Input:** number = "1-23-45 6 "
**Output:** "123-456 "
**Explanation:** The digits are "123456 ".
Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123 ".
Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456 ".
Joining the blocks gives "123-456 ".
**Example 2:**
**Input:** number = "123 4-567 "
**Output:** "123-45-67 "
**Explanation:** The digits are "1234567 ".
Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123 ".
Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45 " and "67 ".
Joining the blocks gives "123-45-67 ".
**Example 3:**
**Input:** number = "123 4-5678 "
**Output:** "123-456-78 "
**Explanation:** The digits are "12345678 ".
Step 1: The 1st block is "123 ".
Step 2: The 2nd block is "456 ".
Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78 ".
Joining the blocks gives "123-456-78 ".
**Constraints:**
* `2 <= number.length <= 100`
* `number` consists of digits and the characters `'-'` and `' '`.
* There are at least **two** digits in `number`.
|
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost index for every prefix sum % p.
|
Array,Hash Table,Prefix Sum
|
Medium
|
1016
|
79 |
Hello hello everyone welcome to my channel todays 121 any problems but such a very famous problem interview saudi duty world and avoid the world can be constructed from letters click subscribe button decimal should not be used for example for this is the giver problem and subscribe tomorrow morning To Search All The Character Of This Word Which App Ve Singh Faujdar Addison Rules And Provide Enough Condition Problem Solve Will Do First Will Look For The First Character Thursday Will Continue For The Character Subscribe Distraction Restriction In This Session From All Directions And Subscribe No Pati This Tags This Show We Are Not Able To Find A Second Character This World Does Not Exist A Gift From This Will Continue For The Like Share And Subscribe Our Channel No Will Do That Thing Again For All The Way Descended From Starting From Share And Subscribe Do subscribe channel share video and subscribe and decided not to withdraw from your second character already no veer inform this word from hair pack to retail deficits subscribe channel subscribe school 204 mein aa i20 i lash 10th board Dot like and half inch plus point J-20 this is for all the 100 number of columns and subscribe our Dr. V0 this but any particular gets a strong global stance and subscribe become bird and deposition subscribe Indian village in this world will be written in offices Se cigarette info flashlight implement it exists helper method which will be written in a inside we this MS Word the in which tired video character board inter identity jan10 trimming word that hindi in position in opposition of the word doc 100 to hair first visit to Check Effigy To The Not Already Written Words Like This Is The Third Form Of The Second K Scan Dubai Which Possible Benefits Check Weather Obligation Xavier Processing Currently In Life Don't Like Subscribe And Width Verse Of This l210 - 105th Round 100 And I Great Daily Ko Switch Board Dot Length Aur Cigarette Daily Urdu Board Of Cheer On Daughters Will Cover All The Country Which Is The Best App Na Ho Sorry For The Current Position Manager Kevin To Check Only A Bird Carrot Position Is Not Equal To The World In our current board index board that I got the mosque in that case like we were not finding get current character matching with r current Indian law board and being in return for no the life but still under the great and director got this current position character from the collector And Subscribe I Will Use This Temperate Corrector First Holdii Collector Order Corrector And Gautam Ji Indian Updates Will Work For Liquid Video Subscribe Possible And Subscribe Avoid Position Will Do And Of The Richest Village A Return To Insert In Branch Letter Haldi I - 110 I - 110 I - 110 A And B third branch let's call the They should basically subscribe like and share sent a message simplex implementation of this problem has tried to compile our code main hoon yaar isse compile hai beech-beech mein is hoon yaar isse compile hai beech-beech mein is hoon yaar isse compile hai beech-beech mein is type spelling type vo samaj line number this is it line number 321 line number Three Liquid Soap This is So Let's Sheet Compiling and Settings of Vijay Jain Shwetambar Code Accepted Subscribe Me Solution Please Hit the Like Button and subscribe To My Channel thanks for watching this
|
Word Search
|
word-search
|
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
**Example 1:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED "
**Output:** true
**Example 2:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE "
**Output:** true
**Example 3:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB "
**Output:** false
**Constraints:**
* `m == board.length`
* `n = board[i].length`
* `1 <= m, n <= 6`
* `1 <= word.length <= 15`
* `board` and `word` consists of only lowercase and uppercase English letters.
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
| null |
Array,Backtracking,Matrix
|
Medium
|
212
|
1,773 |
hello everyone welcome to another video and in this video we are going to look at a very different question now this is important because we need to understand how to access uh um a value inside a 2d Vector okay now um let's jump straight into the explanation first okay uh so what is what we are given is um let me what is this yeah so first we are given a vector of strings okay we have three values first is type second is color and then we have name okay and we are given rule key and rule value okay now this rule key it's it tells us like what we are looking for are you looking for type are we looking for color or are we looking for name okay and this rule value it tells us the exact value that we are looking for is it like for example if it is color then are we looking for blue green red black whatever okay so we need to find such pairs or such uh elements that follows the given requirement of our rule key and Rule value okay now how will we do that so the first thing is um let me just remove all this okay so the first thing we need to uh take care of like taking consideration is that um type color and name every time at each at uh every Vector okay type is going to be at zero thickness color is going to be at first and name is going to be at second index okay so this is quite significant for us because using this we will be able to find a key now what is this key it will help us to fetch the value and compare it with our rule value okay um it will be easier to understand from code so let's jump into it so as I said first we need a key okay we'll compare this key if a rule key if that is equals to type in that case RT will be equal to 0 else if our rule key if that is equals to color in that case our key will be equal to 1. else if the rule key is equal to name and K will be equals to okay now we need to go through uh the list that is inside uh I'm sorry the vector that is inside okay so for that I'm good Vector of string let's say temp in items okay now here we'll see if temp of key if that is equals to rule value that is uh the value in temp that is now the for thus this is our temp okay in this we have our key okay 0 1 or 2 so 0 is this one is this and 2 is this so if temp of let's say 1 okay that is color if it is equals to rule value that is let's say B uh blue then we'll increment our count and at the end we'll return our count okay uh one more thing let's declare and initialize okay uh let's submit this okay so it was that easy let's not worry about the time complexities and everything as of now okay going forward will we will be taking care of that right now as you can see our run time is 154 Ms which is not an ideal thing to do okay um but uh let's not focus on that right now we will simply we are simply covering the fundamentals right now okay the basics that how we are going to solve these questions okay going forward we will always be looking at uh two solutions one will be our Brute Force approach and the other one will be our optimized approach okay so that's it for this video and uh do let me know if you have any suggestions or any queries for me to solve from any other different platforms okay so yeah thanks for watching I'll see you in the next one till then keep coding
|
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,573 |
Hello hello everybody welcome to my channel it's all the record problem number of best to split string to give energy subscribe ltd Video then subscribe to the Channel Please subscribe number of characters of Islam in one to three servi please attend a lot and 251 087 total number If wave in this is 320 can only move one in which of the subscribe number one in all subscribe to 154 convince kathir volume total district in different subscribe this Hair wave sleep is the number of switch off shri 1008 equal number of one two three Boys subscribe The Channel subscribe and subscribe the Channel and subscribe Shubhendu number please payment is want you back tomorrow morning tucker-tucker 54 cut is this edison and tomorrow morning tucker-tucker 54 cut is this edison and tomorrow morning tucker-tucker 54 cut is this edison and swadeshi liye more clear morning have spring 0 two plus two cats and bf3 people poses 3.3 two plus two cats and bf3 people poses 3.3 two plus two cats and bf3 people poses 3.3 places two cut So How Will Place 1362 Will Choose To Out Of Three Swadeshi 30 To Which Is 3 And Says Have A String With Five Sure Hindi Se String Phase Have Four Places To That Sort Of A Is Four Places Which Can Choose To Places Where Mintoo Products For The Number of this point to which is for factorial divided by two factorial and two factorial quick open this will give oo subscribe dishes feminine and 15010 this is including 100 number one and let's go for this channel subscribe number one industry 12345 6021 If you subscribe to subscribe and Share and subscribe the Channel subscribe share and hair morning have three places to visit in this point and chronic two three four bf and places to cut will sleep multiply all of the state handicapped and places bindhe string In 12th Science and Research That is AIDS Patients Equal Number of One of You Will Solve This Problem Solving 1st Number One Wife 600 Will Check Subscribe - 2nd Like - Two 1 - 2 Subscribe - 2nd Like - Two 1 - 2 Subscribe - 2nd Like - Two 1 - 2 That Divided by Two Number of Wells and Similarly is This One Is Not Model Developed 3032 Number 90 Number One Two Three Idiot Number Three Weeks He Twos Soul Will Take One 's Wife Pim Verbeek To Find Number Of Places Where 's Wife Pim Verbeek To Find Number Of Places Where 's Wife Pim Verbeek To Find Number Of Places Where One Third Of One Is The Will Start From A Given Number Valve Vapor More This One Third Will Be Getting Some Will Be Valid For Third The Best Fennel Instead * So Valid For Third The Best Fennel Instead * So Valid For Third The Best Fennel Instead * So A Number 62 F Subscribe Scouting One A Number 62 F Subscribe Scouting One A Number 62 F Subscribe Scouting One Not To Tell This Dish Will Start Doubting Well Being Born In Students Will Be Similarly After 10th Urs Know No One Will be from subscribe for court will need wave live 1000 tech subscribe no need to be id flights where are different ways of representation to right december subscribe like this is the meeting Thursday ko widro character c in add karo to take care 140 characters 0 country wise subscribe The Video then subscribe to subscribe our Channel Ko Bill Gates This Prayer Will Multiply And Minus One Star N Is - 2 And You Will Be Divided By Two A Is - 2 And You Will Be Divided By Two A Is - 2 And You Will Be Divided By Two A Vector Product Will Be Divided Into And After Date Of Birth Model With Decision 200 Direction Will Take Also available on all news channels will result in case of wave tabs long gown and one-third is lineage divided by three loot veer vyatit and one-third is lineage divided by three loot veer vyatit and one-third is lineage divided by three loot veer vyatit a model with three is not seervi subscribe lage the 120 tours and different wave from long way from being Used For It's Not Give Vote To Subscribe Will Update Please Join This Page Tuesday In Case Of This Will Welcome To * Tuesday In Case Of This Will Welcome To * Tuesday In Case Of This Will Welcome To * More Than 130 Number 19 Number Subscribe Will Be Strong To Do Subscribe Sid Know What's The Time Seervi Jo Arm To One Between Fennel and Space Complexities one-by-one in this contest Like Complexities one-by-one in this contest Like Complexities one-by-one in this contest Like and Subscribe my channel Thank you if you have any questions please read and thanks for watching
|
Number of Ways to Split a String
|
find-two-non-overlapping-sub-arrays-each-with-target-sum
|
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** s = "10101 "
**Output:** 4
**Explanation:** There are four ways to split s in 3 parts where each part contain the same number of letters '1'.
"1|010|1 "
"1|01|01 "
"10|10|1 "
"10|1|01 "
**Example 2:**
**Input:** s = "1001 "
**Output:** 0
**Example 3:**
**Input:** s = "0000 "
**Output:** 3
**Explanation:** There are three ways to split s in 3 parts.
"0|0|00 "
"0|00|0 "
"00|0|0 "
**Constraints:**
* `3 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
|
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.length. If you are still stuck with how to build prefix and suffix, you can store for each index i the length of the sub-array starts at i and has sum = k or infinity otherwise, and you can use it to build both prefix and suffix.
|
Array,Hash Table,Binary Search,Dynamic Programming,Sliding Window
|
Medium
| null |
226 |
hey friends welcome back to another leetco tutorial if you are new here my name is anar and i'm a self-taught my name is anar and i'm a self-taught my name is anar and i'm a self-taught software developer that makes content to help you break into and grow in the tech industry today we will be solving lead code 226 invert a binary tree there will be a whiteboard component where i explain in detail exactly how the algorithm we're going to implement is going to work and then there will be a coding component where we actually implement it before we get into that though a gentle reminder to subscribe to the channel so you don't miss any of my future content so in order to solve this problem there's one specific thing that you need to understand clearly and that's treat reversals in our solution we're going to be using depth first post order traversal and let me show you how that works so with the depth first traversal you actually traverse to the bottom of the tree to its leaves a leaf is a node that doesn't have any children the first time you actually process a node is when you've come to the bottom of the tree in a depth first traversal you recursively walk down the left notes and then when there's no more left notes to walk down you walk down the right notes let me show you what i would look like you start off at the root note then you walk to the left node from there you once again walk to the left note then from this node you try to traverse the left but there's nothing there then you try to traverse the right and again there's nothing there what makes this a post order traversal is that you operate on the note after traversing its left and right children so in this case after trying to traverse the left and right children of this node you would actually perform some sort of computation on it once that's done you pop back up to this node and you go to its right child once on this node you would try once again to go left then you would try to go right and then you would perform some sort of operation on this node then you pop back up to this node since this nodes left and right children have both been traversed you perform some operation on this node then you pop back up to this node since this note left children have all been traversed you go down the right node from this node you go down the left node from this node you once again try to go left then you try to go right and then you perform some operation then you pop back up to this node and you go down to the right at this point you once again try to traverse the left then you try to traverse the right since there's nothing there you do some operation on this node from here on you pop back up to this node and since both of its left and right children have been traversed you perform some operation on this node now finally you pop back up to the root note again and since all of its left and right children have been traversed you finally perform some operation on this node what the actual operation is fairly irrelevant in this problem we'll just be switching the left to the right and the right to the left the part that you actually need to understand is the tree traversal not the switching of left note to right node let's try to actually code this up now the simplest way to do tree traversals is using recursion so that's how we're going to do it here anytime you're traversing a tree recursively you want to start with the case when you actually hit the bottom of the tree and the left and right nodes are null or none so we start off with if root is none return none what you return doesn't matter the reason you need to return something is so the recursion stops when you reach the node that doesn't actually have any left or right children instead of actually traversing into a non-value and getting an error non-value and getting an error non-value and getting an error then we're going to do our recursive case self.invert case self.invert case self.invert tree root.left tree root.left tree root.left self. since this is a post order traversal whatever operation we want to perform on the node is going to go after the two recursive calls just so you could see the tree get reversed i'm just going to print the node and then as you actually come back up the tree you want to return the node you're on if we give this a run you could see the actual tree traversal happen so the first thing we print is one which is this because it remember goes left then left right there's nothing there then it performs the operation then you have three because it goes back up and then three then two and so forth i explained this on a whiteboard so if you need to revisit that go ahead and do so now the only thing left is to change the operation we do on the node at the moment we're just printing the node's value what we want to do is swap that out with making the left node the right node and the right node the left node this is fairly easy to do you create a temporary variable with root.left then you make root.left with root.left then you make root.left with root.left then you make root.left equal root.right and then you make equal root.right and then you make equal root.right and then you make root.right root.right root.right equal 10. if we submit this you see it completes so again the reversing part is very simple it's the tree traversal that you need to understand if you enjoyed the video don't forget to drop a like and drop any questions you have in the comments section that'll be it for today and i'll see you in the next one
|
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 |
1,773 |
hello guys my name is asala and welcome back to my channel and today we are going to solve a new lead code question that discount items matching a rule so we will be solving this question with the help of JavaScript the question says you are given an array item each where each items I is equal to type color name describe the type color and names of the ith item you are also given a rule represented by two strings value so we will be given three things in the question first of all we will be given an array which is which includes item secondly we will be giving two strings the first is the rule key and third one is Rule value these two are a string so what role they gonna play is that the ith item is set to match the rule if one of the following is true if rule key is equals to type and Rule value is equals to type I then we have to return account to increase by one if these three condition match we have to increase the count by one so return the number of items that match the given rule so if you haven't understood the question let understand it by the uh by the question here by the example number one so these two are strings first is Rule key and second one is Rule value so we know that by question that at index 0 with the type index 1 represent color index to represent name so this is type this is or color this is our name so they are saying that on each individual eye so these are I one two and three these are all I okay so we have to check in each individual eye whether they are meeting the condition of rule key and Rule value if they are then we have to increase the count by 1 and return that return the final count so how do we do that first of all we will be checking the color pool value color so means if the question is given as in the question the rule key is color and color is which Index this index blue silver and gold so in all these three I it will check for which it will check for rule key if these three values and in rule color if it is matching with rule value which means that it's a silver so if it's silver then we have to increase it by count by one so only one there is one I which is I number this uh this is the one and if because this is only matching so we will increase it by count and return that final count similarly in this question you can see that there are three items here or L also will burnt 2 3 and here that rule key is type so we will be targeting this these three one two three because these three represent the type and we will go on a check that they are phone or not if they are not phone then we will not increase the content therefore we will increase the quantity we will increase this is fall and this is computer so when here it will be count one then again 1 plus 0 there it will be 0. and 2 so we return two if you see this in the in this whole I item there is also a phone at the bottom but at the last but we are not counting this because this is not matching the type because it's not matching the type it's matching the name so it's a name value not a type value that's why we are not increasing the count so let's do that so just before starting to solve this question guys 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 first of all I will create account variable that count is equals to zero and this count variable I'm gonna return the return code so first of all I will check this condition if rule key is equals to type if rule G is equals to type then what we have to do we have to create a loop for let I is equals to 0 I is less than num start sorry item short length items dot length and I plus now in this I will check means if this is if rule key is What rule Keys type so we are targeting these three values one two and three these three values so if it's type and it's matching with rule value if rule key is type and it's matching with rule value so what we will say that if uh items zero what sorry items I and at 0. okay so items I add 0 means these are my eyes one two and three one to 2 and 3 these are our item at zeroth index so each items I at zeroth index these three my item for example number one and now if this these this condition you have to write is equals to here as well is equals to what is equals to rule value if it is equals to rule value then we can increase the count by one so I will say that count plus you can also write count plus is equals to 1 both are on plus is equal to both are correct you can write either ways I prefer writing count plus because it's much easier and shorter to write so if this is true then right count by one that means just select this whole code here and just paste it three times because I have to check for three values okay so I have pasted three times let's shift this whole section to the left side and now instead of type I will write second is my color so I will add color and their index is not zero it's one and I will change this as well and I will see that instead of type write name and instead of 0 I will write 2. so this was all in it let's run it and check so I made some mistake here let's check what we are making out stick here rule one rule 2 and count plus let's see what the mistakes we are waiting is this and the account is equal to n type is equal to uh so what you have done is there we have to attend the length spelling incorrectly if you put it early and GTH instead of that l e n g uh so we made a mistake in length and the n g t h GTS now it should run fine and run it so you see that it's working fine and we have got an answer so this was all in the question guys still you guys have any doubt ask in the comment section and if you've liked the video please do like the video if you would like the video please do comment in the comment section that you have liked the video thank you guys for watching the video see you next time
|
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,877 |
Hello friends welcome to my channel here I solve L problems and prepare to the court interview today's problem number is 1877 minimize maximum PIR sum in Array the PIR sum of a pair and a and b is equal to a plus b the maximum pair sum is the largest pay sum in the list of payers given an nums of even length N Pay up the elements of nums into and divided to two pirs such that each element of nums is an exactly one pair and the maximum pair sum is minimized Returns the minimized maximum PIR sum after optimally paying up the elements let's check the examples in the example one we see an array with four numbers 3 5 2 3 you can see that if we pick up the maximum element it's five to get minimum pay P sum we need to pick up the minimum elements and add it to five in our case it's two so to get optimized pair we need to get maximum element and add the minimum element to it and after we need to pick up second element after maximum and add the second element after minimum and so on so first of all we need to sort the input array nums to so we can easily get maximum and minimum elements let's do it to sort array in Python we can use method sort after we need to Define some variable for result here we will keep the maximum PIR sum and return it else it can be helpful to get number of elements in nums so let's define it after it we need to check all payers to do it we need use a loop and goes through IND indexes from zero to n divided by two and uh get two opposite elements from Maximum side and from minimum side let's do it for I in range n divided by two current pair sum equal to nums of I plus opposite element nums of n i - of n i - of n i - 1 for instance for I = to 1 for instance for I = to 1 for instance for I = to 0 nums I nums of I will be zero nums and the opposite element will be nums of n minus one and finally we need to update result it will be Max maximum of current result and the P sum so after we check all elements we will get the maximum value of P sum in the result variable and return it let's check the tests test passed let's submit it works and uh pretty efficient so finally let's check and analyze the time complexity of this algorithm first action was the Sorting the sort algorithm has time complexity of n log n second part we go through all elements in Array so it has time complexity of so total time complexity is n log n+ n in Big O notation we use only the most significant part of expression so in our case total time complexity is n log n so it's pretty good result and uh good complexity that's it for today thanks for watching see you tomorrow bye
|
Minimize Maximum Pair Sum in Array
|
find-followers-count
|
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
872 |
hey everybody this is Larry hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's problem leave similar trees have I done this before no worries I haven't not recently so okay so today's prime is leave similar trees easy hit the like button and subscribe and join me on Discord let me know what you think about today's Farm uh I'm a little bit tired today so I'm not gonna do a bonus question I was doing a really old Advent of code problem and ah there's so much reading I missed one line of uh of instructions and that took me like two hours to debug um so kind of hard sometimes Advent of reading very carefully apparently anyway today's five minutes leave similar what does it mean so considering all leaves are buying entry from left to right to browsers she the values of these those leaves from uh leave value sequence I can't read today either so you have six seven four nine three two binary trees are similar to the same okay um okay so I mean so the um sorry I got a message so that sounds good I mean I think the um I was gonna say that I've I think you could do them co-currently but actually now that I co-currently but actually now that I co-currently but actually now that I think about I'm not sure I mean you could kind of still do it that way but there's a lot more uh tracking I think that it I don't know that it's worth the extra complexity um and kind of the example one is kind of what I was thinking of okay well you have to do some things to get to the next leave and I don't know and then you have to kind of keep track of states and uh maybe you could do it with um explicit stack and kind of do it that way to get the next Leaf but I feel like that's too complex and I'm just gonna um the short answer is just get a relief and then compared to the two frames and I think that's gonna get so I'm gonna do like a construct leaves um of you know right and then maybe just like you know in a way of values right and then here we have a traversal it seems like we're having a tree well actually let's say it was linked list right I don't remember anymore uh my I've been I need more sleep maybe oh I'm just tired maybe more naps I think I felt like I slept yesterday but I don't know but anyway so yeah so here we just checked to see if the leaf if leave that left is none and no doubt if the left and right no Jannah and then this is a leaf so then that's just a pen note that value right um and then uh well I mean in field you should do a pre-order but pre-order but pre-order but and what I mean by that is put it here but obviously this can only happen if uh if this is a leaf which means that these things are kind of uh mutually exclusive anyway so yeah so then now we need to return R and then we just return construct leaves of fruit one is equal to construct leaves of food too but and it will do a pairwise comparison uh hmm Okay no Okay let's just put it all down don't mess something up yeah that's what I expected it was matching on but that's still not great is this magic on the same thing okay huh hello they should hit at least once right or am I just doing something silly notice none oh I am doing some recently I forgot to call this function okay Larry silly lie all right and there's an easy bombs I am confident about it except yeah you know if I would have submitted it if the test cases was a little bit more uh whatever but uh yeah so this is linear time linear space um all right guys yeah I mean you know if you have a full uh tree or a complete tree I suppose then you're gonna have n over two leaves right so that's linear space and that's the size of your output or that's you know that's the size of this thing so um yeah that's gonna be the size of the output and that's not the size of the output but that's the size of this thing anyway so um yeah and in terms of space you really can you have to do either one anyway right I mean what I mean by that is that if you um is off the depth of the tree I'm really off today sorry friends I need to take a nap before doing the Avenue but yeah um it's gonna be linear anyway uh for time because you don't have to look at every node and for space um the uh traversal is going to be o of H which is going to be linear I suppose depending how you want to say it so yeah um that's all I have for today let me know what you think stay good stay healthy took your mental health I'll see y'all later and take care bye
|
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
|
1,300 |
Hello Everyone So Today Bill B Discussing Question No. 1300 Need Code Which Is Some Of Mutated Are Closest To De Target Playlist Part Of My Beneficial Series Started Earlier I Have Made Two Videos In Which I Have Discussed The Template Solution And Its Inscription. It has been kept in good detail and I am going to teach him the same template solution and concepts here and this is a part of a container series in which I have taught him to do progressive template and that tablet is very important because it helps you in understanding your majority and binary. Those questions will be solved. Okay, so just watch the video. If you are watching the continuation series, then there is no problem. Okay, if you watch all the questions from the line and now your next question is there. What we have to do is check here that we are fine, now what is it that we have a target also, we have to return such a value that in this also, if the value of all the elements is more than this well, then they should be equal to that. If you replace it then how many elements are bigger than tu in it, then all of them are bigger than tu. If you replace all the elements with tu, that is, if you replace all the elements with tu, then how will it look like hey tu, now you have changed this, now bring it in front of this then this is Kya aayega six ok here to six aaya but ye jo even hai na this should be closest to the target meaning this is your even come s close s target should be meaning the closer to the target the better it is like people said distance Absolute difference is ok. Absolute difference means that if you target sum minus then it should be minimum. Ok if it is absolute then you can ignore the negative because here we are taking absolute so everything I have said is smaller the better it is ok. Understand that when I take three here, then how many elements are greater than three, then here all the three elements are greater than three, then these two will be replaced, if it remains the same then it will become 333, so here the sum is What will come here? What will come 9 and 9 - 10 here? What will come 9 and 9 - 10 here? What will come 9 and 9 - 10 What is its absolute value What is the absolute value of nine I have taken one this time so here is your well answer Well what is the answer if here I take four Just on example If I take four then here four will be changed, 9 will be converted into 4 but it will not be three because 3 is less than 4. He said whatever elements are bigger than this well which is selected, whatever elements are bigger than this well, change them in that. Two, replace them with that, leave the rest of their small elements as they are, okay and when your time comes, if you want to keep it as the closest target, then how will you check for it and one more thing and tell me that if Maa takes it, then it is done. If the minus is one plus one, the answer to both will be one, then it may be that for two wells, the value is one and well, let's go to the mother. If the answer is one for both, then which thing will you do? It will be small, they have said that if it is small, then here you will return the well one. You have to return the small one, you understand, try it yourself, I will give him his friend, do this, let me discuss two questions, it is in this playlist and You will also find these in the lead code. If this is a similar problem, there is a lot of similarity and there is a lot of similarity between the problems. This will also help you in how you can group the questions so that it becomes easier for you to identify if any new problem arises. You can cluster her, friend, she belongs to this group, so I can follow this approach, otherwise if you just have this hint, then you will get some start from the story, okay, I have to do this. Okay, try gold, if it doesn't work, then we are already discussing that we have to remove the predicate, it is not in it, so how to remove that predicate, till now we are seeing in the whole video that we have to remove the predicate, so let's come here. But predicates come out, rest of the predicates are done, then your entire problem of benefits will be solved automatically. Okay, first of all, binary search will be done here, but why will it be done, how will it be done? In the example we have like 493, we do not have to do some search here. We don't just have to search, we find out the range, okay where can we go from where to where, that is, what are the possible values, but N is life, just like we have one life, okay, first of all, let's make a thumb rule and start with the basics. Let's start with what is the range of any thing that is well, that is, from where to where can we get well. If we are given a well, then how will we find out from it that brother, well, it cannot be more than this. How can this happen? So what can happen to us here? So first of all we came to know that the well cannot be negative, one thing you notice, if it is negative then you see in the question, if all of them are positive then if the well is negative. What happened is that if all those elements are bigger than that because it is positive then all the elements will become negative. He said that if the element is bigger than that then replace it with bell because first it is negative here then all the elements will become negative. And all this will also become negative and this absolute value will become very big because here minus if the target is negative in front because we have given positive then this whole expression will become very big so here well negative. If not then we start from zero okay let's start from zero and this is what we do 493 This is my A which is my four nine three is not which is life now if I convert this here if I convert this Well, after giving the input, how will it look like my zero, you just add value in it, now what will be the sum here, 3 - 10, this is 7, okay, sum here, 3 - 10, this is 7, okay, sum here, 3 - 10, this is 7, okay, I have written you, 222, all the elements are bigger than you, so what will happen is 6. - 10 this will be 333 ok so what is here 9 - 10 what is this ok so what is here 9 - 10 what is this ok so what is here 9 - 10 what is this one now what have we done 4 isn't 4 and 3 is smaller than four so 33 will remain and what do we say what will come here is four Six Three 4 Okay, I have 483 93, there is no change, there was some difference in this step, but in this step there was no difference from 9 to 10, how much time is still there, 16, keep it, 11 is bigger than all three, so where should you stop? You have to wait here and which element is this? This is the max alumnus because after the max element there will be no change. Hey, it is in front of it is smaller than this. And this is equal, let's go in descending order here, then here is downfall A, then going in ascending order, meaning, how does this look to me, this is how the graph here is, now this is the element here, so I If it is made from this, then if my predicate, what to do, I know, you are underestimating this card, this one should reduce my predicate and here yes no, you will return like every time I make it in predicate, so what here. Return No Yes and yes If you have to return then mine will be reduced then I will get this and how will it be returned, nothing has to be done, look, half of it is already yours, search for you in this well. Okay, and why is binary search going, this is also proved because this pick element concept of yours will go here, what you have to do is map it to another one, this is your new one, this one is done. Ten is 7411, you have to give this input along with this area, which means in the predicate, you will have to give this area in the input and you will also have to give this, by the combination of these two, you will create a new erase and it will give you the binary search which is your predicate. Right, these will be monitors, that's why I am saying look, they are not giving sorted, still how come our brother is not searching because our predicate here is mannotones, how come after yes, all the noes are happening before all the noes, okay? So what do you say that whatever you map, it will always come in the same order, why do you notice one thing, yes here, the graph of Appsloot is not there, but you get the graph in absolute terms. Come on mother, if any graph of yours is like this then take its mode. Yes, it happens like this, do you understand, look at this, I was trying to show that yours will start like this, it will fall on one, there will be a downfall, that is, an absolute minimum value will come and then it will increment, this is the mode of yours, right? If you take the mode of A = If you take the mode of A = This will come, you will see that there is minimum one, so don't get confused in it now that it should be one, that means it is coming from this, so in this, we have a predicate here, we want the first test here, we will get it, now we have to make a predicate, this How will the predicate be? Try to implement this predicate in the code. You have understood better what I have done. Well, if you are able to correct it then it is very good. It is a very simple thing. Now there is nothing to be done. Now you have to put this function in the predicate, that is, you have to put this thing in the predicate, you just have to map it in this are and this are. Now in this year you have to do yes, no. This was your input, zero, one, two, three, four. Here, binary search will be done because it is increase sorted, you will computerize it, from here we have found out the route, people. You will have each map, one value for each value is 10 and see this is being converted and here binary search can be done, take it, you just have to write its predicate, so let's write the predicate quickly, okay but. Before making the court, I show what will be the predicate in it, what will be its appearance, what will be its skeleton type, so what am I saying here like if I want yes then how should I make the predicate so that I get yes here and If I get no here, then if I do it, this is my M. Okay, then it will become M plus one. M + 2. By doing this, it will become M plus one. M + 2. By doing this, it will become M plus one. M + 2. By doing this, if my M lands here, then what should I put the condition M should be. Lee give and equal tu m plus one equal tu why because I want yes here at this position then if M + 1 one is equal then M + 1 one is equal then M + 1 one is equal then also we should get yes here because I have to return this position okay and here But 3 is M, give it and equal, you are M plus one, then look, your predicate has become, what do you have to write, I mean, you do not have to write like this, but I am just making the structure which was written by the structure with my pick index, or vice versa. It will be here that off m+1 m+1 m+1 <= Here give L and equal tu sign will come, <= Here give L and equal tu sign will come, <= Here give L and equal tu sign will come, so here I have already implemented this, your L will be zero and R will be what I said is maximum. Option, okay, here we are doing my templates like solution, now here we have to write the predicate, here pay off should be <, we create that function, meaning how is this element. Along with the function, if I am here, then I hit m + 1, function a function returns m + 1 hit m + 1, function a function returns m + 1 hit m + 1, function a function returns m + 1 and this b returns this value, this map value, we have a little of this, so we have to do the computer, otherwise this Let's do the computer, okay, so what I am saying is that I will return, I will take the function, I will take M in it, here, what do I have to do, okay, and what do I have to do here, if I put auto on, then if it is bigger than that If it is then well will be assigned but if it is small then only the small element will remain, then logically it will be your implementation of what this question is saying to do and what to return, you have to do the absolute value of some mines target one also. If you don't want to send the location then you will have to send the target also, we send it to every place, okay, target, okay, so see, I have created a map function and what is it returning? Wait, yes, let's see by submitting and all this is sitting here. Okay, so you guys can see how simple it has become, if you have understood that logic well and now you must have got a confidence, you can implement it by yourself, if it is a difficult predicate because it is a fan, you can solve this. Kid of problem because it is a lot of fun in finding the predicate because it was very intuitive because here we understood that how we can solve a medium difficult problem by taking the help of other questions, I will say this. This was not an easy problem, it was a bit of a trick, but if you practice such questions then you will understand it as binary.
|
Sum of Mutated Array Closest to Target
|
critical-connections-in-a-network
|
Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`.
In case of a tie, return the minimum such integer.
Notice that the answer is not neccesarilly a number from `arr`.
**Example 1:**
**Input:** arr = \[4,9,3\], target = 10
**Output:** 3
**Explanation:** When using 3 arr converts to \[3, 3, 3\] which sums 9 and that's the optimal answer.
**Example 2:**
**Input:** arr = \[2,3,5\], target = 10
**Output:** 5
**Example 3:**
**Input:** arr = \[60864,25176,27249,21296,20204\], target = 56803
**Output:** 11361
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i], target <= 105`
|
Use Tarjan's algorithm.
|
Depth-First Search,Graph,Biconnected Component
|
Hard
| null |
1,026 |
hey guys welcome back to Hustler's algorithm today we are gonna be solving this problem maximum difference between node and ancestor so you can go through this problem statement but it simply says that you have to find the absolute difference between two nodes such that the second node will be the ancestor of first node so let's see what it actually says so the problem statement is we have to find two nodes let's say a be the first node and B with the second node such that the second node will be the ancestor of the first node and the difference between any two such pair of nodes should be maximum so the difference between such pairs of A and B should be maximum right and this will be the absolute difference so let's see what is ancestor first so for one the ancestor are all the nodes that come in path between the root node and that this actual node right so the path is like this so the answer starts for 1 will be 3 and 8. similarly transistor for 3 will be 8 and the ancestor 4 6 will be 8 and 3 because the path is like this and so on and so forth for all the values so let's come to our problem again so what we can do is we can consider any of the path till the root node let's say this is one path this is another path then this is Again One path and the last part will be this right okay so now while traversing these paths will keep track of the maximum and minimum values let's say the maximum is denoted by plus and the minimum is denoted by minus so let's calculate this for each of these paths start from 8 let's Traverse 3 so the maximum so let's start from 8 so the maximum will be 8 and minimum will be 8 right for 8. now we'll go to 3 then the maximum will be 8 and the minimum will be 3. now let's go to one we have the minimum S1 so now as this is our last node we'll calculate the difference between the maximum value and the minimum value and this will be the absolute difference so it will become 7 right now again from here we'll backtrack so till this point we have the maximum S8 and minimum S3 right so this one is not there now because we came again from this path so till this part we have 8 and 3 and the maximum is 8 and the minimum is 3 now let's go to six S6 will not affect our maximum or minimum values will not do anything just Traverse any of the paths that is 4 or 7 let's go to 4 first here this 4 will not affect 8 or 3 because 3 is the minimum and it is the maximum that's a backtrack from here for six we go to 7 this 7 will also not affect our any of the values neither the minimum nor the maximum so let's backtrack from here then again backtrack from here now we are considering disability right so we'll not consider this any of the values in the maximum or minimum so let's remove three from here okay so now till this point we have 8 is the maximum and it has the minimum so from 8 will go to 10 here the maximum will be updated to 10 and the minimum is till 8 so from here let's go to 14 so the maximum will be 14 and the minimum will be still 8. now we'll go to 13 so it will not affect our maximum or minimum values but as this is our last node we'll calculate the difference which will be 14 which is the maximum value and 8 which is our minimum value so the difference will be calculated which will be 6 so yeah this will not update our answer because 7 is the maximum value that we can get so we'll just return 7. so let's see if it is correct or not yeah so we have the output as 7 for this test case so our logic is correct so let's code it right I'll just write the DFS function which will Traverse the node okay so it will be integer EFS and we have the maximum value and we have the minimum value now if for this root is null then just we can return 0 because this will not give any of the maximum or minimum value so let's update the maximum and minimum values as the maximum will be the maximum value among the root and the previous Max similarly for mean so if what we can do is we can write a case like if the root dot left is equal to root dot right which means that the left value and right value is similar so it will be the case when it will be the last node because the left value is null and the right value is null as well so it will become true for the last node which will be the leaf node so during this time we'll just return the answer which is the maximum minus minimum else what we will do is we'll do the same stuff for the sub trees so let's write this root dot left so it will be the left sub tree and the maximum value is this and the minimum value is this and we have again DFS for the right subtree the maximum value is this minimum value is this and we want the maximum among this stuff right because we have to return the maximum value so we'll just return the maximum value so yeah so first our maximum will be the extreme minimum value so that we can update our first value like if the maximum value is initially let's say negative Infinity so 8 will be greater than negative Infinity so we'll just update Max S8 similarly for Main uh we'll just return our DFS function let's Fast Max and min okay let's run it so yeah it runs fine so let's submit it so yeah it gets accepted so thanks for watching subscribe to the channel for more such videos so thank you for now
|
Maximum Difference Between Node and Ancestor
|
string-without-aaa-or-bbb
|
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105`
| null |
String,Greedy
|
Medium
| null |
63 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem unique paths too we have solved the first variation of this problem this one is pretty similar we're given an M by n grid so this is our grid down here we are going to start at the top left position where this robot is I don't really pay too much attention to the entire story we can either move down or to the right and anytime we get to a different position it's the same we can either go down or to the right but we can only Move Along positions that are marked with a zero so any of these free positions are going to be marked with zeros but this here is an obstacle and that's going to be marked with the value 1 and that means we are not allowed to place our robot here we can't go through this position so it's like blocked off now our goal is to get to the bottom right position that's our Target position and what we're looking to do is just count the total number of ways that we can reach that position so just taking a look at this grid how many ways are there well we can go to the right and then down that's one path and we can go this way so there's really only two paths in this grid but if we had a larger grid we could have more unique paths that lead to the Target well depending on how many obstacles we have as well if there wasn't an obstacle in this position we would have a lot more we would be able to reach the target position this way or even this way and this way as well so the easiest way to solve this problem is brute force and using this logic we can come up with the more optimal solution which is going to involve dynamic programming but it's not too crazy taking a look at the Brute Force solution it's best to handle this recursively so we would do it with a depth first search the main thing we'd want to pass in is our row and column because we're here we have two choices no matter where we are we can either go down which is to take our row and increment it by one or to move to the right which is to take our column and increment it by one and then recursively what we want to ask ourselves is to count the number of unique paths starting from here what we can do is just count the number of unique paths from here and then take those and then add them up and then we will have the total number of unique paths from here but then the catch is how do we compute the ones from here well recursively we'd pretty much do the same thing go down count the paths from here or go to the right and count the paths from here and basically that's how our recursion would work we could imagine like a decision tree but the base case is going to be when we either suppose from here we go out of bounds too far down or maybe from here we go too far to the right that's a base case and that would return 0 there's 0 if we go out of bounds the other base case is if we actually reach the target position then we'd say one so from here how many ways can we reach the target position one what about from here how many ways can we reach the target position one so a good way to like initialize this would be to like place a one here or at least imagine that there is a one here and then our math kind of works out for all the rest of the positions and the good thing about this is that while recursively this would be an exponential solution but when we Implement caching to this caching as in any time we compute the value that goes in any of these positions we never want to recompute it because for maybe this it's pretty simple we just look down and then we can get the value here but for somewhere like this there might be multiple paths and we don't have to re-treverse those paths recursively so re-treverse those paths recursively so re-treverse those paths recursively so we do caching to eliminate repeated work so we'll have like a two-dimensional DP so we'll have like a two-dimensional DP so we'll have like a two-dimensional DP grid that's the same size as this I usually use a hash map but it's up to you this will though lower our time complexity instead of being exponential we'll just be the size of the grid which is n times M that's also the amount of memory we're going to need for this DP solution so let me quickly show you the recursive solution but there's actually a way to optimize the memory to get this to actually be Big O of n or you could get it down to a big O of M but basically like one of these rows is the memory that we need and that's like the true dynamic programming solution so I'll show you that afterwards so this is the recursive solution I'll go through it pretty quickly the first thing I like to do is just get the dimensions of the grid so m is the number of rows n is the number of columns and then I'm using a hash map to use as our cache so what I did is exactly what I said in the drawing explanation I'm basically initializing the bottom right position to be one because we know that's kind of our base case but this wouldn't necessarily be required and you could have instead used like a two-dimensional have instead used like a two-dimensional have instead used like a two-dimensional grid that's M by n but I just like to use the hash map for recursive problems we're passing in the row and column into our recursive function because this function is defined in the outer function we already have a reference to our DP cache and to these variables as well so I'm not passing them in and there's a few base cases here one is if we go out of bounds so if our row becomes equal to M or our column becomes equal to n then we want to return 0 immediately the third case is that the grid position is blocked we know if this value is a one then it's blocked we can't Traverse through there so we would return 0 in that case that's the number of unique paths the other case is that we've already computed the value at this position so this is already in our cache this key is in our DP hash map so we would return the value that was already stored there now if that's not the case that's where we actually do our recursion here so counting the paths at row plus one counting the paths at column plus one adding them together storing them in the hash map and then returning that value and then finally to get our result we just call DFS starting at the top left so now to actually understand the true dynamic programming solution which can be really helpful for more difficult problems I would say this is one of the more easy two-dimensional is one of the more easy two-dimensional is one of the more easy two-dimensional dynamic programming problems so it's a good example to practice on so let's talk about the real dynamic programming solution and let's consider this same example over here even though it's a pretty simplified one it will still get us all the information we need even our caching solution is basically Computing all the values that go inside of this grid to eventually get us the value at the top left of the grid so the idea behind dynamic programming is that we can compute these values bottom up instead of doing them recursively instead of trying to compute this one first and then that leads to the sub problems we can immediately start with the sub problems and then compute them in such an order that we can eventually arrive at the ultimate solution so that's exactly what we do we start at the bottom right and then fill these values in reverse order to get us the top left value but some people do it the opposite way some people don't like to Traverse arrays in reverse order and then the rows in reverse order as well the interesting thing about this problem is that it's symmetrical in that if you count the number of paths starting from here to the bottom right that's the exact same as counting the paths from the bottom right up to the top left so you can do it the same way that you want to you can do from top right to left or you can do like bottom up like I'm doing it's up to you I prefer to do it bottom up because that kind of preserves like the context of the problem because in the context of the problem we're allowed to go down and to the right so if we kind of do it the opposite way we'd have to consider us going either to the left or above but that's a pretty small point now to actually start filling in the values we know that the bottom right is always going to be a value one so we can just initialize it like that and let's just mark this spot just to indicate that we have an Ops here but we still need to fill the value in going in reverse order so what value would we put here well we want to add the value to the bottom and the value to the right and when we go out of balance here we can just assume that the value is zero as like the default value so then the value we'd put here is one what about over here same thing go to the bottom and to the right so we put a 1 here what about over here same thing we go bottom that's a one when we go out of bounds to the right we also assume there's a zero here so we just put a 1 over here and then here when we get to the obstacle we just want to skip it so we just either leave a zero here or put a zero if there's not already one and we just keep going like that so from here we'd get a one and here we'd have a one and then finally at the top left position we'd look down look to the right add those together we'd get a two that's the result that we're looking for so it's really that simple but the way we coded this up we have the entire Grid in memory but it's actually not required we don't need to have this n by m Grid in memory because if you notice something every time we look for a value suppose this one what we would do is look to the bottom and look to the right anytime we're Computing a position we only need the previous Row in memory by the time we get up here and we're trying to fill these values in we don't really need this Row in memory anymore we just need the previous row then you think well we only need at most two rows in memory but actually we need even less than that we only need one row in memory let me show you what I would do we have these values here I'm going to show you how to fill these values in if we were doing it in place so how would we get the value here well we'd look bottom the value that's already stored here and look to the right so it's one plus zero so then we'd put a one here but what I'm going to do is actually place it over here because my argument is that once we compute the value here we actually don't need this value to even be in memory so let's just assume that this value actually is taking up this spot but I'm just illustrating to you that this doesn't matter anymore we're never going to use it again we only need these three values basically the size of the row and now to get the value here well it's an obstacle so it doesn't matter anyway so we'd put a zero here once we put that 0 here we would never need this value anyway and then finally when we get to this position we want to look to the bottom because we want to know how many paths we can get going down and we want to look to the right because we want to know how many paths we can get going from the right but in reality these values are still going to be stored in this position we're not going to allocate extra memory for them so 1 plus 0 is going to give us a one here so as you can see it's possible to fill a row in place without allocating extra memory so we just need a single Row in memory and that's the idea I'm going to use to solve this problem and I'm going to do it in reverse order but you don't necessarily have to so what I'm going to do is just initialize the dimensions again this time I'm going to have a DP row which is going to be filled with zeros it's going to be the size of any of these rows and the last value is going to be set to 1 kind of like I did in the drawing and that will get us to the most optimal solution so what I'm going to do is then go through the list of rows in reverse order so we have M rows and I'm going to go through them in reversed order so R is going to be the index of the row and I'm going to go through every column in reversed order so we can do that just like this and there's going to be a couple cases we know the really simple case is if the value in the grid is a one then we know it is blocked off so we can't go anywhere we can't do anything so what we are going to do at that point is just say DP at this position at this column is going to be equal to zero and then we have a couple cases and then otherwise what we would do is say DP at this column is going to be equal to the value below it what's the value below it's just going to be at DP of column because we're doing this in place remember to get the value in the previous row what we would do is just get the same value in this DP row at the same index so this is the bottom value and to get the value to the right we say add DP at column plus one so that's how we would get the value remember the couple edge cases where we go out of bounds if we go out of bounds going to the bottom well in this case that's never going to happen because we are initializing our DP array with a bunch of zeros this would never go out of bounds if we're going to the bottom but going to the right we might go out of bounds if C plus one is equal to n for the last value in our row we're going to go out of bounds so what we can do here is First add an else if because if this doesn't execute that's when we would want to do this but also say if C plus one is equal to n that means we went out of bounds or we could say C is equal to n minus one either way that means we went out of bounds so what we're going to say is C plus one is less than n if that's the case then we're allowed to do this but if this is not true either then what we would say is the value to the right is out of bounds so we're not going to add it so the only thing we're going to do is add the value below to this well not to this but we'd say the value to the bottom plus zero is what we're going to put here but notice how that DP at of C is equal to DP the bottom Value Plus the value to the right which is zero notice how this isn't doing anything this is just like an assignment it's not doing anything so we don't need it but I wanted to explain why we don't need this but I think it's kind of obvious just looking at it so we don't actually need this else case it's not doing anything and then we just have this code which is pretty much all we need by the time this is done the value at the top left position DP of 0 will have the result so we can go ahead and return it now let's run the code to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has interviews check out neat code.io it has interviews check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
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
|
1,732 |
hey everybody this is Larry this is day 19 of the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem today's contest everything in between uh today's contest we might say I don't know I went on a long hike today so I'm a little bit tired and there's people say in the comments I'm always tired we just may be true uh hopefully you know in today's actually today's problem is uh find the highest altitude which is uh maybe the same team of me and Hiking uh you probably have saw the intro which is a another drone video hope you enjoy it uh yeah uh right now I'm in where am I yeah wow I am losing it I'm in Bush cake here in Kyrgyzstan uh so yeah okay so there's a biker going on a road trip the road trip is one points different altitudes to start at 0. okay so it goes from negative five it gains oh this is the gain so basically you're trying to do a summon the highest that's pretty straightforward right so highest is equal to say negative Infinity uh infinity is equal to some ridiculously big number right and then for DX or d y I guess maybe in gains uh oops so current is equal to zero which I guess highest is at least zero but right okay fine so the highest is actually zero highlight and then yeah and then Kern we add it to Dy highest is gonna Max Kern highest and then we just return highest I guess that's pretty much it I mean it is easy after all so I don't think I expect any trickery uh except for maybe naming things correctly um looks okay let's give a submit yeah uh linear time constant space really don't have much to say about this one so I just hope you enjoyed the drawing video uh of me on some high altitude and yeah uh that's what I have so stay good stay healthy to go mental health I'll see y'all later and take care bye
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
1,444 |
hello guys welcome to deep codes and in today's video we will discuss later question one triple four that says number of ways of cutting a pizza so here you are given a rectangular Pizza represented as a row into columns Matrix where a character a represented an apple and Dot represent an empty cell further you are given one integer scheme and you have to cut this pizza into K Pieces by using K minus one Cuts so if you want to divide this pizza into three pieces then you have to make two cuts okay further for each cut you choose on Direction see here let's say here if you are given this type of Matrix and now for each cut what you have to do you have to choose some of the direction why the vertical or horizontal is either you can cut a pizza like this way in a vertical direction or in the horizontal detection now if you cut in a vertical Direction the left portion will be separated out and you will be have this remaining right portion okay now if and if you cut in horizontal way that upper part would be one piece in the lower part would be another piece got it and the condition that you have to satisfy that whenever you cut a pizza at the vertical or horizontally this uh both means this part must have an upper this must have an upper here also it must have an apple this is an apple here this it must have an apple got it so yeah uh and the last piece remaining would be given to a last person okay the thing here is K is the number of person here and you want to divide uh this pizza into all the given person all the K person for that you will make K minus one Cuts okay to divide the prism further uh and what you have to return the number of ways of cutting the pizza such that each piece contain at least one apple see this condition has to be satisfied okay so here we need to return the number of ways and if the with the modular of this uh so that we are in Earth inside the pound now guys if you take a look at the first example here see here this is the given Matrix let me just draw you this so This Is The Matrix okay now here uh we the K is 3 that means we have to make two cuts and we need to find number of phase to make Cuts such that each pieces has one apple okay so let's say we make this as a first cut so this is now separate it out and this is the remaining part okay this is given to one person and this is the remaining now from this remaining we can make this Cuts okay so this is separated and the last person will get this piece got it so now as you can see person one get this piece person to get this piece and person three get this piece then all the pieces have at least one apple so this is one valid card valid cut now we have to find how many different valid cards are there so let's say in the second try you cut the pizza from here and then from here so this is also valid in the third try you cut the pizza from here and this is the remaining round so from this remaining you cut from here middle so this is also valid and no further cuts are possible so yeah we written here three as our answer now guys if you take a look at the second example here we have the upper dot then Apple Dot and dot so this is this type of Matrix we are given now k equal to 3 that means we have to make at least um two cuts so let's say we make one cut from here then the remaining part is this A a apple dot and now from this remaining part we make out from here so yeah this is a piece will get two person one this will be given to person two and the remaining one would be given to person 3. so this is one possible cut now if you try to make different cuts such that you will get uh three pieces with each apple and it is not puzzle so let's say you are making one card from here okay so the remaining part is what Apple dot so this is the remaining point now if you make a cut from here then this person 3 won't get any apples right so there is no other possible way of making a cut apart from this wave correct this is the only one possible way so here we written one is a one awesome thing here is here K is the one k equals to one that means we don't have to make any Cuts so yeah whatever the pizza is there we have to give to that person only so since we are not making any Cuts so here we written one as our answer okay I hope you guys now understood the question that what we are trying to do we're simply trying to cut this given pizza into different possible ways such that each pieces has one apple okay so now let me explain you further so here let's say there was an apple dot now here what you did see let's say you cut the pizza this way you cut this pizza this way then what is the remaining apple dot then you curse this pizza this way then what is remaining Apple dot uh dot so this is given to person one okay this is given to person two and the remaining this is given to person three now the thing is what after one cut see this was the remain you see this was the remaining part now in the remaining part also we have to do the same thing we have to apply Cuts in the remaining part also what we are doing we have to apply cuts okay and this is what this is nothing but a sub problem see this was the comp the complete problem was this okay the complete Matrix was a complete problem now after making one cut we are getting the sub problem and third sub problem is almost uh similar uh to big problem right now so whenever you guys have something like this sub problems and the sub problem is all is similar to the big problem then what we can do we can write a recursive solution okay you can think of this as another way see you have choices to make cuts and there are different choices see one choice is either you can make vertical cuts or you can make horizontal cuts and let's say if there are in vertical curves that you are doing so let's say you are from one to C column so you can make anywhere cuts at anywhere at the column two column three column four up till c minus one column similarly for the horizontal cut let's say you have R number of rows so you can make cut at a row two three four up to R minus one rows so that means there are multiple ways that you can define a cut okay just let me take this at a bottom so guys till now what you have understood that there are different um ways that you can make a cut there are your choices of making a cuts and now whenever you have choices then what you can do you can write a recursive solution so whenever you have choices you can write recursive solution got it clear till here okay now ah after this what a scene again let's come back here so this was the initial Matrix now after one cut what is changing after you make one cut what is changing what are the changing variables that we have to focus changing variables what are they see false that is the size of the Matrix that is I and J rho and the column and second thing is uh number of cuts remaining Cuts you can say remaining Cuts so there are three variables one two and three variables that are changing here then that we need to Handle by writing a recursive solution okay got this okay now further one thing uh we have to make a note that each piece must contain an apple so we have to make sure that each pieces must contain an Apple so now how we can make sure that each piece must have an apple so for that what we can do is see one thing is what after uh so before cut what we can do we can Traverse and identify but this will consume more time see every time during every recursion call we have we first have two Traverse the metrics and identify whether there is an apple or not in the row that we are cutting on the column with the where we are cutting but to avoid this what we can do we can build a prefix sum right prefix sum that will tell the whether there is an apple in a given so let's say a prefix of i and J so this will tell whether there is an apple or not okay the count will whether the presence of Apple presence less count of Apple so that we have to calculate this only one time calculate only one time correct so we will calculate this prefix sum in order to reduce a Time complex setting uh so yeah clear till here so guys there are three changing variables that means the summarizes there are three changing variables there is the number of rows remaining number of columns remaining and the number of cards remaining second thing is we have to make sure that each piece must contain one apple then what how we can do this we can handle this in the best possibility is by taking a prefixon so prefix sum of i j will contains the count of the number of apples correct clear till here so now let's move on to the coding part uh where we will understand this in much more detail so the code for this is simple see guys here first we took the size m n a then we took the vector DP of size this DP of K the number of rows and the number of columns we took this type of DPM then we took this prefix on that I have told you earlier okay so then we calculated this prefix sum so this is uh this is the particular formula of a prefix sum that you might know uh that is the number of apples in a given row and a column that will be given by that will be taken by this for a prefixon formula so this is the standard way of calculating prefix sum in 2D Matrix so this is a prerequisite knowledge that you must have and then we simply call this all function where we pass the size of the Matrix the number of cuts we have to make the current I and J index DP and prefix sum now in this solve function is also pretty much simple so this is the base condition or terminating condition that means that if there are no apples here then return 0 because there is cuts are not possible no possible cuts because if there are no apples then in the remaining Matrix if there are no apples then there are no possible Cuts now if k equals to 0 that means all cuts are done so all the cuts are done then we return what 1 then we simply return one we got one possible answer this is one you can say valid answer now further we check if the sub problem is already calculated if the sub problem there is a DP of KRS is already calculated then we return the transform now this is uh the simple thing here first we are initial initializing our answer now what is the number of possible cuts that we are taking that is from current row is R so from R plus 1 up till M we are checking so this is what we are checking if the prefix sum of RC minus briefing sum of this current uh row there is another currency is greater than zero that means there is an apple present right there is an apple present between this so let's say if this is the Matrix here and if this is the NR okay and this is R so if subtracting this subtracting these is greater than 0 that means then there is an apple present in here so we can make a cut got it this is this condition so if this is possible then we will try again call for this recursive solution we will make a make this cut so our row will change variable row will change to NR and we will call for recursive solution recursive function and the same thing goes for the column so let's say if you have a cut from here and uh you and this condition will check whether there is an apple or not after in the cut right and if there is an apple then we again call for this recursive function so yeah this is the way that we are checking for all the different possible Cuts in the rows and all the different possible Cuts in the columns for the answer and at the end we are taking the modulus so yeah and here we are simply storing our optimal solution or the best possible solution that is present in the answer into this deeping about it every time we are doing answer plus equal to so we are adding the number of answers only this is where we add the number of ways got it so yeah I hope you guys now understood the coding part as well not talking about the time and space complexity so the time complexity here is M into n into K see these three are variables already there these three variables are already there here into what this is one thing into M plus m why this because here we are taking this for Loop correct so this for Loop will run for M and this for group will run for n so this would be additional uh time complexity that would be multiplied now talking about the space complexity so guys here the space complexity would be also M into n into K you can clearly see the size of our DP array so this is our DP array and that same size would be our stress complexity so yeah that's all for this video I hope you guys understood the intuition of uh how we are building the intuition of recursive solution and yeah based on that intuition we derived our codings so yeah that's all for this video if you guys have any doubts then do let me know in the comment section make sure you like this video And subscribe to our Channel thank you
|
Number of Ways of Cutting a Pizza
|
number-of-steps-to-reduce-a-number-to-zero
|
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts.
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
_Return the number of ways of cutting the pizza such that each piece contains **at least** one apple._ Since the answer can be a huge number, return this modulo 10^9 + 7.
**Example 1:**
**Input:** pizza = \[ "A.. ", "AAA ", "... "\], k = 3
**Output:** 3
**Explanation:** The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
**Example 2:**
**Input:** pizza = \[ "A.. ", "AA. ", "... "\], k = 3
**Output:** 1
**Example 3:**
**Input:** pizza = \[ "A.. ", "A.. ", "... "\], k = 1
**Output:** 1
**Constraints:**
* `1 <= rows, cols <= 50`
* `rows == pizza.length`
* `cols == pizza[i].length`
* `1 <= k <= 10`
* `pizza` consists of characters `'A'` and `'.'` only.
|
Simulate the process to get the final answer.
|
Math,Bit Manipulation
|
Easy
|
1303,2288
|
1,716 |
don't want to miss today's questions i said it's easy money in liquid bank heresy wants to save money for his first car he puts money in the league code bank every day he starts by putting one dollar on monday every day from tuesday to sunday he puts he'll put one dollar more than the day before on every subsequent monday he will put a one dollar more than previous monday given n return the total amount of money he will have in the liquid bank at the given nth day and is up to a thousand you can do it by brute force um which means we have to go through each of the days starting from zero all the way up to n plus i and then go through each and accumulate an answer so answer plus equals to something so i need to know what the current week is the week would be given by i divided by seven so at i equal to seven that's the next monday so it'll be one that'll be week one right now it's week zero i'm going to add one plus what day in the week it is which will be given by i modulus seven and that should do it then return the answer let's give that a run sweet thanks for watching like and subscribe and i'll see you in the next video
|
Calculate Money in Leetcode Bank
|
maximum-non-negative-product-in-a-matrix
|
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**.
He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**.
Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._
**Example 1:**
**Input:** n = 4
**Output:** 10
**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
**Example 2:**
**Input:** n = 10
**Output:** 37
**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
**Example 3:**
**Input:** n = 20
**Output:** 96
**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
**Constraints:**
* `1 <= n <= 1000`
|
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
|
Array,Dynamic Programming,Matrix
|
Medium
| null |
521 |
hey everyone welcome back and today we'll be doing another lead code five two one longest uncommon subsequence one an easy one but have a lot of dislikes 90 dislikes in this problem given to Strings A and B return the length of the longest and common subsequence where subsequence between A and B if the longest uncommon subsequence beca does not exist return minus one The Uncommon subsequence between two strings it is a string that is a subsequence of one but not the other so we have already done the subsequence the longest common subsequence and that was an easy one also so this is the uncommon subsequence in which if the string does not make like they said like a non-commerce succession subsequence a non-commerce succession subsequence a non-commerce succession subsequence between two strings is the string that is the subsequence of one button doesn't make the other so it is pretty confusing but it does not make if we delete the elements of it does not make the same list you can say of same string for example a b c the subsequence of a b a e b d c and we have already done this problem because you can delete yes you can delete the underlined character and still get ABC uh other sequences are like this and an empty string also so what we can do is just compare first of the first of all like this if a is equal to B so if a is literally equal to B we are just going to return minus 1 so we have our first condition done and now we will see the length because if the length is equal then we are going to return either of them because if there is an uncommon subsequence then obviously we are going to return the length which is the same so it doesn't matter if we return the length of a so if we return the length of B so if length of a is equal to the length of B then we are just going to return the length of a or b it doesn't matter now if the length is not equal then we know that the string that has a larger elements obviously that is not going to be made up by the smaller ones like you can see ABC can be made up by this is not the same problem but this follows the same criteria like ABC can be made up by these letters but it is not the subsequence of this is not a subsequence of this string so we will run the maximum length and that's it so length okay the length of B so we will just return the max of length of a given the length of B so that's it let's see if this works and that's it
|
Longest Uncommon Subsequence I
|
longest-uncommon-subsequence-i
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
String
|
Easy
|
522
|
139 |
for given a string s and a dictionary of strings word dictionary return through if s can be segmented into a space separated sequence of one or more dictionary words because code space separated whatever it is as long as doesn't really matter note that the same word in the dictionary may be reused multiple times spee for so of the keep track of the word fore usary all right foreign spee botom apprach already program Rec let's just actually string string for spee the same thing for DP of 3 DP of all right so DP for all right dnamic foreign DP like dynamic programming DP of Ls of this one which is eight which is of string L plus right I in range fore forward in word dictionary foreign speee spee right I minus LS of I minus l greater than or equal to Z DP of I minus length of WP IUS which is I minus Leng of wood for return notation ofation of I where n is the lenguage of strings times m times where G is the L of the word compe
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
82 |
so the problem says that you are given the head of a sorted linked list you to delete all nodes that have duplicate numbers leaving only distinct numbers from the original list also you have to return the linked list sorted as well if you look at the first example the number three is repeated twice and the number 4 is also repeated twice so these two numbers should be removed from the list leaving us the numbers 1 2 and 5. similarly if you look at the second example in the given linked list the number one is repeated three times so it's a repeated number so it should be removed so only 2 and 3 should be remaining hence the output is the link is 2 and 3.
|
Remove Duplicates from Sorted List II
|
remove-duplicates-from-sorted-list-ii
|
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,2,3,3,4,4,5\]
**Output:** \[1,2,5\]
**Example 2:**
**Input:** head = \[1,1,1,2,3\]
**Output:** \[2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List,Two Pointers
|
Medium
|
83,1982
|
59 |
um hello so today we are going to take a look at this problem called spiral matrix 2. um it's part of what's called april ladies challenge um so we get an integer n and we're going to generate an n by n matrix filled with elements from 1 to n squared in spiral order so this is the main uh complication here is in spotted order which basically means we fill the first row 1 2 3 last column 4 uh bottom row six seven and then we keep going first column again seven eight and then we do the row we do the uh the first last column and then we do um the n minus two row you get the idea so we keep going um until we finish the uh the spiral um yeah so this is the problem now uh this is very similar to um the spiral matrix one where that one we get a matrix existing matrix and we traverse it in spiral order um yeah so let's see how we can solve this problem um okay so let's see how we can solve it so i have here um a major tool fill it in spiral order one two three four five six seven eight nine so one simple solution that we can do is definitely like to keep um to keep track of row the beginning of the row um and then increa row begin and then increase it and keep track of the start of the column and the end of the column and just play with all of these pointers increase them at the right time and insert in the right position um and then in a form of default iteration that's the most common solution you'll probably find it in late code and in other explanations um but what i want to do here is a different solution that is um unless variables essentially and so what we are going to do is instead of keeping track of all the pointers for the row beginning row ending beginning column row column and then do four for loops what we are going to do instead is keep track of the direct direction and so what you'll notice is while we are traversing this row um this row here uh what we do is well this is zero right and then this is 0 1 and then this is 0 2 so each time we add 1 to the row and then we add 1 to the row and add 0 so add 1 to the column position and add zero to the whole position right and so if we think about if we try to think about it this way um here while we are traversing row one so traverse row one row what we do is um we take the row indices plus zero and then the indices in the column plus one and so we can represent this direction here so this is this direction and then we have this direction and we have so we have over all four direction and we keep cycling through them until we reach the end right and so we can represent this by zero one because we are adding one to the uh to the wrong position and zero to that position and one to the column position so this is basically left to right direction um let me write it more clearly here so so left to right direction will represent it with the value uh zero one now what about four um what about for this down position so this is um if we take a look here this is one zero one and then one two right zero one two uh zero one two sorry so this is actually uh let me just this is not the correct value so this is 0 2. this is 1 2 and this is 2. so you can see here this position the row position increases zero plus one two but the wrong position stays the same right and so here what this is telling us is that um that so this is up um up down right so we will call it up to down right direction in our case here this is going to be one zero because we are adding one to the row and zero to the column position now what about this direction here let's write it down so this one is 2 and then um the position of the row is two still the position of the column is one and this is to zero so what i'll do here is each time minus one on the column and then adding zero to the row and then here minus one again and zero right so this position is all direction here can be represented with zero minus one basically we are um the direction represents what you should add to x or to i and what you should add to j okay so what this would mean here is that um so this is um right to left right so right to left direction is going to be for us here uh minus one zero so zero minus one right now let's see berm um the other direction which is um down to up right so down to up direction so what is the value there so here well what is the value here this is um 2 0 this is 1 0 and this is 0 right so what are we doing here we are doing minus one in the car in the row position so it's minus one zero and so this can be represented with minus one zero right and so for our spiral order here what is the order of directions that we should take um so if we have um the order of direction is we should go right to left first sorry left to right first then we should go up to down then we should go right to left then we should go down to up and do our bottom to up and we should keep doing this um we should keep doing this until because when we reach 8 here we'll try again to do left to right until we reach a position that we've seen before like four so and then so basically what will happen here is at eight we will try to go to we will go to nine and then we'll try to go to four but four was already visited so we should not visit it so to simplify our um or our logic here instead of coming up with a custom logic we can just maintain a scene set right which will contain x and y values or i and j values and basically we can change direction when we reach a scene cell when we reach a cell that is already seen already visited right so this is the main idea because what we will do here is for example let's say um we'll do one two three and then we'll change direction right and we'll do four five six seven and then we'll go up eight nine and then when we reach four it's already seen so try to change direction but then we'll have already seen this again um but if we had more right if we have more data we will see that for a scene will go down um let's say we had more data after nine more values after nine right so this is kind of the main idea here um and so what we'll do is just have an array like this with these directions and then start for the first um direction we'll just add one each time so yeah let me put it up actually just so that it's um the solution is a little bit more clear so what we'll do is we'll have our directions array here which will have the values that we said here which is 0 1 0 and 0 minus 1 and minus 1 0. so one thing i want to clarify is that the order here is important this is the order of the spiral um traversal the other thing is that the values here represent what we will be adding each time we want to go to the next cell right and to change direction we just add plus one right and to do a second tour we just need to go from here from this position so this is zero one two three to do a second two we just need to go from here to zero which can be done by doing the curved direction which was noted by d plus one and then modulo four the length of the directions list um and so when we reach three we'll do three plus one modulo four that'll be zero we'll go back to do this row here and that's exactly what we wanna do right we wanna once we do all the traversals until down to up we wanna go again uh left to right and keep going again right until we uh until there is nothing to do anymore right um so that's the idea here i hope that's clear um so once we have our directions right we can have a list um to add the values and then we will have a counter where we'll initialize to zero um initialize to one because we want to start from one and then we'll just keep going until we fill all the values which means when counter is equal to n squared right um and we'll of course initialize our res value we'll do that later and then for our we'll initialize x and y to zero right that's the start position and so this is going to be counter um and now how do we add the direction as i said we will use the value here to know how to um transition to the next cell and so what we're going to do is we'll have dx and dy which is the transition here is going to be directions uh d and d here will start at zero because that's what stopped here right which means that we'll add z dx is zero d y is one so for the first one the uh left to right we'll keep adding to the index uh of the column right because that's what we are doing we're traversing a row and so for that one uh once we have the dx and dy we will um say our next x and our next y are going to be x plus dx and y plus dx dy right and then after that we'll check if these values are within the boundaries and because when we reach here right and we are out of boundary we want to change direction and go um up to down right and so that's what we are going to do here so and y is less than n um and the other thing is to handle the case where nine we go to four is already seen so we don't want to go there and so we will do that here and um we want to make sure that we have not seen that new cell again if it's not in scene only there we go traverse it but we should not forget to add to see in x and y here okay um and now um what we need to do is just reassign to x and y and x and n y so that in the next iteration we'll add to this new position we'll add counter right now if not for whatever reason either the um the values is our outbound or it's not seen we want to change direction and so what i said to change direction is just to add one and then do modular of course for the case well we need to do a second round right so otherwise we want to increase d plus one uh sorry d plus one and then we wanna do modulo the length of direction which is four okay and now our dx and dy should be directions d right for the new direction and we are going to reassign x and y to the previous x plus dx and the previous y plus d y and this will work because here we have let's say here 0 this is 0 1 2 this is zero two and so here um to change direction to one zero we'll add one it will be um one and two we are adding zero so one two which is exactly what we want because it's this position right we want to start from 4 and so this works out because we are adding 1 and so skipping this one because we've already added it right and so that works out well here and now we need to increment counter so that um the value um the next value is once we set one the next volume is two the uh the next one is three and after that is four and so we will do counter plus one here um and that's pretty much it actually and then at the end we can return um okay so i have here the solution that we just saw in the overview so first we initialize um the result matrix that we are going to return we initialize it with zero values everywhere um and then we have the directions array the same direction array that we saw um and we start with the current direction here with the first one left to right um and counter starts out at one we start a and j or the index of x and y at zero and then we have our scene or visited set and we go until we reach n squared which is that the final value wanna assign and each time we assign counter and we add to the set of scene values we add x and y and then we take the current direction we add it to the next we add the direction values to the next cell indices and we check that we are within the boundaries and that we have not visited it yet only then that we ascend these next values to x and y but if we are outside the boundaries or it's already seen that means we need to change direction and so we go to the next direction with this so it's either we go to from zero one two one zero which means going for up and down to down direction or if we are here already which is uh bottom to up for the first column for example for the first traversal we want to change direction and go left to right again and so we do plus one modulo four so that we can go here this can be you can also do length of directions and then we add those values um to x and y right and then we assign x and y to these updated values and we increment our counter so that next time we set the updated value here and then at the end we return our result matrix um yeah and that's pretty much it um okay so now that we have the solution let's see how the term complexity here so we will do at most of the squared right because each time we increment counter by one and then once we reach n squared this we exit the while loop so we have at most this much these many iterations um and so that's the only for loop that's the only iterations we have so overall our time complexity here is this um for space complexity we are using this extra set right we are using four here with this list array list directions uh this is constant time we are using all oven squared for the output and so our space complexity here is oven uh squared as well for the output but if we didn't count the output then we'd have an extra oven squared as well for set um one slight optimization that we can do it doesn't matter much with the space complexity because we have the output but we can remove this scene here and instead what we do here is just check if this value was already assigned a value in res right because that will mean it's assigned and what doesn't mean it's set a value so if its value is different than the initialized value so if it's bigger than zero that means it's already uh it was already set um and we can that way get rid of scene get rid of this as well um yeah so actually um only if it's not set that we want to do this right so only if it's equal to zero which means i'm not set um and now let's run it okay so that's accepted let's see if it best test cases um yeah it does um yeah so that's um so that makes it better um and um with this solution uh this directional solution we don't have to do each direction separately in our loop instead we can do them all in one go um yeah and that's pretty much it for this problem thanks for watching and see you on the next one bye
|
Spiral Matrix II
|
spiral-matrix-ii
|
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Array,Matrix,Simulation
|
Medium
|
54,921
|
1,374 |
hello friends today we are discuss this question from lead code weekly contest 179 problem number 137 for generate a string with characters that have odd count it's a easy problem in the problem statement states that you are given an integer n you have to return a string n is return a string with n characters ok says that each character in such string occur an odd number of times ok so what does that mean it means that every character in the outputted string should occur odd number of things and those two Gators will be different as you can see so if the input number is even so we can divide an even number into two odd numbers so like it can be 3 plus 1 like 210 equal to 1000 but if the number is Pole already or then we just have to print a single number so that's the basic logic what we will do is we first take an empty string and then we find out whether it's in order not so for the length to be odd so when the length is odd we just print a in the empty string and it will be ace in that string so that if the n is equal to 5 there will be 5 field and a occurs or number of times so that output can be 5 face but if it's an even number so what we do is we first store n minus 1 times so that let's assume they are the n is equal to 4 so we first print store 3 times a in the empty string and then the last time we stored be only one time so it means we are stood stirring this be one time so it's an odd number and odd plus odd is equal to you so the whole number actually is an even number that's why we are doing this and then we are done in the output string I hope you understand this logic that spirit is simple if you have any doubts please mention out in the comment box and I see in the next video thank you
|
Generate a String With Characters That Have Odd Counts
|
leftmost-column-with-at-least-a-one
|
Given an integer `n`, _return a string with `n` characters such that each character in such string occurs **an odd number of times**_.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return **any** of them.
**Example 1:**
**Input:** n = 4
**Output:** "pppz "
**Explanation:** "pppz " is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh " and "love ".
**Example 2:**
**Input:** n = 2
**Output:** "xy "
**Explanation:** "xy " is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag " and "ur ".
**Example 3:**
**Input:** n = 7
**Output:** "holasss "
**Constraints:**
* `1 <= n <= 500`
|
1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out the correctness and time complexity of this algorithm.
|
Array,Binary Search,Matrix,Interactive
|
Medium
| null |
376 |
Story gone English Video Way Bill Discuss Liquid Question Thoughts What is the meaning of alternative numbers Difference of alternative numbers if positive negative alternative comes what does it mean our alternative is other vice note ok as if this number is given to us what will we do ok see Longest Return D Length of D Longest Vehicle Substatements of D Number Whichever comes longest, we have to get it returned. Okay, so we went like this that our option number means look, this is our number given, in this we can see. How are we getting our fine, first of all it started from one, then what went up, then what went down, after doing 7 mines one, first we have to mine these two from the front digital one, we have to mine the digital one from the back one, okay so what happens 7 Mines One Four Mines Seven Nine Mines Four If we keep doing like this then first costly then negative positive okay, negative positive then negative positive okay, this is alternative A, here again it could have gone like this negative positive so this is also our alternative sequence. It happens because of C, now what is ours, this is the second example, so we had to find out that look at this one, you can see on the exam that this one is ours, so we have to find out whose length is the longest. The length of the vehicle substance is found out. Okay, so we can see here that its answer is 7. So we will find out whether it is A or not. Okay, so look, these are our numbers. First of all, 17 went up and then went down, 5 to 10 went up again, then what will happen 10 to 13 went up again, okay 13 to 15 and then down there are 16 gates in this you can see that ours is this one which is number A. There are this one and simply this one, these three are not less important to us, why they are not less important because we can make it simply one note because these two notes are our alternative means plus minuses. There is no need to change, it means it is not useful for us, so we will not use these numbers, ok then we don't have to even consider this number, once you see the line cut, if it is not for us, then which are our less ones? How much is it increasing and the taxman is fine with five or six rupees, okay, our notes, that is, the numbers are not helping us, if we change the fine then we will not take it, okay, this much we understood. Now what we have to do is see how we will solve this, okay so we will take two values in this, we will take one piece, we will take two values in this, we will take one piece, we will take two values in this, we will take one piece, we will take one value, people value, what does the first mean that which is ours means it is becoming positive, we will pick the other vice below. If A is there then we will take it as valid, what will we do after that, what is happening from first one to 17, this is increment, so in the first starting, we have taken 11, what is the sense of this, because as already told you, our number is like this, isn't it? It can also be said like this, it means the first number, where we don't know whether it will be increment or decrement first, so what will we take, we will take one, because we don't know, after that, first 11 is taken, after date one, there will be 70 increments. What is the meaning of one? We have to count that it should come to our length, congratulations for that, okay, after that 17 is being increased, so we have incremented its value, you are okay, after that this decrement was happening. Here you saw the decrement, how much did it go on the depreciation, three, after that, how much was the increment, so how much did it go, after that, what happened further increment, again the profit was incremented, so they don't have you take care, then what happened after 15. Decrement is five, what does it mean, we can directly make notes from here, okay, what is after that, this one is piped, after that, what is first decrement, then what is increment, this incremented number is after date it. Decrementing is okay, so these points are reduced with us. Okay, so we are losing logic time in this. Look at these points which have become smaller. You can write it like this. If you see, our graph has to go down. It means that here and there we have some tissue, Chinese new, it means what is our number, so how much will remain here, only you will remain here and like here this will remain only three, here also there will be only three and here also only three. There will be tax on pay here too, there will be tax on pay here as well, tax on pay here is ok, after that pay tax on five here, where no difference will be seen from us, story, degree of increment, how will be that of mother, number will be as per previous, it will be fine. After that, we will put the condition IF greater, give nox of i plus one, what does it mean, see, we have made this pickup one of ours, this one is of constant, so we do not have to change it, now what we have to do is that we have 17 I went to 7, now see, we can do journey from the first number and I am entering from the next number, okay, then what will I do, if I see that our number has come, what is it, incredi now. Dan is I plus one means it is greater than the number after that. Yes, it is greater than A. What does this mean? This is our point P point A. Okay, if this happens then pick point A is what will we do in this which will calculate the value. Is the number valid? We will increment it here. Okay, after that what have I put in the name so IF <. What does it mean that this is the number okay? What is happening after that? Na, let's give it like this is seven five, which number is it, I am plus one, okay, what will be the value of value, what will be the value of properly, one big means you too, what will be I plus one, whose value will it be of ours? Well, this is the logic that we have to apply, so this is what I have: N is what is logic that we have to apply, so this is what I have: N is what is logic that we have to apply, so this is what I have: N is what is non-stop left side, the value of the pick, we non-stop left side, the value of the pick, we non-stop left side, the value of the pick, we will keep one in the beginning because we want the first one because we do not know in the beginning whether our number posted first will be negative or negative. It will be positive, okay, so then I have followed by i < and -5 n - 1 because followed by i < and -5 n - 1 because followed by i < and -5 n - 1 because look here i is plus one, what is the meaning of i bill sun, how far will this number of ours go till the last, so that never before The value of I should be known, that's why I have put it, now what to do, I have checked it and the maximum length will come out of it, what do we have to do in it, okay, we will simply get it returned, that is how much will be ours, the longest length will be okay, look at our course. Accepted ok
|
Wiggle Subsequence
|
wiggle-subsequence
|
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative.
* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`.
**Example 1:**
**Input:** nums = \[1,7,4,9,2,5\]
**Output:** 6
**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
**Example 2:**
**Input:** nums = \[1,17,5,10,13,15,10,5,16,8\]
**Output:** 7
**Explanation:** There are several subsequences that achieve this length.
One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8).
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6,7,8,9\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
**Follow up:** Could you solve this in `O(n)` time?
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
2271
|
336 |
hello everyone welcome to my channel so today we are going to do leadco daily challenge palindrome pairs so basically in this question we are given with a list of words and this list of words we are required to basically check that how many pairs of palindromes are being there so here you can see that ABCD is there and then BCD is there right so when we combine these so basically it becomes a palindrome means so because of that only we are having this and when we check for dcda and ABCD then again it becomes a parent company right so that's why because of that we are having this so that's the thing which we are required to check for all the words which are being given to us and are this particular and in this particular uh what we say that vector or vector which is being given to us so before starting let us start with the reading of this question then we'll take for the constraint and then examples so given a list of unique words so all the words that are unique return all the pairs of distinct indices so all the pairs of distinct indices we are required to return in the given list so the concatenation of those two words that is word of I plus word of J is a palindrome so that's the thing which we are required to return so let us first take for the constraints so constraint basically are given to us in such a manage like length of the word could go to 5 thousand that is if we go ahead with n Square solution so it will directly have the 10 raised to Pi 6 right and even the length of that words uh okay here the thing is that the number of words which is being given to us that could be this much about uh that could be till 10 raise to power 3 right and every two to this much and one more thing which we are required to consider for each is that the length of each word is 300 at Max 300 right so then we go ahead with comparing one word with other words so it will let us to have the time complexity two plus two that is 10 raised to per 4 right so overall if we combine if we are having more lows inside them so somehow it will become 10 raised to power 6 Plus 2 or might be two more so it simply becomes a solution of six seven eight nine ten right so this will definitely give us tle so that's why we are required to come out from that Brute Force solution to an optimized solution there we get our answer in such a manner that we utilize the length of the words at maximum and the number of words to the minimum because here you can clearly see that this 10 raised to Percy is greater than 10 raised to power 2 right so that's why we are required to utilize this thing only that we make a solution where temperature if we want to go ahead with a square solution then in that system 2 is utilized mode rather than 10 raised to power 3 so that it don't give us a tle solution so that gives us hint for this solution but even of this hint we very well know the way they have given to us the first thing which comes to our mind is a root for solution only because here the first thing which we are required to check is that is it the palindrome or not so for checking our palindrome we already know that the solution would be order of n right and the second thing which they want us to check is to check pivots right so we will be faking for each word which is being there and comparing that each word with each other word right so in that scenario only then our solution again becomes n Square so in all these cells error n simply would be for any basically it would be the number of palindroms which are being there which we will be passing into the length basically it would be something like this so that's why the overall time complexity somehow becomes n Cube into l or in some scenario it is n square into l so because of this time complexity only in The Brute Force solution we were getting tle now so let me first show you about the Brute Force solution because it if you don't know about the Brute Force solution then it becomes much difficult for us to come up with the optimized solution so here is my Brute Force solution so the thing what I was doing was I was simply going ahead means here's the answer because our return type is basically vector in so that's why we are taking like this now here I'm running a n Square Loop where I'm checking for each num each word for each pair that is I with J that is 0 with 1 and 1 with 0 also so that's why we are starting from 0 for both and then here we are basically concatenating both of I and J and then we are passing that first we are checking that if that I is not equal to C this is for that scenario that the word itself doesn't go ahead and check for a palindrome because if a word itself is fast then it would be surely a palindrome we all know about that so that's why we are saying that if it is not equal to that index itself and its palindrome is true then we will be pushing that pair so this was the root poor solution here you can clearly see that this is N squared solution right and then while we are going ahead with this palindrome thing so here palindrome you can clearly see it will be up to the length of the string which is being covered right so that's why this whole solution becomes order of n square into the length of that word that is this one so this is how this solution becomes and this is the fact that it was giving us tle because here you can clearly see that this solution comes out to be 3 and then 3 6 right into the length that is 10 raised to the power 2 so it becomes 10 raised to power 8. then it gives us tle so that's why it was giving a tle now comes the part that how we are required to modify this particular solution you know we were doing it clearly that we are just passing that particular word and then taking that it is a palindrome or not means after concatenation of those words it is a pandem or not but for overcoming with the tle part and for using that length of the word rather than the number of the words as the most we can say most dominant factor in this solution we can take Force each length in such a manner me taking for the prefix and the suffix of that particular word so in that context what we can come up with is that when we are taking for the prefix part and thinking that if that prefix is palindrome or not and or we are thinking for this topics of that word if it is a paradigm or not then a particular portion that is the middle portion is only left right and that middle portion can we can easily accommodate if we find in the reverse order so all this by this thing only we are able to come up with a solution we in which we are using try so basically even if we use a map or unordered map in this case so you can clearly see that in unordered map or map we have an property that the unit elements are basically eradicated in that sense right so because of that only some test cases might miss and taking care of that test case is only the lead code has presented some more test cases where only a try solution will work and that's why even the another map solution were giving TLD so now let us go ahead with the try solution where even the duplicate words are being kept and we can easily in life but the core factor for this is that we are using prefix and suffix matching so that we could come up with the palindrome even with the partial portions of that particular lens and in that try solution also the way we were taking care that particular index is not the same about which we are finding this also we are required to take care and one word uh thing which that will add up in our dry solution that I'll let you know later so let me explain you that how we can come up with a try solution so let me show you the explanation part for the same then I'll show you that how we are recorded so here is the part so basically in general how we do a try solution we are having a root and then each Alpha that is having their own words so that the thing is there in the try and how we are able to recognize that particular word is ended so for that particular Factor we always Mark the end of that word as true right and or other are basically Mark that false right that is the scenario but in this case we won't be doing like that and the reason for that purpose is so that's it if this SLL is there right um let me yeah here you can see that there was one word also F right so s itself is a palindrome right so the thing is that when we add this s in our this particular try right so if it is marked as true right so the thing is then when it is marked as true then in that particular scenario when it will be checking for this particular node then it will say that it is a palindrome and it will store what was in this for this it was three right so it will store in our answer as 3 comma 3 which we don't want right so that purpose only we are basically taking the end of each word with the index of that word so that's a scenario which we have to eat in our drive this is the first thing which we tweaked and the second thing is um we are storing are each word in the divorce order so that when we Traverse our given string right so in that particular scenario we will be traversing in from front to back right but here we are storing from back to front so we will be easily able to come up if the index of that word is not equal to the index of the given word right and if it is a complete match then surely we figure out that it is a palindrome and we will store that so that is the thing and that's the reason we are storing every word in reverse order so now let me say that storing words in storing words and try in reverse order in the words in reverse order and marking end of the word by its index and if that word is palindrome then the index is stored in the palindrome index so basically I'll try node is something like this that uh in our try note we are having index we are having this palindromic index Vector means palindromic index Vector is there this isn't and this is Vector this is One external thing which we are having and for storing each word we are having a root which is basically of size 26 so these are the three things which names are dry node because for creating a particular trial even in tree also because the tree and drive basically from tree is a type price basically a type of tree only in tree how we Define a particular trees let us take a binary tree so in binary tree we all know that there is left and the right so left load and right node are basically two pointers which are basically pointed towards the left side of the binary and the right side of the binary tree right so that's why we are having left node pointer right node pointer and they wrote node pointer in a binary tree so like that only in a try the mandatory to think that one is the index which marks the end of the word and the other one is the root a note basically this is that pack which will be storing at all the words which are being there and this is one extra thing which we have taken as per this particular question that is Vector of parallel Atomic index which will help us to come out of this particular solution more early more oily and able to come up with all the test cases which are being there so now let me start with that here it is now clear that how we are storing first thing is that we are storing in reverse order so at each but each what we say at each character we are having minus one but when it comes the end of the word then we will be storing the index of that particular word you can clearly see that here end of the word is zero here it is 1 here it is two and here it is 4 but in each other there is minus one so this reflects that end of the word as not reach now come to the part this was for the index and the true 26 which was there now let me explain you for this portion means Vector palindor Mendes so now the thing is that checking for prefix and suffix nothing to reduce time complexity for such cases so for this purpose only we are storing indices in our that particular palindrome index so the thing is that if we take a test case ssabc and there is some other word CBE so in this context we see that SS is a palindrome right so for this particular this pre-six index because of particular this pre-six index because of particular this pre-six index because of this only the index of that word would be stored in our palatomic index and then when we uncount so the thing is that this ssabc this is a pallet room right so because of this that index would be simply stored in our palindromic index so that would be the thing now comes the part then we are when we will be able to encounter this particular word and this particular word was already there in our previous one right so because of this purpose only we will be able to get and because of this prefix and suffix matching only we are easily able to check that is that particular word or calendar with other word or not and in that context only we can uh we would have been missed this case which makes a palindrome right so that's why we are maintaining a different panoramic index Vector of the vector where we can easily check for this case that is a partial word is also a palindrome then is there other part is there any other word which makes us other partial word as the paliderm or not so that's why we are storing in palindromic index and now the other thing which I have already explained that we are storing the end of the word index to word matching of the word by itself right so this I have already explained so this was the overview of this Tri solution now let me show you the coding part of this particular solution so that you could come up with uh that maybe it becomes much more clear for you so that's why let us go ahead with that portion so after it checking out the explanation you can clearly see that this explanation becomes that it is more prone towards the length right so that's why here the time complexity is basically order of L Square y l Square because we are taking length of each word with other word because we are going out with prefix and suffix so that's why it becomes L square into n because how many times we are going ahead with this matching is equal is basically the number of words so that's why it's l square into n and the space complexity is basically order of n into l and this is also somehow completely dependent upon the try which we are making because the number of words which are being there and the back end which could be taken so according to that only it's n into it but it could be also at worst case scenario it could become n square into l but that is a worst case scenario which can be reached and cannot be reached that all depends upon the input of our words so that's why here the time complexity is this Methodist complexity is this much now comes the part that how we are required to code this solution so that's the other thing now let us go ahead and code the solution so here's the coding part yeah so this was a brute for solution which I had explained now comes the path for it optimize solution so here you can see the optimal solution yeah okay we can't do more okay let me start from so here is the product try note so here we are taking three things one is the root itself which I've marked tells me next that is try not start next or 26 by 26 because we all know that in English alphabets we are having 26 characters right so that's why I've taken as 26 and it is starting initialized with empty strip next one is the power for INT index equals to minus one that I have already explained that how minus one then next comes the part Vector of in palindrome indices there we are basically storing all the indices for those three section surface which are basically palindrome so that's the thing now here we are basically adding all the nodes which are being there in our try and here we are checking for the palindrome and this is you can see the driver code and here we are basically searching for those words which are being there in our palindrome now let us start from this so here whatever the size of this is so that taken and then now here we are calling that add function is basically for making a try so here we are passing the first word and in this first word we are passing with the index so that when the word ends then at that moment only we store that index to the end of the word and now here when we are adding that how we are adding that let us check for that particular moment so the thing is that first we are directly taking that particular route as a reference here we have already taken that right so we are taking by reference that particular route and then here we are going from the reverse side of that particular word and then we are checking that is palindrome S 0 J right and then what we are doing we are directly if at that particular moment are that particular word is having the prefix which is a palindrome right then we are directly pushing that particular index to our palatomic index Vector so that's the thing which we are doing here now go into the next part so we are basically making a try right so how we make our time we basically say if that particular character or entities already exist or not if that doesn't exist then I try then we make a new node of that right so that's the thing which we are doing here we are first converting that to integer and why we are converting that to integer because we have taken to indices till 26 right so it comes into the range of 0 to 26 only that's why we are converting each character in the range of 0 to 25 by subtracting minus 8 so by subtracting a from that so now we are checking that if that particular character exists in a dry or not it doesn't exist then we are making a new node out of that by this thing and then we are moving ahead so connecting with the next two means for the next time and then like this here then this particular for Loop in means basically now we have added all the words from our basically all the characters from our word then at the end what we are doing we are okay we are here masking the end of that particular word with i that is now our index would be marked as I earlier it goes at each moment as minus 1 only now here P will be pushing that particular index to a palindromic index so that's the thing which we will be doing at the end these all things are just for that type when prefix is matching with the palindrome I mean basically that prefix is a palindrome when we are basically pushing dot those indices at this particular moment and if we have already pushed that particular word into our tribe then we are pushing at the end that index so this is the thing now here comes the part taking for the problem this is that common thing only that how we check for the palindrome so this is all now consistent part that searching for that word so how we are searching for that word is we are now traversing from front to back now we will be checking if there is a match or not so basically here we are taking our a of I means that particular word means that string and then here we are taking that particular try now we are traversing by taking that particular word we are traversing that word only that's the thing which we are doing here and we are also keeping a check that if that node exists or not if that exists then only we'll move it as come out of that so that's the thing say here if that particular node index is not equals to minus 1. that simply refers to we have a raise the end of the word so in that scenario only we will next thing which will take is that if that index the same as the index at which we are presently if that is also not the scenario then we'll check for the next condition that is that particular whole word a palindrome if that if then we'll post that particular into our answer whether that index and the index of that particular word which we were traversing till now so that's the thing which we will be doing here and now constip parts we will be traversing now our next note so that's the thing we will be taking here and then if a node doesn't exist because then it does it doesn't exist then it will come out of here so it doesn't exist then we'll continue that is we will be now checking for our next particular these basically or next word that we will be taking here and then now here come to the part for the indices which we had stored earlier so now we will take for each index in a palindrome index so the thing is that if that I doesn't equal to the J right is if it is not the same then we will be pushing that particular to our answer and then at the end we will be returning our answer so this was the whole thing which we will be doing in this solution and I have already explained the time complexity and face complexity for this particular solution this thanks for watching and if you really like this video then please do like and subscribe to my channel and do share among your friends so this was all thank you
|
Palindrome Pairs
|
palindrome-pairs
|
You are given a **0-indexed** array of **unique** strings `words`.
A **palindrome pair** is a pair of integers `(i, j)` such that:
* `0 <= i, j < words.length`,
* `i != j`, and
* `words[i] + words[j]` (the concatenation of the two strings) is a palindrome.
Return _an array of all the **palindrome pairs** of_ `words`.
**Example 1:**
**Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\]
**Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\]
**Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\]
**Example 2:**
**Input:** words = \[ "bat ", "tab ", "cat "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "battab ", "tabbat "\]
**Example 3:**
**Input:** words = \[ "a ", " "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "a ", "a "\]
**Constraints:**
* `1 <= words.length <= 5000`
* `0 <= words[i].length <= 300`
* `words[i]` consists of lowercase English letters.
| null |
Array,Hash Table,String,Trie
|
Hard
|
5,214,2237
|
1,399 |
hi my name is david today we're going to do number one three nine count largest group this is an easy level problem on lead code and want to solve it in javascript so we're given an integer n that we take in and each number from 1 to n is grouped according to the sum of its digits return how many groups have the largest size so for example n is 13 the output is four and we have to loop through one to thirteen one here to 13. and then we group together by how they're added together it's kind of confusing at first but you get the idea that one adds up to one and this also adds up to one plus zero is one and there's just this is group for two and this is that's the height this group has the highest amount of two indices and then there's four of them so we return four so the key to looking at this whenever we see something that we have to divide by a digit we want to use the mod 10 feature we don't want to make it a string so think whenever we have to go by digits think mod 10 divided by 10. so let's get to this so how we're going to do this is that we're going to create well we have to create the output create output variable and we set it equal to 0 first and next we create the max length variable create max length however it is max size which mx size variable and now we can create a map create an object to keep track of everything to create count object and that's going to count keep track of the numbers and their accounts and now to fill out this count object we loop through n and inside of this loop we have to create a num variable that we're going to be dividing by 10 like i said that before with the current number and then also create a sum variable so and then once we have variable set up we have to create a while loop while num is greater than zero we're gonna have to manipulate it and then have the conditions well we're going to add some by the mod 10 of num add some by mod 10 of num so for example when we goes we for this one we start at one mod ten is one so one gets put so for the number one the sum is one and then number two that's almost two but then when we get to 10 here we go so from 1 to 9 is just going to be equal to each other and then what we want to do next is we have to change the num divide num by 10 so we look at the one so for 10 we look at 10 mod 10 is zero and then we divided by 10 so one and then we do the same thing we did it for one before and then we got one so the num of this object is going to be from one through nine and then the count the values the count of it and then we do that and then we have to create the condition if we define our new max length okay sorry and then we have to add this to the object add the num and the sum so add ah sorry the sum is going to be the key to count and then increment it when we see it and then the values we get it find the max size with the values of count to the highest value we have account will be the max size of it and then once we get fill this out this count object we have to look through it again loop through count condition if value is equal to max size and then if it is we increment output and then lastly we return output okay so put in the code that output equals zero that max size starts off at zero that count as an object now we loop through n for that i starts off at one equals to one i is less than or equal to n i plus and inside this we create the variables that num equals i and then let sum starts off at zero and now we do a while loop while num is greater than zero we have to look at the sum of it of each digit so sum plus equal num mod 10 and then we change num equals num divided by 10 and then we need the math.4 math.4 math.4 because there might be a decimal and now we got that we will have to update the object so count sum is what we're looking at and then equals to we'll use this syntax to see if it's not in there we set it to equal to zero and if it's near we just set it equal to whatever it was and then we increment it by one regardless and then after that we find the max size so max size equals math dot max whether it's the current max size or count so and we can see here we can cancel our count so you can see it gets to the sum of it and how many times it occurs so for this we this is the 13 one we got okay so after that we do the object for that key in count and inside of this we create the condition if count index key is equal to max size we increment output plus and then once we finish this we return output great we got it so the time complexity we know that we're looping through n so it's going to be of n and we'll also we've been through count here but count is this is always going to be smaller than this so it's going to o of n and then the space complexity we're creating this map these constant this is proportional to however long this is so it's going to be o of n as well so that is how you solve this problem thank you
|
Count Largest Group
|
page-recommendations
|
You are given an integer `n`.
Each number from `1` to `n` is grouped according to the sum of its digits.
Return _the number of groups that have the largest size_.
**Example 1:**
**Input:** n = 13
**Output:** 4
**Explanation:** There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
\[1,10\], \[2,11\], \[3,12\], \[4,13\], \[5\], \[6\], \[7\], \[8\], \[9\].
There are 4 groups with largest size.
**Example 2:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are 2 groups \[1\], \[2\] of size 1.
**Constraints:**
* `1 <= n <= 104`
| null |
Database
|
Medium
|
2046,2097
|
206 |
all right so let's take a look at another linked list problem this one is just called reverse length list it's very common in problems that you might have to reverse a linked list iterate through linked lists so in this particular case let's talk about how you would reverse one so you're given the head of a singly linked list you need to reverse the list and return the reversed list so to return the list typically you're going to return whatever the head is and so if we're reversing it you'd most likely be returning the five note after it's reversed as you can see in this image one two three four five reversed five four three two one so how would you go about reversing it uh you're probably going to want to uh you know change what the one points to so the one is going to end up pointing to nothing and then you're also going to then make b2 point to it so how would you do that you would have to probably consider maybe multiple pointers maybe you know what the next one is and as well as you have some sort of previous list node that you're going to be using to set the value that you have so what i mean by that is let's say we started off with a list node previous set it to null so that way when we're first iterating through our list one can be set to point to that null value and then when you get to one you could set one as the previous value so when now you're at two you can make two point two one and so forth so let's go ahead and try to do that so as i said you're going to want to have a previous node and that will get updated so that way you can point each node to the previous one as you're reversing it and you also now need to iterate through the list so we're starting at the head and we'll say while it's not equal to null we're going to essentially uh keep iterating the head into the end of the list so now here's the important part uh we're going to want to point that head node or whatever the head is as we're going to be changing it as we move through the list we're going to want to point its next value to uh the previous one so let's go ahead and do that now and i'll also talk about something you need to do before that so head dot next equals prev and then you could also make prev equal head so that way when you move on to the next one you can end up setting that next value it's next to the previous instance and we'll actually also just say head equals head dot next now that part that i said was important you need to also have some way for this to actually work so what i mean by that is i went ahead with the naive walking through the solution not thinking about it to kind of showcase this issue when you change head.next equal to previous you change head.next equal to previous you change head.next equal to previous you actually don't know what head.next is actually don't know what head.next is actually don't know what head.next is you lose that so this will essentially end up looping on itself because you've changed the head.next and then you set changed the head.next and then you set changed the head.next and then you set it to brief and then it just ends up becoming brief and it's going to obviously not work as intended so instead what you need to do is also create some sort of temp value or actually let's just call it next because it really is the next value in the list and we'll say that it equals head.next we'll say that it equals head.next we'll say that it equals head.next so now instead when you want to bump the head value you say head equals next this is so that way you again have some temporary storage of the next value so when you reassign it you don't lose what it is and now after that is all said and done you've now gotten to the end of the list you now need to return the new head and the new head will actually just be that previous node reason being let's go ahead and walk through this here as you keep iterating through the list you're constantly saying as you come here to 1 this becomes the previous node then you enter h2 and it's the previous all the way to the end were five and once you got to five it is considered the last previous node that you were working with so that is actually the head that's what we want so coming back down here again let's just go ahead and submit this and as you can see it was accepted basically it's just going to be big o of n which is just the length of the list being that you're just iterating from beginning to the end list and you have constant space because you're not allocating you know any extra space other than this previous node and this next node but that's not considered uh you know big o of n or anything like that because you're not storing a copy of the list or anything to that extent so it's just constant space to store those two values and that's it if you have any questions about this problem or you want to see another problem specifically in the future let me know in the comments below and please take a moment to like and subscribe for future content thank you
|
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
|
1,388 |
hey what's up guys this is chung here so today let's take a look at number one thousand three hundred and eighty eight pizza with three n slices so there's a piece of this with three n slices of varying size and you and your friends will take slices of pizza as follows and basically you if you pick any pizza right and then your two friends alit and bob will take the pizza on each side of this pizza right and there is a like for example if there is a one two three four five six pizza right for example you if you take number four so alice will take number three bob will take number five same thing right same thing for the other one let's say if you take number six here so alice and bob will take number one and number two so which means that this is like a row like a circ a circle right and it's number one and number six they are connected to each other right and then it asks you what's the maximum possible sum of slices you can get right for example if this we have one two three four five six here so the maximum we can get is ten so how do we get 10 right so the 10 is like this so first we take number four so once we take number four three and the five is gone right so the only thing we can take is from one two or six and of course we'll take six that's why the total is ten right and here's another example here right and then there are some like constraints here so the size of the length is within 500 and the length of the size uh has to be a it's a can be divided by three right and yeah so that's the description of the problem you know actually if you watch these things closely and you can realize that you know basically this when once you take number four here right you cannot take number four i'm sorry once you take a number four here you cannot take number three here all you can take is between one and three right so this is kind of actually the problem it's very similar like the uh the house robber number two right if you guys remember what does the house rubber number two is that we also have like a like the uh array right and you can only you cannot rob two consecutive house and the same thing as this one the last one the first one they are considered to be next to each other which means that if you take the first one you cannot take the last one same thing for same thing if you take the last one you cannot take the first one right so that's that i mean the only difference for this problem than the uh than the house robber number two is that you know for the house robber number two here you can take up to two to the power of n sorry not you can take to half of the undivided by two number of houses right because you can take this one and this one right but for this problem you can only take exactly and divide it by three number of uh number by this number of houses the you can call the houses or in this case it's a size of pizza right because it says that you know every time we will take one we'll take one pizza when one piece the other two person will take two other pieces so in total you can only take item you have to take exactly undivided by three number of pieces so that's the difference i mean since we have these constraints here right i mean we can you we can still utilize the technique to calculate the at house rubber number two here but only for this one we have to introduce a second dimension of our dp here which means that you know for the dp we have dpi and j right so the dpi means from zero to ice slices so this eyes is one base so this is one base here from zero to ice slices right and we have taken like js pieces right we have taken this j pieces and the j is like what j is the limit is undivided by three right so that's why we have to kind of like this uh have this kind of two dimensional um dp state and in the end we simply have this one kind of dp like the n right which is the size of the slices and how about the j is like the n divided by three right so that's our final state right and the next thing is that we have to take care of the uh this circle thing right which means that we cannot take the first one and the last one at the same time so i think for me the easiest way to fix this one is that we have to basically do two of the dp we have to do the dp twice so let's say for example we have one two three four five right we simply do a dp for one two three four five once and then we do a dp for two three four five six one more time because with this one since we have already removed the last one we are making sure that no matter how we choose right even though we choose number one and number two sorry uh this is one and five at the same time right it's guaranteeing that it will not violate our conditions same thing for this one right so this it's okay if we choose two and six at the uh at the same time that's how we handle this like uh circle thing yeah and with this two here right and then all it's left all the left is that we just simply do a an acid for loop right and then the dp state transition function will be dpi equals to what so at the current i right at the current i um we either choose to pick to take the slice or we don't take it right so it's like zero it's like a classic zero one uh case right so if we don't take the uh if we don't take the current slice it means that we have dp i minus 1 and j right because we since we didn't take the current slice so j didn't increase that's why we just have this one if we decide to take the current slice what's going to happen so of course we have it so this is going to be the max right going to be the max out of this two right so this is that we don't take the this slides the second one is we decide to take the slice again if we decide to take the current slice then it means that we can only start from i minus two right because if we take the current slice and then it means that someone will take the i minus one that's why we have to the next state for us we're starting from i minus two and of course the now it's going to be j minus one because the previous since we are currently taking a slice that means that we're gonna have like j minus one state for this state right so that's basically the state transition function for us and this kind of analysis here we can start our coding so actually the coding is kind of surprisingly short you know like i said you know so we're gonna have like n right so n is what the uh so the total number of slices we're gonna take is the n is the length of slices right slices divided by three right so that's the first thing and then like i said we simply call two we're gonna have like all right sorry i just got a phone call all right let's continue um so i'm gonna have like a helper functions to help us calculate the uh the maximum slices we can get right so we're gonna have like get max slices right so i'm gonna pass in like the uh slices right so this is actually a new slices but i'm gonna still using the same variables name here and assuming we have this kind of helper functions here and i'm going to call it help max get max slices right so i'm going to pass this slices that from the second one to the last one right so that's the first one and the second one is get max slices right and the other side right so this is how we do a the slicing in python right and so we so the first one is from the second one to the last one and the first one and the second one is from the first one to the n minus one right from and then among all those among those two values we get the maximum right that's going to be our final answer and now all is left is like this right so now we have a i'm going to have like an m equals to the length of slices right and i'm not going to have a dp here so at the beginning everything is zero right so and uh so the second dimension is like the n plus one okay because anyway when you take exactly this number of slices right from this pizza and the first dimension will be the range of this number right of this uh this new slices here and then for i in range of one to m plus one right and then the second one is for j in range of one to n plus one okay so like i said the state transition function is simply the dp i j equals to what max the first one is not picking the current one which is the i minus one j right and the second one is to pick the current one so to pick current one we're getting the numbers regarding the uh the values of that slices which is the slices that i minus one right since the uh this one is one base and the slice is zero based right so and then we have like this dp if we pick the current one it's going to be the dp i minus two right so because the i minus one will be the dpi minus one will have already been taken by someone else and then after this one the previous state will be j minus one because we are taking one that's why the uh the previous one is j minus one but you know okay so here is something we have to be this is like one of the corner case which is the you know since we're doing i minus two here right as you guys can see here so we have the i starting from one right so we have to do a simple check here you know we only do this thing if the i is greater than one else zero right so let's do these things here so it means that you know if it's a first basically if the i equals to one we simply uh we simply just use the slices it kind of makes sense right because you know if there's only one if they're if they don't they're only one slices left we can we simply just take that one and there's no previously state for that right and when the uh when the i is greater than one then we have a we can just use this state and once we take the current i so the previous state will be i minus two and then j minus one right so in the end here we can simply return the dp m and n so this dp means the uh the biggest slices the biggest value we can get with the first m basically with all the other slices available and we pick n numbers of the numbers from the slices right and then here we have a here we do this max right and then there you go so if i run the code here what import system go here missing one of the parentheses okay yeah so it's accepted i mean real quick for the time complexity right i mean it's pretty straightforward right we have an acid for loop here that's why the uh so the outer loop is m right so we have a m times n that's going to be the time complexity and the space complexity is the uh it's same for the o of m times n but i think we can simply compress this space complexity from of m times n to o of m because we only need two previous state as you guys can see we only need dpi minus one and dpi minus two right that's why we can just remove this n dimension space complexity but i'm not going to do it here i'm only doing this main logic here yeah i mean just to recap for this problem real quick you know the uh so basically this problem is another format of a variation of the house robber problem the only difference is that you know for this problem you can only rob exactly undivided by three houses and also we also have this kind of like the uh the circle thing and whenever we have circle issues we at least that's for me i always use this kind of technique basically i try to rob from the first one from the second one to the last one or from the first one to the n minus one right the second off from the last one that's how i handle this circle thing and inside of here right since we have we need to rob exactly a number of houses that's why we need to have 2dp state and the not too deep state i mean i said that we could get rid of this one i mean i we need to have like two for loops i didn't mean to have two db state but we still we need to have four uh two full loop nested for loops here so the outer loop is the loop through all the slices from the first one to the last one and the second for loop is to loop through and how many slices we can get among from the from this zero to ice slices you know we have some like of invalid states along the line here but those are not going to affect our final result because all we need is the dp the final one dpm mn here right and this is kind of like a very classic technique one of the uh the dp type right which have we have two dp state a two for loop here and the other loop is to loop through the uh the slices and the inner loop is the loop through the second dimension right and then here and then we also have like this kind of classic zero one scenario which we either pick the current sl element or we don't pick it and if we don't pick it means that second the second one didn't change right and the number of slices we get didn't change and then if we pick it and that means that we have to jump two more back right to get the previously state all right cool i think that's pretty much what it is i want to talk about for this problem and let me know what you guys think and otherwise i'll just stop here thank you so much for you guys to watch this video and stay tuned see you guys soon bye
|
Pizza With 3n Slices
|
greatest-sum-divisible-by-three
|
There is a pizza with `3n` slices of varying size, you and your friends will take slices of pizza as follows:
* You will pick **any** pizza slice.
* Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
* Your friend Bob will pick the next slice in the clockwise direction of your pick.
* Repeat until there are no more slices of pizzas.
Given an integer array `slices` that represent the sizes of the pizza slices in a clockwise direction, return _the maximum possible sum of slice sizes that you can pick_.
**Example 1:**
**Input:** slices = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
**Example 2:**
**Input:** slices = \[8,9,8,6,1,1\]
**Output:** 16
**Explanation:** Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
**Constraints:**
* `3 * n == slices.length`
* `1 <= slices.length <= 500`
* `1 <= slices[i] <= 1000`
|
Represent the state as DP[pos][mod]: maximum possible sum starting in the position "pos" in the array where the current sum modulo 3 is equal to mod.
|
Array,Dynamic Programming,Greedy
|
Medium
| null |
1,252 |
hey how you doing guys it's ilya bella here i recording stuff on youtube chat description for all my information i do all lead code problems make sure you um subscribe to the channel give me a big thumbs up to support it and this is called self with all values in the matrix um given and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices at i is equal to r i c i for each pair of r i c i you have to increment all cells in row r i and column c i by 1. return the number of cells with all values in the matrix after applying the increment to all indices let's look at this example you get n which is 2 m which is 3 indices 0 1 output 6 explanation initial matrix which is uh you know zero and after applying first increment it becomes um one two one zero the final matrix will be one three one white one three one which contains six odd numbers right here we got n which is two and which is two indices uh one zero we return zero because final matrix uh 2 to 2 there is no odd number in the final matrix constraints uh both and m are greater than or equal to 1 and are less than or equal to 15. um the length of that array is greater than or equal to 1 and is less than or equal to 100 the value at the position of one at i zero into that indices is greater than or equal to zero and is less than n and right here i one is greater than or equal to zero and is less than m well um go for it first we need to create a two boolean arrays um let's say odd rows new let's copy boolean real quick let's say boolean um the length of that array is equal to rows and we got out columns um new boolean and right here we got m means columns then we are looping through this um indices row by row indices and we need to say r rose at the position of i at 0 we do x or bitwise true and we do the same for columns i at one x or true then we need to create uh two more variables which are the first one uh r is zero and the second one which is c is zero um next we create two loops the first one which is you know we say boolean um i and we are looking through these uh odd rows and at each iteration we count we calculate the number of rows which appear uh odd number of times in the case when i is true then we add 1 to that r otherwise we add 0 and we do the same here for columns and um let's say c plus equal i uh then one otherwise zero and finally we return um any so n minus r multiplied by c plus um m minus c multiplied by r which means um an initial um rows minor minus rows which appear odd number times multiplied by uh columns that appears odd number of times plus uh initial columns minus columns that appear uh odd number of times multiplied by rows which appear odd number of times that's it let's run this code um good let's submit success so what do we got um initially we got odd rows and odd columns which are uh set up to false and columns um the length of that on rows is uh you know we got right here as well we got um zero one and we have um false and here we have um also zero 1 2 then i mean we're looking at this example right so we got 2 which is n m which is three then um then all columns are set to false and false then we are looking through these indices which are here and we are at the first row um are you know right here um into that odd rows uh the position of zero we see that it's set up to false uh bitwise uh x or bitwise means that suppose we got um we got um you know zero x or 0 is 0 then 1 x or 0 is 1 one x or um one is zero the same uh we got when we let's say we got false x or false which is false then true x or false which is um true through x or true which is false um so we have here um false x or true is equal to true then um at the position of one into that odd columns we got false x or true which is true then we are here at one we got true and at one right here we got again false because that's even then we break out of that loop and we are here are which is um zero then c zero and we are looping through these rows or draws and we can see that at the position of zero we got true so we increment r by one we add one we got one instead of zero then we again increment by one we got two instead of one then we out of that loop we are here we are looking through these out columns we add the position of zero initially and we can see that you know we got false and false so we got a bunch of zeros zero then now we return n which is 2 minus which is uh 2 multiplied by c which is 0 plus m which is 3 minus c which is 0 multiplied by 2 that means that here we got zero plus um plus six and we return this result which is six that's the whole problem thank you guys for watching leave your comments below i want to know what you think follow me on social medias i do all lead code problems big me give me big thumbs up to support my channel and i wish you all the best bye
|
Cells with Odd Values in a Matrix
|
break-a-palindrome
|
There is an `m x n` matrix that is initialized to all `0`'s. There is also a 2D array `indices` where each `indices[i] = [ri, ci]` represents a **0-indexed location** to perform some increment operations on the matrix.
For each location `indices[i]`, do **both** of the following:
1. Increment **all** the cells on row `ri`.
2. Increment **all** the cells on column `ci`.
Given `m`, `n`, and `indices`, return _the **number of odd-valued cells** in the matrix after applying the increment to all locations in_ `indices`.
**Example 1:**
**Input:** m = 2, n = 3, indices = \[\[0,1\],\[1,1\]\]
**Output:** 6
**Explanation:** Initial matrix = \[\[0,0,0\],\[0,0,0\]\].
After applying first increment it becomes \[\[1,2,1\],\[0,1,0\]\].
The final matrix is \[\[1,3,1\],\[1,3,1\]\], which contains 6 odd numbers.
**Example 2:**
**Input:** m = 2, n = 2, indices = \[\[1,1\],\[0,0\]\]
**Output:** 0
**Explanation:** Final matrix = \[\[2,2\],\[2,2\]\]. There are no odd numbers in the final matrix.
**Constraints:**
* `1 <= m, n <= 50`
* `1 <= indices.length <= 100`
* `0 <= ri < m`
* `0 <= ci < n`
**Follow up:** Could you solve this in `O(n + m + indices.length)` time with only `O(n + m)` extra space?
|
How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.
|
String,Greedy
|
Medium
| null |
1,074 |
weekly contest and apologies I am a bit late today the reason being I went to office had lots of work I came back around 8:30 had dinner took some rest around 8:30 had dinner took some rest around 8:30 had dinner took some rest and here I am in front of the laptop however in the evening I released best technical resume template for all the college students who are looking for resume creation from internship internships and J job perspective so do check this video out here I and Jen one of the subscriber of coding decoded who works at Morgan Stanley reviewed four to five rumes and while this session you will get to know the most common mistakes that are committed especially by the college students while building their resumes while crafting their the it up and in the end we have also shared a template that act as a reference for all of you guys on how to build or craft your resumes efficiently that will catch hr's attention so do check this video out it's a long video but I'm pretty sure it will keep you engross throughout the session I'm attaching its Link in the description below so do check this out whenever you get some time and I'm pretty sure it's not going to disappoint you guys now let's get back to the problem number of matri that sum to Target also let me just introduce myself for those who don't know me I'm s Deja I'm working as technical architect sd4 toobi and today's problem is a hard problem it's indeed a hard problem however it's an extension to one of the previous problem that we have solved in the past so even before jumping onto the previous problem let's try and understand the question here we are given a matrix and a Target value what do we need to identify the number of non-n sub Matrix that number of non-n sub Matrix that number of non-n sub Matrix that sum up to the Target the question is pretty understandable so you need to identify all those the count of those sub matrices that sum up till the Target and if I ask you guys have you seen such a question in the past obviously you will say no we haven't solved such a question in the past but we have solved 1D type of the same problem this is a 2d problem we have solved 1D type of the same problem which is subar sum equal to K lead code 560 this question is a prerequisite question for solving this one so because this is an extension of the same concept over 2D this is for 1D so I will urge you guys to First have the look at this video here we will be using prefix sum and maps to come up with the algorithm and once you gain enough understanding of this algorithm then only jump onto this problem for those who have already aware of this concept this video is for them I'll be sharing more to it in the presentation section so let's quickly hop on to it and I'm restating that lead code 560 is a prerequisite here an array is given to us and we are also given a Target value what we need to identify the number of sub matrices in this 1D are AR that sum up till the target value and in today's problem we are given instead of 1D 2D Matrix so how can we extend the same approach using maps and prefix sum to actually arrive at the solution so I hope you went through this video and consider this method as a blackbox helper method wherein if you are given a matrix 1D Matrix and a Target value you are able to count all possible number of sub matrices that exist in this 1D Matrix to give us the target sum value so let's with this assumption let's proceed ahead now it's time to apply the same algorithm over to a 2d Matrix so the intent is really clear what we need to identify the sum of the each and every submatrix that exist in this entire 2D array and once we have that sum value we can compare it to the Target given value and in case both of them turns out to be equal we increment the count value otherwise we skip it up so the intent is really clear if we are able to identify the sum of each and every submatrix that exists in this entire array our work is done so let's go step by step let's consider the case where we only have the first row available to us and what we can do since we have only one R available to us we can apply the previous algorithm this one prefix some plus map based approach onto this first row and we can identify all the possible sub matrices that exist in this row so it would be one would be this one other one would be this one the third one would be next one would be this one the fourth one would be this one fifth one or fourth one would be this one so using this algorithm prefix some plus map based approach is it can be easily identified in time complexity of order of one so the first row gets covered now comes the concern what we will do we will simply add the elements up starting from this particular row onto the next row so let's go ahead and add them up what do we get 0 + 3 is 3 1 + 4 is 5 so let me we get 0 + 3 is 3 1 + 4 is 5 so let me we get 0 + 3 is 3 1 + 4 is 5 so let me just write five over here then 2 + 5 is just write five over here then 2 + 5 is just write five over here then 2 + 5 is 7 now we have a row which is something like this 3 5 and 7 what we will be doing we'll be applying the same algorithm that we talked about over here prefix some plus map based approach onto this particular row and what all cases will it cover it will cover all the cases inclusive of the first two rows let me just highlight few of the cases the one could be this one other one could be this one next one could be this one followed by combination of these two followed by combination of these three the other could be this one and the next could be this one because as per this algorithm we will be again identifying the prefix sum over this entire and using the map based approach in order to identify those sub matrices wherein the some turns out to be equal to the Target value and let's proceed ahead let's apply the same algorithm onto the next row as well so in the next iteration what we will be doing we will be adding these values 3 5 and 7 onto 6 7 and 8 so let me just go ahead and write the total sum will turn out to be nine here would be 12 followed by 7 + 8 is 15 and again we followed by 7 + 8 is 15 and again we followed by 7 + 8 is 15 and again we will apply the same prefix sum map based technique in order to identify the sub matrices where the total sum turns out to be the target sum and what all cases will it cover it will cover all the cases starting from the first row up till the third row so let me just highlight few of them one would be this one other one would be this one followed by combination of the these two followed by combination of these three followed by combination of these two and this one single as well so here you will see all the possible combinations wherein first row is included second row is included and third row is included gets covered now comes the concern are more Cases left the answer is yes so what are those cases let's start the iteration instead from the first row to the second row which is 3 4 and five so let's redo the same iteration starting from 3 4 and 5 and using this row we will again apply the same prefix some map based approach and what all cases will it cover so consider the first row has gone we are only focusing on the second row this time now it's again time to apply the map based prefix some approach onto this entire row and what all cases will it cover it will cover these cases 3 Ted independently for four treated independently five treated independently the combination of three and four combination of three four and five combination of four and five treated independently as I already told so all possibilities that could exist in this entire row gets covered that means we are done with this iteration as well now what we will do we'll combine the second row and the third row so 3 + uh 6 second row and the third row so 3 + uh 6 second row and the third row so 3 + uh 6 gives you 9 4 + 7 gives you 11 and 5 + 8 gives you 9 4 + 7 gives you 11 and 5 + 8 gives you 9 4 + 7 gives you 11 and 5 + 8 gives you 13 and let's again apply the map based prefix some approach we are using it as a tool across all the rows what all cases will it cover it will cover all the cases that form the combination of the second and the third row so to highlight let's do that 36 47 58 3 uh 3 4 67 4758 58 independently and 3 6 47 58 considered all together so when we apply prefix sum approach onto this row all the possible cases gets covered so we are done with the matrices that start from the second row and it's time to extend the same algorithm onto the third row itself so this time what we will consider all the subm matrices starting from the third row and what would be those 6 7 and 8 there are no more rows ahead and we can simply apply the prefix sum map based approach onto this row and it will cover all the possibilities that could exist in this row and with this we have successfully considered all the possibilities that may exist in this complete 2D Matrix and in order to understand the code fully how it's how it is operationalizing let's quickly walk through the coding section and I promise once you will go through it you'll get a good hold of the concept the first and the foremost thing that I have done here is to use the solution from sub array sum equal K so I've exactly used the solution that I proposed over here and I have treated it as a blackbox so if you go and check that solution I have copy pasted it over here and I'll be using this in order to derive the solution so let's walk through it I'm not going into the details of this helper method for this you need to visit that video so let's walk through the rest of the algorithm here I have taken two variables n and M one for the row count other one for column count and this array represents some row represents the row that will be considered at any particular time for operating over subar some algorithm and the size of this row would be equal to nothing but number of columns that we have moving ahead I have created an answer variable I iterate over a for Loop and here the iterating variable is I that represents the starting row index and I have filled in this summed row to start with all zeros and I have created another for Loop wherein the iterator is St and it is acting as the ending row index so if you carefully observe then two things are changing there is basically a range of rows over we are over which we are considering in each iteration and these two for Loops is helping us derive those two rows starting row and ending row once we have identified those up what do we add the elements across the columns together and we form the sum draw once we have identified the sum draw we apply this algorithm subar sum over to sum draw and we pass in the Target so this problem reduces to 1D now and whatever answer is returned from this helper method we add it to the answer variable in the end we simply return the answer so let's try this up the time complexity of this approach is order of n² into m square into n okay there a typo this should be answer and this should be answer again let me just submit this accepted 90% faster it is pretty this accepted 90% faster it is pretty this accepted 90% faster it is pretty good memory usage is equally well with this let's wrap up today's session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more update from coding decoded I'll see you tomorrow with another fresh question but till then goodbye
|
Number of Submatrices That Sum to Target
|
high-five
|
Given a `matrix` and a `target`, return the number of non-empty submatrices that sum to target.
A submatrix `x1, y1, x2, y2` is the set of all cells `matrix[x][y]` with `x1 <= x <= x2` and `y1 <= y <= y2`.
Two submatrices `(x1, y1, x2, y2)` and `(x1', y1', x2', y2')` are different if they have some coordinate that is different: for example, if `x1 != x1'`.
**Example 1:**
**Input:** matrix = \[\[0,1,0\],\[1,1,1\],\[0,1,0\]\], target = 0
**Output:** 4
**Explanation:** The four 1x1 submatrices that only contain 0.
**Example 2:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\], target = 0
**Output:** 5
**Explanation:** The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
**Example 3:**
**Input:** matrix = \[\[904\]\], target = 0
**Output:** 0
**Constraints:**
* `1 <= matrix.length <= 100`
* `1 <= matrix[0].length <= 100`
* `-1000 <= matrix[i] <= 1000`
* `-10^8 <= target <= 10^8`
|
How can we solve the problem if we have just one student? Given an student sort their grades and get the top 5 average. Generalize the idea to do it for many students.
|
Array,Hash Table,Sorting
|
Easy
| null |
485 |
welcome to september's leeco challenge today's problem is max consecutive ones given a binary array nums we turn the maximum number of consecutive ones in the array if we're given an array like this we can see the maximum number of consecutive ones is going to be three like so let's not over complicate this our approach is going to be to use two pointers what we're going to do is have a left pointer starting at the very beginning the zero index and we'll have a right pointer that iterates down through our entire array now what we're going to check to see is this number a one now if it's a one then we want to just keep the left pointer where it is and we will calculate our maximum number of consecutive ones to be r minus l plus one so here at this very first point we can see r is zero l is zero so that's going to be zero plus one so our maximum length of consecutive ones right now is one now we continue on if we see that it's one we'll keep our left pointer where it's at and this will be r one minus zero plus one is equal to and indeed that's going to equal two but when we see that we're pointing to a 0 now what we're going to do is move our left pointer all the way up ahead to actually one ahead of the right pointer like this so now here at this point it's going to be 2 minus 3 which is going to be negative 1 plus 1 that's going to be 0. and z right here is 0 right and now we'll keep our left pointer here and each time we'll check to see if that's a 0 or 1. if it's a 1 we'll keep it and we'll calculate the maximum number of consecutive zeros and here i'll go all the way down up to here which will be a length of three so let's begin all we need is a left pointer as well as our output both of these will be zero and we're going to say four right pointer and number and enumerate nums first thing we'll check is if n is equal to zero because if it is then we want to move our left pointer ahead to the right pointer but remember add a one here so that we don't count this number as a one as well next we'll calculate our max which would be the max of output and r minus l plus one finally return the output and that should be it let's see if this works okay looks like it's working and there we go so time complexity is going to be of n and space complexity is going to be a one now there are some variations of how you can do this but really there's not a good way of making this any faster than this so that's it there are some variations but i think this is good enough all right thanks for watching my channel and remember do not trust me i know nothing
|
Max Consecutive Ones
|
max-consecutive-ones
|
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_.
**Example 1:**
**Input:** nums = \[1,1,0,1,1,1\]
**Output:** 3
**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
|
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.
How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
|
Array
|
Easy
|
487,1046,1542,1999
|
296 |
hello and welcome back to the cracking Fang YouTube channel today we are solving a notoriously hard problem 296 best meeting point given an M byn binary grid where one marks the home of a friend return the to uh the minimum total travel distance the total travel distance is the sum of the distances between the houses of the friends and the meeting point and the distance is calculated using the Manhattan distance now this is a hard level problem if you're solving it um you should probably have some experience with lead code so for that reason I'm actually not going to go over example cuz it's just waste of time to actually go over it what I want to do is actually talk about the naive solution and the kind of optimal solution and the reason I want to give the naive solution is because in the case that you actually don't know how to solve this one uh or you don't understand the most optimal solution then given that this is a hard question usually the interviewer will be fine with the BFS approach which is the naive so the naive solution would be essentially for each point in the grid let us do a BFS to find the distance to each of the houses right and the reason we use BFS is remember that in an undirected graph BFS will actually give us the shortest path um to a point so that's why we use BFS so basically you know starting at for example here let's calculate the distance to all of the ones so we go one tile two tile three tile same here one tile two tile three tile and then one tile here so the distance from this point is seven to all of them we can do this for every single uh row and column uh value in our grid um and then just basically take the minimum distance um minimum tile sum and that is the answer right so unfortunately because we have a m byn grid um and then we have to search for every single element in an M byn grid we have to search potentially the entire Grid in the case that the entire grid is actually ones uh which means that we have to visit all M byn Points uh which means that this algorithm is actually going to be really and it's m^2 n^2 going to be really and it's m^2 n^2 going to be really and it's m^2 n^2 which is really bad and we can improve on this but again the BFS is really easy to come up with it's really easy to code because it's just a standard BFS you just have to just Loop through everything and kick off your BFS so there's that problem um but if this is all you know then it might be okay in an interview you should probably talk about how you might improve it but that's fine now what I want to do is actually go over the kind of gigabrain Chad solution which is actually really simple and really stupid that they would even have this as a problem so let's kind of get rid of all this stuff and think about this so if we have some points and we want to figure out you know the shortest distance between that optimizes right the point that gives the minimum total travel distance how might we do this right now you might thinking okay well what if we just find the middle point right what if we take the mean but unfortunately means are really bad because they are easily skewed by uh extreme values so for example if all of the ones are on the right side um then the mean will actually get dragged one way and we don't want to do this and this is where this stupid little hack of this question comes in and this is where you realize that you can actually use a median and let's think about why we can use a median and let's look at a normal distribution to kind of illustrate our point if you remember in a normal distribution or really any distribution what does the median represent right so this is the median point the median by definition by I guess like concrete mathematical statistical definition is the point such that to the right of the median represents 50% of the data and to the left of it 50% of the data and to the left of it 50% of the data and to the left of it represents 50% of the data which means represents 50% of the data which means represents 50% of the data which means that this is the exact middle point such that 50% of the ones are to the left and that 50% of the ones are to the left and that 50% of the ones are to the left and 50% of them are on the right which means 50% of them are on the right which means 50% of them are on the right which means that this is actually the exact middle and for our problem is actually the point where that optimizes the minimum total travel distance because it is the point that is actually equidistant from kind of both sides if we look at it unfortunately this is a bit hard to implement when you have a 2d grid right if you have a 1D Grid it's really easy to find the median Point um but how do we do this in a 2d grid and really the algorithm is basically just going to be oops I lost my pen here instead of trying to work with a 2d grid we're actually just going to transform all of the ones we're going to take their location and build one master um 1D grid so this is 0 uh this is point this is if this is row zero so this is 0 1 2 three 4 so this is row zero column 4 and basically we just populate uh this so it is this row uh two column 2 right so what we can do is we can calculate um this these are all of our points so what we want to do is actually find the Middle Point here which is really simple because it's literally just the kind of middle point of our values here and then once we have the med Medan which is the coordinates of the median all we have to do is actually calculate the Manhattan distance um from that median point of these values and then add and then basically just find what the uh minimum is here right so we'll basically just minimize uh that value and that's really all you have to do pretty straightforward again the intuition here is that basically again the median is that point which represents 50% of all data points to one represents 50% of all data points to one represents 50% of all data points to one side uh and then 50% to the other side uh and then 50% to the other side uh and then 50% to the other side again this is a bit tricky to kind of think about when you have a 2d grid which is why we transform it into a 1D grid and then we can basically just solve it easier by finding the midpoint of you know this new transformed grid we only care about the ones here and then we can just basically find the point that is in the middle so let's now go to the code editor and see how we'll type this up this sounds like really handwavy and really hand like magic but once we go into the code editor a through line by line and um you'll see that actually it's really simple and hopefully you should be able to understand this problem now okay that's enough rambling let's go to the editor okay we are in the code editor let's type this up the first thing I want to do is actually just Define some variables to help me out here with the actual processing so I'm going to say that M and N are going to represent the length of the grid and it's going to represent the length of the grid um zero so basically this just gives me the number of rows and the number of columns now I also need some variables to keep track of kind of my work here so I'm going to say the rows is going to be an empty list the columns is going to be an empty list and my um the points with a one are going to be um so like the houses is going to be a uh empty list and the reason that I need to store the rows and the columns is that remember what we talked about with the medians right when we have the values and we basically want to find what's kind of like the Middle Point here and this will only work if obviously the values are sorted right if we have they need to be in the exact order that they would come in otherwise it falls apart because then you'll have things out of order they need to be literally in the order for the column um and same thing for the row we can't have them jumbled up because then actually their true position is not where it would be so we need to process our grid here to actually put everything in the right order and we'll see how we do this in a second but we do need to keep track of the rows and the columns okay so what we're going to do is why is my caps lock on okay um we're going to say for I in range M so basically we're going to go through all of the rows and we're also going to say 4J in range of n so basically we're going to go through all of the rows all the columns and we're going to say if the current point is a house so if grid of I and J remember if it equals to one it's a house then we're going to say that um houses the append and we're going to put the position of the house I and J now remember that we actually need to store um the position in the row where this house happens so that way we can calculate what is the midpoint of all of the um the column values and also for all the row values and the reason that when we did it in the example earlier we didn't have to do this because it was a ond array when we have a 2d array we basically have to find the midpoint over the grid we can't just do it in our single kind of um you know array because it's a grid we need to find it across the rows and the columns so that's why we need to keep track of all the points um where there's a house in the rows and then that will help us find uh the midpoint so we're going to add um to rows we're going to pend the position of our row which remember is I okay now unfortunately we can't just add a j to columns as we go here because obviously We're looping through the rows first and then the columns so we're not guaranteed to have that strict ordering uh of the rows if we were to add J now so we actually need to do a second Loop through the array but actually switch the orders instead of processing uh row by row column by column we're actually going to go column by column row by row and that will actually give us the columns in the order that we need in order to find the midpoint uh within the 2D grid so we're going to say 4J in range so we're going to switch it this time in range n so we iterate over the columns first we're going to say um for I in range of M we're going to say again if the grid of I comma J equals to 1 we're going to say columns append J so now we've found the J's uh sorry the columns and they are also in sorted order as you would go through in the columns okay now that we've done this comes kind of the simple part so we now need to find the median of all of the column and row positions so how are we going to do that remember the median is literally just the middle element here and because everything is sorted um it's literally the element in the middle right so for examp example if we have 1 4 5 7 8 9 10 how would you find the median here well remember the median is literally the element that's in the middle here um so that means that okay what is the median element well there's three to the left of seven and there's also three elements to the left of seven on the right so seven is our median and remember this only works here because this is sorted right so that's the reason why uh we want the sort because otherwise it would uh be jumbled up here so uh and okay and let me just take a step back and the reason we want it sorted is because if they're in the wrong position then the distances that you calculate uh later because we still need to calculate the Manhattan distance from all the points um and if it's not sorted then obviously they're in the wrong position and we'll actually calculate um the wrong ordering here so we need to make sure that our uh median is actually correct so what we want to do now is we want to find the median of the rows so remember that this is just rows uh length of rows divide by two so basically just literally the median element in the middle element in the rows we're going to do the same thing for the columns so we're going to say the median column is going to be equal to columns length of the columns uh divide by two so now we have the median of the rows we have the median of the columns now this is our most optimal point but remember that we're not asked to find the most optimal point we're actually asked to find the distance to the point so we found the kind of median point but we still need to calculate the distance right and we need to minimize this distance um so what we want to do is we basically just want to calculate the distance from um each of the points to this median one and whatever is the smallest distance uh to all of the points then we potentially just want to return that so how are we going to do this well we basically need to calculate um the sum of the distance from all the points to the median right so we already know that the median is the best point now all we have to do is just calculate the sum here so we're going to say return the sum of what is the sum we need to calculate the Manhattan distance so how do we calculate Manhattan distance uh if you recall from the description if we pull it up it is this formula so the x of one point divided minus the x of the other point absolute value plus the Y of one point and then the Y of the other point uh absolute value and then add those two together so we basically just need to do that so we're going to say that um we're going to sum and we're going to sum all these elements so we're going to say the absolute value of Point um I guess we'll just say house because it's really a house here so house zero so house is the house Zer is the X position minus the median of the rows uh plus the absolute value of House of one that's the y-coordinate minus the of one that's the y-coordinate minus the of one that's the y-coordinate minus the median of the columns um for house in houses so basically this will calculate the distance from each of the houses to our kind of best meeting point and then we just add together all of those um sums and we're done because we just want to find what that maximum point is so okay that should be it hopefully this is fine looks like it's accepted and let's submit it and we're good accepted so uh let's hide that and let's talk about the time and space complexity here so what do we do here we have one full pass through the array right so that is going to be what this operation is Big of M * n because we operation is Big of M * n because we operation is Big of M * n because we have to pass through the entire grid once we do the exact same thing again so this is also going to be Big O of MN so that was um this part then to calculate the median this is just literally taking the value of an index uh sorry taking some value out of a list so that's is Big O of one time same with this is Big O of one time and then to do this we have to basically pass through all of the um houses and houses in the worst case this is going to be Big O of n * n case this is going to be Big O of n * n case this is going to be Big O of n * n again because in the case that you have every single point in the grid actually being a house then you're going to have to process every single house again so this is Big O of n * n but as you can this is Big O of n * n but as you can this is Big O of n * n but as you can see none of these are nested so this is just Big O of n * n plus Big O of n * n just Big O of n * n plus Big O of n * n just Big O of n * n plus Big O of n * n plus Big O of n * n so ASM totically you plus Big O of n * n so ASM totically you plus Big O of n * n so ASM totically you know we have something that's like 3 * know we have something that's like 3 * know we have something that's like 3 * Big O of M * n but we know that this Big O of M * n but we know that this Big O of M * n but we know that this really just equals Big O of n * n really just equals Big O of n * n really just equals Big O of n * n because we can ignore um these um constants so that is the time complexity n * n as you can see we complexity n * n as you can see we complexity n * n as you can see we basically brought it down um by a factor of n * n because the root force was m^2 of n * n because the root force was m^2 of n * n because the root force was m^2 * n^ 2 and now it's just m * n so we've * n^ 2 and now it's just m * n so we've * n^ 2 and now it's just m * n so we've definitely improved there space complexity wise again in the worst case the entire grid will actually be ones which means that um we basically have to restore all of the points in houses rows and columns um and this is just going to be Big O of n * n because that's the be Big O of n * n because that's the be Big O of n * n because that's the total number of points there are in the grid and if we have to store them all again in our houses array um then we're basically just copying uh the Grid it's just in a bit of a different format so that is your time complexity space complexity they're both the same n * n complexity they're both the same n * n complexity they're both the same n * n hopefully this problem clarified things again this is one where if you know the Brute Force it's probably fine um just because it's actually quite tricky to come up with it and you know it's not the end of the world if you need to do that it's still good to know this solution and it really is predicated on understanding how medians work and how well if you think about it in a 1D grid the median is literally the point where the um the distances there's an equal amount to the left and to the right and then you know that's how we basically were able to kind of extend it um into this case and then find the median point and then basically just calculate the distance from each uh one that is where it will actually be minimized anyway definitely a weird one this is one where if you've seen it before you'll be able to come up with this solution and kind of walk through it without not really having any issues most likely you're not going to come up with this one on your own um BFS yes you can definitely come up with that one on your own this median crap no way um I don't know why they ask this question it's really bad anyway if you enjoyed the video please leave a like and a comment if you want to help me grow leave a sub subscription to the channel otherwise thank you so much for watching this problem has absolutely blown up my brain see you in the next one bye
|
Best Meeting Point
|
best-meeting-point
|
Given an `m x n` binary grid `grid` where each `1` marks the home of one friend, return _the minimal **total travel distance**_.
The **total travel distance** is the sum of the distances between the houses of the friends and the meeting point.
The distance is calculated using [Manhattan Distance](http://en.wikipedia.org/wiki/Taxicab_geometry), where `distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|`.
**Example 1:**
**Input:** grid = \[\[1,0,0,0,1\],\[0,0,0,0,0\],\[0,0,1,0,0\]\]
**Output:** 6
**Explanation:** Given three friends living at (0,0), (0,4), and (2,2).
The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal.
So return 6.
**Example 2:**
**Input:** grid = \[\[1,1\]\]
**Output:** 1
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `grid[i][j]` is either `0` or `1`.
* There will be **at least two** friends in the `grid`.
|
Try to solve it in one dimension first. How can this solution apply to the two dimension case?
|
Array,Math,Sorting,Matrix
|
Hard
|
317,462
|
1,600 |
hey everybody this is larry this is me going over q3 of the recent weekly contest 208 where i got really lucky um hit the like button hit the subscribe button join me on discord and cue twist wrong inheritance so again this is an exercise that turns out in reading to constraints uh and what i mean by that is that uh basically there are most a hundred thousand entries um on this thing but at most ten course to just get inheritance order so that's the key thing to notice because that's the thing that we're going to optimize to be the most expensive um and even though there's this one is really worthy so there's a lot of reading uh it's about half an hour in and only 400 people solved it so it's a hard problem to read anyway um but it boys boils down to um constructing a tree and then doing um a depth research with pre-order uh in the pre-order with pre-order uh in the pre-order with pre-order uh in the pre-order direction um and once you get that then that's uh that's all you need uh so basically the way that i did it is as i said i just turned it into a tree uh i also use a dictionary for lookup table so that i can add notes to certain nodes quicker but that's the general idea so basically i have a node class that does that has a list of child children and the name just for fun and then add children would give me a note with that name add it to a ch as a child literally a child in this one right like because it's inheritance get it okay fine uh i know and then you return the note to that i can use it later for the lookup table so my initialization is just okay i create a root node with the king i put it in the lookup table i have a lookup table and i have a set of dead people uh i see that people uh and then basically for every time we birth we get the note that has the child's name and we just add it to the oh sorry yeah we set the child names node is equal to the parent's uh node adding a children so that's basically what i did here this should be o of one because the lookup is all one right and this is you know adding a child's or one as well so this is an all one operation uh dead we just add to a deadlift so this is old one so basically so far everything we've seen is over one except for getting hurt and so order uh so this is the big expensive of n operation linear operation where you do a depth first search and literally i have a definite search where i do uh a pre-ordered traversal of where i do uh a pre-ordered traversal of where i do uh a pre-ordered traversal of the tree and if and we skip putting the name and the result if and actually i didn't need to not know go but uh we skipped it with instead which makes sense right so this is very basic uh pre-order traversal uh and this is uh pre-order traversal uh and this is uh pre-order traversal uh and this is gonna be of n right this is linear time and n can be 10 to the fifth but as i said in the beginning the key part is noticing that constraint is that they're at most 10 cores so you know 10 times 10 to the fifth is 10 to the sixth so it's fast enough that was my instinct and that's basically how i solve this problem uh and once you have the right data structures um i think the one that may be a little bit will take a little bit hard second to look up is a lookup table but once you have stuff like that and you know taking the time to even create a note class maybe and i did this during the contest right once you do that the problem is pretty elementary um so definitely you know don't be afraid to you know take different tools uh and try to do whatever you can to minimize the uh the running time uh that's all i have for this problem i went over each complexly and the space is gonna be linear because we have one note per um one note per person and also one lookup entry per person so yeah um anyway uh you could watch me solve this live during the contest next wrong inheritance this is again a reading is fundamental problem fundamentally long it's one of one f's now but um but yeah i think i was trying really hard to read this successor function and be like what is it asking because it's kind of confusing but yeah but that's basically literally what i was doing um yeah basically now i'm just being successful and i'm trying to understand successor i think immediately i thought it was pre-order but i pre-order but i pre-order but i was trying to really pass the way that they phrased it and the way they phrased that pseudo code was kind of just weird right you probably agree with that so that's what i was trying to figure out how to read that correctly um if x has no trial oh hey i'm like i look like i'm not moving at all i'm stuck in time for a second i got the video froze but now the video is still working it's just that i'm being boring perhaps in a good way but it seems like i spent a whole minute just reading this uh but i think at this point i knew it was gonna be some kind that first search i think um i took a look at the constraints at some point maybe come now i look at 10 strains i think the thing that i know this is um maybe not now maybe not yet but soon yeah now i'd take a look at the constraints i see that and that could be at most 10 get her inheritance core so that i can do a linear thing because my idea was to do a linear that first search or something like that and that could only work if we don't have that many inheritance so i have to look at the constraint there uh and i try to do the queen thing of uh creating a node so that i don't have to worry about it um yeah also not efficient as you can tell right now i'm just writing my note class which consists of the children uh the notes children and uh the name but i think i didn't do it yet but you see it hey but yeah uh and right now i'm just initializing the node i mean this is actually to be honest right now a boring problem uh if you listen to my explanation uh during the explanation video i go over it so this is actually not a surprise and it's not really that much code um so yeah basically so the tricky thing for me for this problem is just trying to figure out okay i want over one asset to find the note that we added to so basically i just have a lookup table right uh and i was just making sure that uh how my interpretation of the dead people is uh correct yeah i'm just trying to think about how i wanted to do it uh and i think i figured it out otherwise it was sad um yeah i tried to pre-warm the uh the yeah i tried to pre-warm the uh the yeah i tried to pre-warm the uh the dictionary but i wasn't sure about the syntax so i was just like yeah whatever let's just write it out to be sure because sometimes it gets you know like it magically is a set uh and i've been really bad about that it had a couple of typos in the contest ago so yeah and now we just set the child name really yeah child name yeah so i added that so that i can uh you know get that easy in one core and that's pretty much it the depth is pretty straightforward as well we just put into the set uh once you have everything set up mentally uh everything becomes a little bit easier uh and i took the time to test this once and i think here i'm just double checking the that first search because i didn't want to implement it and then to be well and i was like 10 questions should be okay uh and then yeah and that research is pretty straightforward in how i implement it uh and you know again obviously i tried to uh yeah i tried to exclude the dead people i was trying to look through the thing again uh just wondering if i can exclude the dead people in a way that um that doesn't affect the performance that much but then when i saw 10 calls i was like i guess i don't really need to do that but yeah i'm just thinking about like here i'm also vertifying that pre-order here i'm also vertifying that pre-order here i'm also vertifying that pre-order works uh just giving it some dots because i was sure that it was pre-order because i was sure that it was pre-order because i was sure that it was pre-order but you know like yeah and i was like what are you doing now um and here i knew that i just needed to check the name the dead name but i wanted to see that at least like i didn't get any compiled or anything like that uh and this i've been doing this trick where i you know this comparison is just terrible right so i've been kind of just copying and pasting um the output so that i can you know it's slightly easier to read uh and i saw that uh my output is more than the intended output and i was like okay that's probably the dead people so we can um you know we can take care of that um run it again test it again uh print it out it looks okay i actually do go by one because five minutes is a huge penalty so yeah um so yeah i submit and it was good uh hey thanks for watching uh let me know what you have about these problems uh hit the like button to subscribe and join me in discord and it's been a very lucky contest for me so if i'm a little too giddy anyway i'll see y'all next problem bye
|
Throne Inheritance
|
throne-inheritance
|
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function `Successor(x, curOrder)`, which given a person `x` and the inheritance order so far, returns who should be the next person after `x` in the order of inheritance.
Successor(x, curOrder):
if x has no children or all of x's children are in curOrder:
if x is the king return null
else return Successor(x's parent, curOrder)
else return x's oldest child who's not in curOrder
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
1. In the beginning, `curOrder` will be `[ "king "]`.
2. Calling `Successor(king, curOrder)` will return Alice, so we append to `curOrder` to get `[ "king ", "Alice "]`.
3. Calling `Successor(Alice, curOrder)` will return Jack, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack "]`.
4. Calling `Successor(Jack, curOrder)` will return Bob, so we append to `curOrder` to get `[ "king ", "Alice ", "Jack ", "Bob "]`.
5. Calling `Successor(Bob, curOrder)` will return `null`. Thus the order of inheritance will be `[ "king ", "Alice ", "Jack ", "Bob "]`.
Using the above function, we can always obtain a unique order of inheritance.
Implement the `ThroneInheritance` class:
* `ThroneInheritance(string kingName)` Initializes an object of the `ThroneInheritance` class. The name of the king is given as part of the constructor.
* `void birth(string parentName, string childName)` Indicates that `parentName` gave birth to `childName`.
* `void death(string name)` Indicates the death of `name`. The death of the person doesn't affect the `Successor` function nor the current inheritance order. You can treat it as just marking the person as dead.
* `string[] getInheritanceOrder()` Returns a list representing the current order of inheritance **excluding** dead people.
**Example 1:**
**Input**
\[ "ThroneInheritance ", "birth ", "birth ", "birth ", "birth ", "birth ", "birth ", "getInheritanceOrder ", "death ", "getInheritanceOrder "\]
\[\[ "king "\], \[ "king ", "andy "\], \[ "king ", "bob "\], \[ "king ", "catherine "\], \[ "andy ", "matthew "\], \[ "bob ", "alex "\], \[ "bob ", "asha "\], \[null\], \[ "bob "\], \[null\]\]
**Output**
\[null, null, null, null, null, null, null, \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\], null, \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]\]
**Explanation**
ThroneInheritance t= new ThroneInheritance( "king "); // order: **king**
t.birth( "king ", "andy "); // order: king > **andy**
t.birth( "king ", "bob "); // order: king > andy > **bob**
t.birth( "king ", "catherine "); // order: king > andy > bob > **catherine**
t.birth( "andy ", "matthew "); // order: king > andy > **matthew** > bob > catherine
t.birth( "bob ", "alex "); // order: king > andy > matthew > bob > **alex** > catherine
t.birth( "bob ", "asha "); // order: king > andy > matthew > bob > alex > **asha** > catherine
t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "bob ", "alex ", "asha ", "catherine "\]
t.death( "bob "); // order: king > andy > matthew > **bob** > alex > asha > catherine
t.getInheritanceOrder(); // return \[ "king ", "andy ", "matthew ", "alex ", "asha ", "catherine "\]
**Constraints:**
* `1 <= kingName.length, parentName.length, childName.length, name.length <= 15`
* `kingName`, `parentName`, `childName`, and `name` consist of lowercase English letters only.
* All arguments `childName` and `kingName` are **distinct**.
* All `name` arguments of `death` will be passed to either the constructor or as `childName` to `birth` first.
* For each call to `birth(parentName, childName)`, it is guaranteed that `parentName` is alive.
* At most `105` calls will be made to `birth` and `death`.
* At most `10` calls will be made to `getInheritanceOrder`.
| null | null |
Medium
| null |
1,609 |
Hello hi friends welcome back to loot problem 1609 you know entry le suicide looking details of this problem is one to bring to your notice data this day cream tube videos related to record solution in java s well s java j2ee interview helpful for material videos they discuss You Know All Agreement Go To Interview Questions And Instead Of Which Sun Data Structures To A Few Hours Was My Videos And Lit Please subscribe The Channel Annual Subscription Really Help Channel Tourist To Morbi Per Please Subscribe So Let's Look At Problem Spinal Tree This Name The Giver and debit mix form for all Indians should have given ass condition saw it a point to retrieve year notifications point condition that root of the final tree this at level invincible thanked children room at level index one day children at level index from 1 to 0123 Laghe inform every one in next level all the notes and the level have arranged in teacher values and strictly increasing teacher values and strictly increasing teacher values and strictly increasing order from left to right so as you can see that teaser even level pay for example this is the human level to show the value Clear All Most Valuable Player Increasing Order From Left To Right Sunao 797 Yaar In Increasing Order Pet Left For Everybody In This Level Call Note Set The Level Have Even Integer Value Against Decreasing Order From Left To Right Sunao Reviews Fuel Rod Level Vandalize And Destroy Your Values in the World And Destroy Your Values in the World And Destroy Your Values in the World Level Trend and End Decreasing Order Similarly IF You Go Level-3 Teaser and Level Similarly IF You Go Level-3 Teaser and Level Similarly IF You Go Level-3 Teaser and Level Saurav This One and Wearing Decreasing Order 12860 Two Front Saw This Condition Including Day Worship Special Guest Oath 121 and Way to You Will Return to Fear in That Case should given route of the end of so 500 minutes will be code number 1150 number give us that route will be and number so they are implementing a solution for watching will check is this route it should be and number equity one number one will directly return Forms from website so let's take the example over a year and explain how we can solve this problem please problem only medium difficulty level 100 first thing edit mention in the condition so every level 2001 level the note beauty 111 should be chord suvver technique called s B face and level driver of binary search tree to the deficit and values of cube is why deficit and values of cube is why deficit and values of cube is why english civil aa they never give up eating notes from each level will power to edit war cubes and will determine process by level life process the notes in the Q Level 11:00 Rates for example of how notes in the Q Level 11:00 Rates for example of how notes in the Q Level 11:00 Rates for example of how raw live with process disturbed closed productive rate so let's start and Ayush you know from this example of how they can implement BF website and using the outgoing war that is solid from solid this is the why sowe new Year And The Visiting The Root Note Swift Sacrifice Teaser Take 108 Show This Is The Note Chupi Sadhe Like And Number Reduce And Number Invented Into Our YouTube Twitter Even Numbers Which Substance From A Point Slide Mist Next Time Like It's Wildlife And Will And Files And Will Go Aunty Tower Why Vikram Same 6309 What We Will Do Is In Every Nation With The Notes For Update Level So Varindra Oil Achievement Software Submitted That This Element From The New Bride And Will And Its Children For Evil And Difficult And You Will And Right side and work you will attain first and will add that you train will develop right to 10th and 12th swift and four year so they are adding that into the cue Avinash Vaidya are the even numbers because now where processing other level so as long as they Hey Even Numbers Will Do The Cubes And Din Will Start Processing The Level Name 34 Level Shyam Processes In This Will Start Processing Level One Right This Level One So Wherever They Are Processing This Will Pool Billiards Element And Will Always Create And List From The God Elements And So I Will Put This Element Interver List Tweet First And For Women Power List What Ever Were Falling From Which You Will Put Into The Earliest And When We Positive Verification Left And Right 0 Cliff Industrial Software Govind V Q And Where Polling Four From A Few Minutes When They Are Moving Forward From The Given Videos From Left And Right Zinc Seven Hair And Care Fight For The Next Level Soyega Cream Launched Here Create This List And Will Avoid This List And For Even Level Will Make You All The List Is Decreasing Hit List left decreasing so for example if you see the condition for the marriage type for the life level tree for the means this point level tricks og 11th hu is this one sonth index level all notes and level have even in reserve yashoda to you will check Appointing Values from the check Appointing Values from the check Appointing Values from the Q&A Distinct and Decreasing Update Q&A Distinct and Decreasing Update Q&A Distinct and Decreasing Update Condition Now You Will Check From the List Ride With Rate This Element Annual Day of Warming and Decreasing Order from This Point Decreasing Order Software Good Show Will Continue Processing Ten Level Fight Sun Wutaniya Process 1101 Process Live Wallpaper Good Sounder Solid Its Related Audio Story But You Have To Process Each And Every Month Basically Site Sun Will Process The Level-2 Level Two Is Site Sun Will Process The Level-2 Level Two Is Site Sun Will Process The Level-2 Level Two Is The Human Level Show All The Chill Dist Notes Issued Before 10-02-2014 10-02-2014 10-02-2014 30 Calling E Will Put Friend Things Into Per List Gyan Sun Hu Will Face 3000 Between Two Our Least Seven Cases Same Time You Have To Receive New Level To He Became President Level Two And Will Have To Insert The Children Of This Point To The Curious Him Add Soft Smooth Point Free Song Wedding Twelve Years In Power Fuel Software 128 Will Go That And After Death At Seven Children Will Go Sure And No Right Side Absolutely Smooth Children And Best Software That And Sachin Till date Ronit Har Day Hui Hai That List For Defamed Nau Will Validate List Play List Shirdi In The Increasing Order 5831 Level Threats But Even In The Next Level Solitaire Value Soft Software Dare And Strictly Increasing Order From Left To Right So From Left To Right Shift Meaning Of Increasing Order Cities For Increasing Order Read Se Zinc Placing Order Sui Hermits Offers Poll Toppers Truck Level Reduce 3382 Is The Last Level Of Distinct Soen A Year Will Your Polling The Element From The Tree And Will Again Keep Adding That Into Our List Regions All Will Have Brand New Latest Hair Style For Each Level Sunao Koi Vighna 208 Indian Sex And * Price In Proper Least Indian Sex And * Price In Proper Least Indian Sex And * Price In Proper Least One Wolves Elements For December Aa Gone From The Why Notice Rights Reserved Seats On Nov And Why Welcomes A Limited Time And Hui Orissa List For The 11:00 Time And Hui Orissa List For The 11:00 Time And Hui Orissa List For The 11:00 300 Level-3 Is Chord Level Aberration Is Awards 300 Level-3 Is Chord Level Aberration Is Awards 300 Level-3 Is Chord Level Aberration Is Awards Show All The Note 4 Give One Shoulder notes31 Tight And Din Hui And Reduced And Will Have To Take You Delhi Sperm Decreasing Order Twelfth Class Great With The Greater Than Six Greater Than To Hui And Good Cheer So I Will Return Proven This is a true for distic 33 and even and trick basically 342 approach war benefits and adult is in treatments for watching java read so let me show you how it's improvement this I soft english hui create the results hui thing play list of list Of interior and drafting chili a hair is root key is equal to nalin will just that sort of a when did you not real great soldiers return forms otherwise meet creator tummy like atri notes q write you who's consisting of prisoners pe note sis notes to izzat read The because a it's earliest and will foster father root hair to the united and airways create a couple of various like's youth award and typing slide is not where not giving flight so that subject free mode switch have created to the bullion approximately store understand witch river Vyaar and gift yavan and level 500 first thing I will say there root value that destroyed and software checking your feet not visited were police will also say that is equal to truth mins oo here and the god level name will feel then it starting from the God Level Clear All Is Equal To True And Will Do This Point Look Posting Allocated Goals Vikram Simati Hui First Check The Size Of The Because When Bigg Boss Hui Want Oo Only Process Batman Elements For Example This Size Will Give One Should Support You Will Want To Process Problem Next Time Waste Processing Level-1 This Next Time Waste Processing Level-1 This Next Time Waste Processing Level-1 This Level Band Size Started Only Want To Protect You From The Queue Brightness To You Want To Process Product You Should Strive Will Read The Size Of The Year And Will Tie That For Ludhianaweez 20 To Distance Is Right I Will Stand Including And Will Keep Falling Note From The Cube And Its Teachers And Level First From Your Feet Is And Level Din Vineshwar The Notice Iodine That Person All 152 Ki One Direction Return Form And Poor On The Human Level Witch Chapter Notes Value Should Be Hot Right To Wear Checking A Hair Tips Hot Benefits Not Heart When To Interest Director Falls From The Other Side He's Created This List And Distribution New Research Of Titration Will Have A Newly Established Wedding Is Children Into That Is This Fold Notes In Today's Live World In The First Level In The Next Level Will Have 1000 Likes This Made Stool Late Add Likes And They Never Were Falling And Will And Its Left Right Clear And Its Right Side Effect Is Not Known Fact Which Ended With Slide Sorter Follow Piston Day's War Rye Enmity Just Demonstrate I'll Want To Show You How Do Scrutinized Oil Free Mode Turn Off But Hui Actually Year Boy Poor And Even The Had Never Did You Say One Level Receiver Puberty Level 2010 This Dynasty There That Case Movie want to form the basis of increasing order back to back software check the listed decreasing order for even level basically aa for even level chest seconds us strong level i daily discount also increasing order for this comment infection rate is that auspicious increasing order and exit decreasing And correct sudhir checking officer increasing order release date hui hai subah increasing every element is the element class 9 equal to i plus waqt element basically a flash light on main to der support will be setting to hui aadat hi one level show will be on the that Ab Ya Na A Solid Sic Hi Ranbir And Usually Starts With Congress Support For Example A B C D S One Is The One In Dalit Day 10:00 Formal Complaint For Belcom Dalit Day 10:00 Formal Complaint For Belcom Dalit Day 10:00 Formal Complaint For Belcom Day 30 Companies Not Come And Lastly I Will Be 12820 Company 500 Leak Kam to alam is hui airtel even level day will just get delhi stand with maximum set the fifth element this little s bank rate day backward call light turn on the 111 give one is equal to file sends equal to right mins every time you will Do glamor activities of you in next time the level will be for discipline and deposit level next time level request one should support they are doing so he also here again rating list so this is for even level and decision for 1150 this is even level tricks And level courier checking if i the limit is backem so this is or dry play cord level is for example enemy rate 100 the were checking net to of the elements of victims are 10:00 da plus one of victims are 10:00 da plus one of victims are 10:00 da plus one for example 30 level-3 let's get Rich And for example 30 level-3 let's get Rich And for example 30 level-3 let's get Rich And Level You For The Best Well Is Vikram Greater Inside Next Element Day It Is Not Per Decreasing Order I Think You Will Just For This Year And Eve Teaser Ki 111 Should Be Increase In Rates Shoulder Software Checking Yes I Will Add Your Feet Is Victims displeased and i plus one for example of burning lamp stand seven days will for like water falls between friend him limit zoom and regular means next element sick like she where is more than 32 and nice mode on seven pro software checking point 133 swaroopini time every Fire Every Level Will Have To Changes Basically So Let's How They Are Doing So Whenever You From Woman Found Nothing Is Breaking Will Immediately Return Form Gift That Bricks And Witch Comes Out Of This While We Would Oil It On Friday When Alternate Route Per Means Factory Is The Correct You Not Read This Following The Rules Basically Solitaire In This Code On Weekly Photo Contest Andar Example1 200 Gr Code Working Fine I Will Also Want To You All The Example Dard Hai That Ones 111 And Two For Se Soy Milk Powder Sudhijno Different Types Of Everything Will Submit This Has A Solution These Days Amarkot Solutions Getting Accepted Clear A Showpieces How They Can Find Out Your Feet Is Character You Know Entry And Not Based On Which Runes To Have Used Khadi This Approach And Cubic Roots Which You Can See This Is Back To back to you started and you like maybe 34 level hui air travelers and they are putting out with acute and next level liquid polling is out and they will drop dead after its children were pouring after they were properly slept and while children in the sequence Souvenir verification done for the list from this 24th Want to check your kids cycle and scooter Decreasing order for even and rod level and increasing order for even Level reduce increasing order and degrees in hospitals for this is also increasing order Cons This is a what else Level So Lets You Can Solve This Problem Hum That Typing Is Planned For Everything In Every Detail Typing So If You Understand Solution You Have Any Questions Please For Editing To Comment Unite And Like To Answer Your Question Of Tracks Are It Very Straightforward Animal Or Chatting Fruit Reddy And Number Crusade's Polling Liquid Polling Elements For Each Level And Wheel Chair For Example When Ever Were From The God Level Will Check Attitude Give Value All In Hui Reddy And Personality Morning Jewelery That Chapter Can't Too Insignificant To Dalits And They Will Miss You Again Play List All Doing His Career For The Previous Volume Soft Emergent A Solution Is 100 Aa Giri At Least Solution Videos And Already Have Valid Co Diner Playlist Having More Than Fifty Five Solutions With Example Splendor Co Details For Creative 2010 Full Form Luteri for India in Java Interview and Giving a Recording Interviews and Coding This Also Give Very Carefully Before Doing Any Online Coding Test Rice Vikas You Will Get Similar Question Setting Show the Concept Completely Clear and Will Greatly Value Your Also Have Another Playlist Better Helps You Live With Your Contact With Benefits Dynamic Programming Head Map Data Structures Please Activate And Please subscribe To My Channel This Will Help Channel To Group Thanks For Watching
|
Even Odd Tree
|
find-all-the-lonely-nodes
|
A binary tree is named **Even-Odd** if it meets the following conditions:
* The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc.
* For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right).
* For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right).
Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._
**Example 1:**
**Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\]
**Output:** true
**Explanation:** The node values on each level are:
Level 0: \[1\]
Level 1: \[10,4\]
Level 2: \[3,7,9\]
Level 3: \[12,8,6,2\]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
**Example 2:**
**Input:** root = \[5,4,2,3,3,7\]
**Output:** false
**Explanation:** The node values on each level are:
Level 0: \[5\]
Level 1: \[4,2\]
Level 2: \[3,3,7\]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
**Example 3:**
**Input:** root = \[5,9,1,3,5,7\]
**Output:** false
**Explanation:** Node values in the level 1 should be even integers.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 106`
|
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
563,1005
|
253 |
hello everyone welcome back to my channel so today i am here with another meeting rooms question so this meeting rooms question is a follow-up question follow-up question follow-up question to the previous meeting room question if you haven't seen or done the previous meeting rooms question i highly recommend you to take a look at that video before looking at this video i'll put the link to that video up left or right i don't know yet but without further ado let's get started this question is very similar to the previous meeting rooms question for this question we're going to find the minimum number of meeting rooms required for all the meetings say if all the meeting times are not overlapped with each other then we could just use one meeting room but if there is an overlap that means we'll have to add one more meeting rooms to the total meeting rooms being used to find the minimum number what we need to do is to try to reuse those meeting rooms as much as possible how do you check whether meeting rooms were usable well we could basically just looking at the meeting rooms that are in use already and see the meetings that has occurred in those meeting rooms whether they have ended or not if one of the meetings has already ended that means that meeting room is available for another use what's the best way to find whether there is a meeting room that's available to reuse the solution is to use a min heap in the min heap we're going to store the end time of the meetings that are already using some rooms so whenever you're looking at a new meeting what you need to do is to compare the top element in diamond heap with the start time of your current meeting if your start time of the current meeting is later than the top element in the mint heap that means that room is available to use for your current meeting now let's take a look at an example say if you're given an array of meeting time intervals of 0 to 30 5 to 10 and 15 to 20 and you want to find the minimum number of conference rooms required the first thing that we need to do is to sort these time intervals by their start time so once they're sorted what we need to do is to create a min heap let's call it rooms used and in the main heap we're going to store the end time of the first meeting so in this case we're going to store 30 in the min heap and then we're going to move on to the second meeting in the input array which is the 510 meeting and we're going to compare the start time of the current meeting that we're looking at with the top element in the min heap so the top element in the min heap currently is 30 and 30 is greater than 5 which means the 0 to 30 meeting is still happening in the meeting room and we can't reuse the meeting room for our 5 to 10 meeting we're going to add another meeting room for our 5 to 10 meeting and we need to push the end time of the current meeting into the min heap as well so the current end time is 10 so we're going to push that into the heap which the heap will turn into 10 30. and then let's move on to the next time interval which is the 15 to 21 and we're going to compare the start time of the current time interval which is 15 we're going to compare it with the top element and the heap which is 10 in this case and we see that 10 is less than 15 which means that meeting room is clear for use so we don't need to add another meeting room for our 15 to 20 meeting we could reuse that meeting room so we pop the 10 out meaning that we're gonna reuse the meeting room and we push the 20 which is the end time of the current meeting into the heap so the current heap is going to be 20 30. and now we're at the end of the array we loop through all the elements in the time intervals we're going to count how many elements left in the min heap and we see there's two that means we only used two meeting rooms for all the meetings now let's start coding our solution so the first thing that we need to check is to check whether the intervals is valid if it's not then we just return 0 because if you don't have any meetings you don't really need to assign any meeting rooms the next thing we need to do is to sort the intervals so intervals dot sort key equals and we're only sorting it by the start time and after that we're going to create a rooms used min heap and we're gonna insert or push the end time of the first meeting into our min heap and here we're gonna use a built-in library called heap queue a built-in library called heap queue a built-in library called heap queue we're going to call heap push on rooms used we're going to push the first meetings end time so after that we're going to loop from index equals 1 to the end of the intervals and we're going to compare the top element from our min heap and see whether it's less than or equal to our current meetings start time so if the rooms use top element is less than or equal to the current meeting start time that means the room's used meeting is already done so we could reuse that room so we don't need to add another room we could just delete that meeting from that room and then push our current meeting into that room so we're gonna do heap pod also from rooms used and then we have to push our current meeting times and time into the heap so that later on we would know when this meeting would end for this room so when this room is going to be available for future uses so heap cue he push into rooms used with our current intervals and time and now at the end of the solution we're gonna return the length of our heap so that would contain that would be the number that would be the minimum number of conference rooms that we have used for these meetings alright so that is the code for this question now let's take a look at the run time and the space complexity for the run time since we're doing a min heap which is priority queue so when you're inserting it needs to sort the current elements in the heap so that would be a big o of n log n runtime and we're also looping through every element in the intervals that's going to be big off and runtime so in total this question would require a runtime of big o of n log n and for space complexity since we are storing the rooms that's being used in the min heap if all the meetings are overlapped with each other that means we'll have n rooms being used so the worst case the rooms used is going to contain n elements so the space complexity for this question would be big o of n so that's it for today's meeting rooms question i really hope you have tried actually coding this out on your own because you know practice makes perfect and you need to do it i need to learn by doing it don't forget to give this video a thumbs up if you think it's helpful and feel free to leave any comments down below and i will see you in the next one bye
|
Meeting Rooms II
|
meeting-rooms-ii
|
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106`
|
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
|
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
|
Medium
|
56,252,452,1184
|
450 |
Hello hello everybody welcome to my channel it's all the problem delete node in binary search tree member classical problem it's kind in interviews and problems looks like easy but it's not video not with family aged such problems sholay 3d problem statement anderson given root no difference of events AND IT DID NOT BE GIVEN THAT IN BSC RETURNS AS REFERENCE POSSIBLY UPDATED OF THE VIDEO THEN SUBSCRIBE TO THE PAGE IS THIS IS THE COUNTRY GIVEN IN THE EXAMPLE AND HOW TO DELETE DINO DELU IS 341 323 VERVAL ANSWERS FOR HISTORY ABSCENDED FLUID IS PROBLEM OVER This is not fair of the tree nod32 delhi dare devils value will go to subscribe and subscribe the node for this check this does n't have left is not have left and vic and right 100mb and yes sorry for that is nod video Channel Thank You Will Go Into It's An Order Subscribe Screen Rule Notice For Candidates Will Be Valid Notes Will Finally Subscribe To The Page If You Liked The Video Then Subscribe To The Page That Vivechak Din More Lead Minimum Balance Into The Rights Of Trees In This Life What is the Means Describes How Will Check Sorry for the Inventor Verse of the Trees Pay Check is the Current No Like Bill Fruit Null returns the video then subscribe to the page if you liked the video then subscribe to the page give me to delivery note 210 wheelchair animals with this year they will send you have left front it is not pimple describe how will improvements for implementation forbes quotes for sure subscribe my channel by pressing subscribe button bill check is Route to turn off a return 90 and sweater to be minus one in case and fruit developed as they are always been no data is equal to null will return that road value picture will always be in the same method subscribe to main saudi is video ko dawa 779 Wheel Chair And Compare Is Roti Channel Subscribe Must Subscribe Ki And Aashiqui Otherwise And Cha Aap Alsi Fruit Well Ki Is Lahar Dekhi Dekhyou To The Life Will Call You Ki Desh Me Tak Torch Light For The Rights Of Trees And Fast That in there swift diger person subscribe definitely developed in the 9th 210 will call in updater road near a good will update and assign to the dot right a key and similarly the are not alone in aaj bhi jas return di the root key dot left or Right Which Is Effigy Road Dot Right This Channel Twitter A Root Fair Member's Switch One Otherwise If The Not Withered It's Not Benefit Is Vain Increase In Appearance English Alphabet Supporter From The White And Will Avoid Food At Right Is Equal To Delete Not For dot right hand did not vanish subscribe the video then subscribe to that such a pitch walking it's louder let's subscribe so that you daily 2nd id for watching's settings ignou mba marketing executive subscribe 9 that's an ax updates OECD hair oil beach sexual subscribe to Vitamin Road Value advice will come on Thursday from Institute of Work and Time Complexity of the amazing video channel thanks for watching.
|
Delete Node in a BST
|
delete-node-in-a-bst
|
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_.
Basically, the deletion can be divided into two stages:
1. Search for a node to remove.
2. If the node is found, delete the node.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 3
**Output:** \[5,4,6,2,null,null,7\]
**Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST.
Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted.
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 0
**Output:** \[5,3,6,2,4,null,7\]
**Explanation:** The tree does not contain a node with value = 0.
**Example 3:**
**Input:** root = \[\], key = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* Each node has a **unique** value.
* `root` is a valid binary search tree.
* `-105 <= key <= 105`
**Follow up:** Could you solve it with time complexity `O(height of tree)`?
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
791
|
1,048 |
Hello Gas Welcome To Me New YouTube Video Today in this video we are going to solve the questions Longest Train What do we have to do in Longest Train Chain? We have a list of words Jivan and we have to rearrange the list and arrange it in the list. By doing this we have to tell the length of the longest string chain or the longest word chain. Now before the longest word chain, let us see what is the word change. It is a sequence of words like it is written here, it is a sequence of words where every two words. The words will be adjacent words, there will be a difference of one alphabet between them, just like if you see that the word world one, there will be an extra alphabet in the word tu, which was there in so many words one, but if we put example variations, then what we have to do in this is that on each string Like this word is right, now look simple, let us understand what will be in the word chain, whatever words will be there in the word chain, they will be in increasing order of length, understand that eating means like, we are doing the same every time, right? That is, we add a new word in the previous world and then it becomes the next word of our word chain. If we add a new word in it, then it will become the next word of the world channel. So, what we are doing is that the length in every word. If we are doing plus one then always the lens in the word chain will be in strictly increasing order. Difference of one is ok. If the difference is more than one then it cannot be a part of WhatsApp. So for this, like if in this example. See, here the length of all the words is three, here the length is 6, here you are here something is okay, so first of all we used English to make Watson, okay basically the word is changed, we are adding it, so the most First of all, what will we do, let's start with our words, okay, I have referred this code, otherwise I will write it completely and show you, so see what you will do, first of all, arrange your words in increasing order of length, words and how. I will do that I will go to the current expert of w1 and w tu home are and ask that if my list or word change was over here, okay if my version ended here then what would be the maximum length it could have been, okay brother if the index is on free. My Watson is running out, so what should be its maximum length? It's ok, so the word which is on 3, I have to find a word which is one liter longer than this, in which all the elements are equal and only one element is extra. Okay, like here for BCA. When I got it, I asked, the right starts from here and ends here only, so the length of the version should be Jati, meaning one, so first of all, and now what we will do is that we will give greater, equal, you words till zero. What was the last element of the chain? He returned it here, now I have to implement this free function, G ward number, I am on the G word, now I have to intake it that if I do any one alphabet story, dal dun to si and ban jaata ki nahi ban. If I go then first of all I will check that brother, there should be only one difference in the length of both of them, if there is zero difference or difference more than one then the date is ok on this note which I am looking for then what will I write that IF C U R dot lens will not make free dot length then water is ok just give me NCERT exercise if free's CID I will increment , I will get such an element. Okay brother, okay P ID Brother, if you exit from the log then whatever will be the pid < if there is free dot exit from the log then whatever will be the pid < if there is free dot exit from the log then whatever will be the pid < if there is free dot length then it will be false for that. If it is equal to experience then with this we will become true. Okay, our code has been submitted here, my color is the answer, so. ok gas this was it on this video if you like this video then you can subscribe my channel and let me know if you want me you make a video on other specific link code question and other question basically and if you have doubt So they can also say thank you
|
Longest String Chain
|
clumsy-factorial
|
You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`.
A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`.
Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`.
**Example 1:**
**Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\]
**Output:** 4
**Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\].
**Example 2:**
**Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\]
**Output:** 5
**Explanation:** All the words can be put in a word chain \[ "xb ", "xbc ", "cxbc ", "pcxbc ", "pcxbcf "\].
**Example 3:**
**Input:** words = \[ "abcd ", "dbqca "\]
**Output:** 1
**Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains.
\[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed.
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 16`
* `words[i]` only consists of lowercase English letters.
| null |
Math,Stack,Simulation
|
Medium
| null |
778 |
778 swimming rising water on it n by n grid each square representation at this point and I do something similar to this maybe not it ok we double check real quick sigh I guess not because they told me I didn't do it but ok dose up to that which I will use anyway ok 70s women rising water on an N by n grid each square whoever sent the elevation at that point I NJ look good something I J now Wayne starts to fall at time T the temple board everywhere is T you can swim from a tee from a square to another for directionally adjacent square even when you have the elevation of both squares individual yah mo is T so I am using my funny voice you can't swim infinite distance over time of course you might must stay within the boundaries of the grid for doing your swim we start the top left corner what is the least time until you reach the bottom white square so that already feels like a binary search problem well let's see so it's 50 by 50 what are the numbers squid oh it's just from so the numbers are from 0 to 2500 so basically it's just connectivity with I mean I think my intuitive sense is binary search and if you binary search over 2500 numbers well that's like 20 or less than 20 because 20 is 2 20 is a million yeah and then you do a depth first search on dad and that's linear time which is of and square and it's 50 in this case so my album would be log of n squared times n square which is N squared log N is that it so that's 2,500 times log of 2500 ish so that's 2,500 times log of 2500 ish so that's 2,500 times log of 2500 ish which is destined million so that should be okay yeah I've enough Lewis I mean that's it let me know in the comments if you need to slow that down cause I feel like maybe I'm confident on this one no but yeah many times you know me but I still should be under a million operations which just should be fast enough okay well we will see if what I'm saying is true but okay my wing keeps no Mike I just keeps picking me is it square no it is a square quick okay if we could connect them is we could get karey for cheaper so that's the way despite it for not just return in time so him may be entirely impossible minus 1 okay so it's so time and at one time so ok so at time 3 you could so it's inclusive okay so you should so that should always be true just case it's 16 okay fine okay so what makes it quit okay so that means you can get from top nerf to top or the bottom boy how do you want to do it yeah and I should do professor it you could do different I think 2500 for deaf research maybe cutting it close maybe not I don't know just talking over the directions well this were always performance because okay this is between this is equal to well that's all it is smaller than now then we created the queue also could use a billion to win maybe we'd use it no would say it shouldn't matter maybe that's how to actually but okay and then put on a queue return for us let's say if X is equal to n and actually we could fire you into this okay whoops what I always forget because I like this it's not insert as if I had too many ATP's in my head no quite 8 my might oppose okay let's try this one Oh what 16.5 mm 16.5 would do it but I Oh what 16.5 mm 16.5 would do it but I Oh what 16.5 mm 16.5 would do it but I just need to do that whoops no gasps yeah good catch stuff ah there's only edge crease I need a finger bow they were just one element I guess only one so I guess has to be these two elements well yes that's very good cool let's take a look I should try it a big case Oh No Oh cuz I don't okay that's a good education because I don't look at the limit of the first one so we can we have to start at something smaller okay you got me I was so confident too but uh but that's fine now is bigger smaller than okay actually I was thinking about like how to handle it but then I did that it was a fleeting thought that did not come back unfortunately so now let me see there's another one another sitting mistake okay cool all right well terrible one memory usage cuz I keep on declaring new stuff but that's fine oh no oh wait no I misread that well tell more something but people are doing much class I think you can play maybe there's a smarter way actually I think now that I think about it a little bit yep I could have done now you pie cup diner in one breadth-first search and diner in one breadth-first search and diner in one breadth-first search and then like or maybe not purpose to it but like it's a shortest path problem where yeah you get to each point and then the cheapest route that you could get into that point or someone like that yeah but I didn't do it that way so and running time was fast enough I guess actually not I think about it I don't know why I did in my crazy way even though I thought that I mean it's morning time should be okay but it's just quitting is not ideal for and in the wheel but um but you can actually do something like some sort of connected components on think I think one thing that it reminds me of actually it's kind of like a minimum spanning tree actually and you could do that in linear time very quickly and then use a greedy classical album where yeah for every time you just take the smallest element that's in this yeah I mean but essentially yeah Costco you could do it in Union fine or other thing like that so yeah it so action oops I guess I was too lazy to think about this plan because I just was like okay this solves it and then we think about it that much but clearly look at the submission time I think you can actually self-discipline I think you can actually self-discipline I think you can actually self-discipline some sort of I mean I think it's not a minimum spanning tree sorry but you're trying to find a spanning tree for which there's a cause and it's like a variation on the shortest path spanning tree maybe there's minimum I don't know but the core point of those spanning tree algorithms is that it is greedy and I think if you just construct things such that like you connect stuff every longer way and you have a lookup table to see where it connects and like yeah like I'd in connecting energy would keep merging similar to like the chi-square room one similar to like the chi-square room one similar to like the chi-square room one of the minimum spanning tree limbs and then you can do that in linear time because you only yet we pass EG which is just read plus read times 4 so which is all really obviously where we use the number of taxis which is n square so that should be fast well hmm but I did not do that so always there to say about Islam I think actually for hard fun this is okay depakote a um I think how long did I end up taking okay 15 minutes I mean I didn't get the right white solution but quite enough which is actually mix it up on palm I think now that I think about it maybe mix it up good interview plum in a sense that well what is it's just greedy too greedy ish there's a spanning tree thing and truly there are a couple of ways to do it clearly because I did in another way and it seems to fit so at least you get to explore within de we were like different ways to kind of approach this and kind of like look at constraints and kind of attack it that way which i think is fine it's still a little bit on the tricky side I don't like greedy palms in general but that's a very personal bias only because I feel like I just I'm terrible at greedy algorithms and I have to prove them correct and I know that people always mention about the Metro Metroid's and then try like I can't do it's that it's just maybe something I need to practice in with a lie and I couldn't my head did not even go that way for this one so well yeah but that said you could probably do some yeah I mean I think actually you could have done it with one depth first search if you have a 50 to the fourth away but that's probably a little that's quiet little wedding time intensive so I don't know but post it yeah but over yeah my oh what a fun problem I think but and connect the components just keep popping up in random places I definitely maybe not one as hot as this one but I definitely ran into it these kind of interview
|
Swim in Rising Water
|
reorganize-string
|
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`.
The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`.
**Example 1:**
**Input:** grid = \[\[0,2\],\[1,3\]\]
**Output:** 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
**Example 2:**
**Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\]
**Output:** 16
**Explanation:** The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 50`
* `0 <= grid[i][j] < n2`
* Each value `grid[i][j]` is **unique**.
|
Alternate placing the most common letters.
|
Hash Table,String,Greedy,Sorting,Heap (Priority Queue),Counting
|
Medium
|
358,621,1304
|
876 |
so hey guys welcome back so let's solve our today's lead code challenge it's a very easy problem middle of the link list so basically we're given the head of a single linguished so it's a single English we have to return the middle node of a link list so if there are two middle nodes we have to return the second middle node so let's say we have one two three four and five so uh we have to return the middle node of the link list right so here the middle node of the link list will be node 3. so our output will be three four five right so further we have one two three four five six so middle node here will be four so since the list has two meter nodes with value three and four so we have to return the second middle node which will be four so for the rubble English from 4 will be four five and six right so it's a various problem so simply what we'll do is will take two node pointers right so let's say slow and fast so basically main point here is slow will move one step at each every time slow will move one step and fast will move two steps so whenever our fast reach our pass reaches at the end slow will be at the middle right so let's say we have moved slow so slow will come here and fast is moving two steps one two parts will come here so now for the slow will move slow will come here and fast will come here because it's taking two steps every time one and two so fast have reached till end and slow will return the slope right slow will be pointing to the middle node right so I have written a very simple code here right so I have taken a slow and head so slow and fast so firstly both are pointing to the Head node so if hat is not equal to null so we'll keep moving fast and Fast and so while fast is not equal to null and fast next is not equal to we'll keep moving fast is the two steps fast will be 0.2 fast is the two steps fast will be 0.2 fast is the two steps fast will be 0.2 fast next and then it's next slow will point two slows next right and at last will return slow which will point to the middle node of the link is given right mean simply we are running a while loop so while so now uh further in fast in Fast and X we have another burden in the next of fast we have a null right so we'll come out of the while loop and we'll return the slow pointer which is pointing to the middle note so now further in first next we have a null here so slow will obviously point to the middle node now so after coming out of the while loop we'll return slow right so let's try to run it's running so accepted so that's it for this video If you still haven't doubt you can ask in the comment box otherwise it's a basic level problem so I will explain yesterday's lead code challenge also so stay tuned for more videos if you still haven't doubt you can ask in the one comment box right
|
Middle of the Linked List
|
hand-of-straights
|
Given the `head` of a singly linked list, return _the middle node of the linked list_.
If there are two middle nodes, return **the second middle** node.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[3,4,5\]
**Explanation:** The middle node of the list is node 3.
**Example 2:**
**Input:** head = \[1,2,3,4,5,6\]
**Output:** \[4,5,6\]
**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.
**Constraints:**
* The number of nodes in the list is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
| null |
Array,Hash Table,Greedy,Sorting
|
Medium
| null |
546 |
hello friends in this video we will solve it called problem number 546 remove boxes so first we will understand the problem statement after that we will see approach for this problem and at the end we will see code in java let's understand the question so in the question we have given boxes of different color representing different positive numbers and we need server rounds to remove boxes until there is no box left each time we can pick contiguous boxes with the same color and remove them and we will get k into k points so we need to return maximum points we can get so let's see example one so here we have given array one three triple two three four three one here two is three times continuously so it will be three into three it will be nine as we can see after removing this part so we have then we will remove this four so it will be one into one why we are doing one into one because we are removing k elements so it will be k into k points we will get after that we will remove this then we have three continuous three here we can see so it will be three into three equal to nine after that we remove this so we have one to continue so this is so it will be 2 into 2 equal to 4 then it will be 18 19 23 total is 23 so final answer is 23 let's see example two so we have here continues one three times so it will be three into three equal to nine so this is maximum points we can generate from this error if we not select continuous one then we select one at a time then it will be if we select this one so it will be one into one equal to one so it will be three so it is not maximum we will get continuous one then only we will get maximum points let's understand the approach for this problem so this problem is dynamic programming problem so first we will take l and r as two indices it is pointing to this indexes so we will count this continuous elements so we have three continuous elements so now our r will be pointing to this so we will count this continuous elements so till that we will get two continuous elements so our eyes for r is pointing to this so we have count equal to 2 means k equal to 2 we have after that we need to check from this range l to r how many connected ones we will get so we will it will be dp of l r minus 1 k plus 1 means l 2 r minus 1 means till this and we have k equal to 2 and one we have added because our value is 1 so we need to find out this value in this sub array we need to find out so we had calculated from this part we had calculated so it will be k plus 1 so actually we have calculated for this part what about this remaining part so we will solve like breaking from taking i as a point and breaking into the array means fixing some breaking points after that taking from that range like dp of lr of k will store because we have calculated value of dp of l rk this here we can see this we have calculated but we don't know about this part this will also give us maximum answer we will calculate as dp of l and we will check i and r is equal here we can see so it will be so this is calculated as k dp of l2 i minus 1 means this part we need to find out and we know that this is k so it will be k plus 1 and dp of i plus 1 2 r minus 1 we need to find out we don't know about that problem so it will be count 0 so this is our final dp solution as we saw in the previous that again i am repeating to clarify this l and r represent the range k is the count that we are counting the continuous count after that we have calculated this continuous one supposed we have suppose that from l to r minus 1 we have remaining numbers that is k so we have calculated in this part so and we have suppose that we have remaining this as 0 means we don't know about that but in this also we get maximum continuous also so before that we had written this condition like when we get a of i and a of are equal then we will use this condition so it will be means we have we are supposing this as k after that for i minus 1 from this to this we need to find out so we are taking as i minus 1 means not including this i so because of that we are adding k plus 1 means adding plus 1 to it after that for this part i plus 1 to r minus 1 we are put count as 0 means we are initializing as 0 we don't know about this let's see time and space complexity for this solution so time complexity will be o n cube because we have dp of l r k after that of n for iterating splitting the ranges so there is a trick to remember in dynamic programming to find time complexity like we are taking the states into iterating the loops if there are nested loops then it will be increased to n square so our final time complexity will be of n to power 4 and space complexity will be of n cube because we are storing dp of l r k so they have three dimensional errors because of this reason we got n cube let's see code in java so here i have defined dp of three dimensional it represents l r k where l represents the range from l to r and last one defines the count so here i am calling the function solve boxes and boxes is the array of positive numbers and dp we had created and zero means starting index means l and boxes length minus r one means r and count is initialized as k zero so in this function we are checking if l is greater than r means we had crossed the first to the last index then we are returning the zero here i am checking that condition how much ones are continue so here i am calculating this k plus boxes of r and r minus 1 frame the last indexes after that i am checking if l and r this range is already calculated with the current count then we are returning this calculated value after that i am calculating from l to r minus 1 and k plus 1 into k plus 1 because we are calculating in r also because of that we are adding plus one here we are taking r minus one so we have calculated till this l two r minus one and supposing that we have uh continuous elements from the last so we need to partition that part and calculate in between also from l to our range so here we are rotating to l to our range and calculating that at any given point of the box means at any box same between l and r is equal to the last one then we are applying this condition previously calculated value is max or from l to y means taking the i as the part and k plus 1 plus i plus 1 r minus 1 and count is 0 will get the maximum value in this dp l2 range and count then at the end i am returning the answer thank you for watching my video please like and subscribe to my channel because it motivates me to create more videos
|
Remove Boxes
|
remove-boxes
|
You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
Return _the maximum points you can get_.
**Example 1:**
**Input:** boxes = \[1,3,2,2,2,3,4,3,1\]
**Output:** 23
**Explanation:**
\[1, 3, 2, 2, 2, 3, 4, 3, 1\]
----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points)
----> \[1, 3, 3, 3, 1\] (1\*1=1 points)
----> \[1, 1\] (3\*3=9 points)
----> \[\] (2\*2=4 points)
**Example 2:**
**Input:** boxes = \[1,1,1\]
**Output:** 9
**Example 3:**
**Input:** boxes = \[1\]
**Output:** 1
**Constraints:**
* `1 <= boxes.length <= 100`
* `1 <= boxes[i] <= 100`
| null |
Array,Dynamic Programming,Memoization
|
Hard
|
664,2247
|
1,043 |
hey everybody this is Larry this is day three of the February Leo day challenge hit the like button hit the Subscribe Buton join me on Discord let me know what you think about today's PR 10:43 petition away for maximum sum uh 10:43 petition away for maximum sum uh 10:43 petition away for maximum sum uh yeah I'm here again spamming you about my walking channel so you want to check that out my journey F Japan um every couple of days I'm going to try to do every couple of days I release another episode uh and after that I'll get to Taiwan and you know so it's actually a lot of episodes left so we'll figure it out but uh hopefully it's interesting or at least you know just get to walk around and hang out uh anyway let's take a look at today's Farm I want to make a disclaimer that I'm actually uh um on a gym thing because I think I talk about the gym a lot here and it's kind of I don't know let me know in the comments if you don't care about this at all I maybe it's I don't know just kind of give an update but it's kind of relevant because I've been doing uh for this day um I'm currently about I want to say 20 hours maybe give a take an hour or two a 20 hour fasting um and I'm trying to do a 72 hour fast so it's going to be a 3day fast um yeah so if I'm a little bit you know then you know that may be why um but the short answer was that I think I've been bulking a lot since I kind of came back and I've been eating a lot um but it apparently uh is Flowing off my blood sugar level so um so I'm trying to kind of reset a little bit I thought I was going to gain another like 5 six lbs before doing the cut I don't think I'm doing a full cut but I am going to at least uh crean up a little bit first so yeah anyway let's take a look at today's Farm uh and we'll see what how well I can do on no food for 20 hours uh let me drink some water because it's better than nothing all right giv it an energ away partition and AR way into contigous subr of length of most K after petitioning each Subway has his value changed to become the maximum value of that Subway return the largest sum okay what's K oh K is the length Oh I thought it was just for partition it um you just consider the largest but in here it seems like it actually is um it actually changes them to like K * n it actually changes them to like K * n it actually changes them to like K * n okay that's actually a little bit interesting um hm I mean the first thing I would notice is that n is 500 so we can do something about like n Square maybe we have to be a little bit careful how would I think about this maybe the hunger is start starving starting but um H so we want so with this one we want to maximize so the idea or my initial idea I don't know the answer yet just to be quick even though this is a medium I don't know uh I my initial idea is going to be that okay well the observation is that like and I don't think this is greedy but if we were to think about a greedy strategy to kind of play of ideas then we wouldn't like the max number to kind of um you know surround all that it can right and then the question is I don't know that there is a greedy exchange argument um because the way the reason why I say that is because this is a hug different problem you want to maximize and minimize right so that's why I'm kind of uh I guess minimize is actually a dumb problem at least the rate that in this exact preciseness because then you just have every number for itself because you can only make things worse in this case so I guess yeah in this case we want to maximize huh I mean given that n is 500 I mean I'm I was trying to think about some strategy to be honest and then try to prove those strategies like if I had a greedy I would have to prove greedy but also to be honest maybe that was a little bit silly because given that n is 500 my other um Dot may be just uh dynamic programming right yeah I mean it maybe I'm still trying to think through the greedy is thing but I don't know yeah but DP maybe is reasonable because then now okay what would DP look like right so basically maybe we have something like um get Max Index right and I don't know the dimensions yet but you know we want to keep it n square or n Square log n at most for 500 that's my kind of back of the head envelope right so here and I don't know if that these are the dimensions yet I guess actually thises make sense okay but the idea here is that um you know get Max gets to Max after partitioning starting from Index right um yeah so that means that everything before that has already been partitioned and you already got a score so you don't have to worry about it and in that case then now you can Bo Force just taking K is equal 0 1 2 or not K is equal but like I is equal to 0 one two well I guess zero doesn't make sense but one two three dot order to K so I think that makes sense then right so if this is greater than n then we turn zero because we're done so I guess in this way is actually not that bad usually I'm pretty good at DP but to I maybe a little bit uh shaky about it but yeah but basically now here we get uh up to K right something like okay so the best is equal to zero because we want to maximize so it's just a cental value maybe you could do negative Infinity if you want to play that I don't think there's any negative numbers so it should be fine either way but then yeah and then uh oops and then maybe current Max is equal to zero as well and then here we go um current Max is equal to Max of um ARR I or index plus I uh or current Max right and then here the idea is that now we can do recursion right because we get Max um index plus I right and here we have to kind of make sure that index sub I is U this is less than or equal to or less than n right something like that and you can maybe terminate early so you can do something like I don't know right even this looks kind of yucky but uh for now we'll focus on this right so here this is basically what you want to do um uh plus one because this number this index is already into the current Max and then the score that you get is actually equal to um current Max times uh I + 1 right because I plus 1 is the uh I + 1 right because I plus 1 is the uh I + 1 right because I plus 1 is the number of numbers that you took so yeah and that's pretty much it I think uh in the concept of course we have to do dynamic programming things I'm going to run it real quick looks okay and yeah and of course like I said uh this kind of branes out oops this kind of branes out a couple of times right so of course we want to um yeah we want to memorize so let's oops let's do it oh man I am really right now sorry and sometimes people ask me why I separate them out it just makes it easier to read this part of the code uh and just make all the space kind of explicit yeah uh I'm going to do an extra prom after this because I apparently I already done it though I did struggle a little bit of this but uh yeah uh 1404 day streak uh yeah and this is going to be linear space because we only have linear number of inputs and each of them is all one space um o of n * K * because well I mean there's only o * K * because well I mean there's only o * K * because well I mean there's only o of n input and this takes all of K at most of course K could be at most N I think I don't remember yeah so you could say it's all of K * n or all of n s but say it's all of K * n or all of n s but say it's all of K * n or all of n s but I don't way you know that's pretty much it um don't know why I struggled with this one I mean I thought I did okay oh yeah I guess I actually WOTE pretty much the same code last time but I just felt like mentally i that's the problem with uh greedy solution sometimes it's just so like intoxicating the uh um enticing right because you're like oh I feel like there may be but then you know uh I think some of it that is that I cheated a little bit and that I kind of look at the constraints and like okay and as you go to 500 I don't have to like you know n square is going to be fast enough or 10 times K is fast enough so I'm going to do that but um I don't know but yeah uh that's what I have for this one I'm going to do a bonus one after this so stay tuned uh yeah that's all I have come walk with me stay good stay healthy to good mental health I'll see you later and take care bye-bye
|
Partition Array for Maximum Sum
|
grid-illumination
|
Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a **32-bit** integer._
**Example 1:**
**Input:** arr = \[1,15,7,9,2,5,10\], k = 3
**Output:** 84
**Explanation:** arr becomes \[15,15,15,9,10,10,10\]
**Example 2:**
**Input:** arr = \[1,4,1,5,7,3,6,1,9,9,3\], k = 4
**Output:** 83
**Example 3:**
**Input:** arr = \[1\], k = 1
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 500`
* `0 <= arr[i] <= 109`
* `1 <= k <= arr.length`
| null |
Array,Hash Table
|
Hard
|
51
|
92 |
let's go question number 92 reverse link to list two this is medium question uh let's get into it given the head of a singly linked list and two integers left and right where left is the smallic under white and liberate the node of the list from position left to position right and return the reversed list let's check the example one in this case uh-huh left is two uh-huh left is two uh-huh left is two four so we're gonna uh reverse this one so two going to here last and then three here four here and then we need to connect the before here to here and then we also need to connect this until to last item does this make sense so okay the example two there are only one item one libras is the same because the item is only one okay n is the number of node and then n is smaller than one and then uh bigger than one bigger equal than one and then small equal than 500 under the value is minus 500 to 500 left right is 1 to n but this makes sense okay and follow could you do it in one person sure okay today i'm gonna show you the one pass this okay my approach is one pass time complex case linear and space complexity what because we're gonna use iteration to reverse they'll link the list so i'm gonna use this one my output is um singly link the list right now to previous current next so i'm gonna let's this is the null and then i'm gonna switch combine one then we also have the left pointer and right foot here my approach is first i'm gonna locate it the current to reverse that point to do that i wanna use the left pointer so left point at two minutes we started to diminish if we reduce one and then here's the increased one so the uh point of pointing to start point at this time current pointing the first item of we need to reverse touch this makes sense so and then i'm gonna start to converting the brush by one like this and then that time i'm gonna reduce because we just go to get right minus left so that is the same as this one that is makes because left the pointing to start point that this makes sense move down change oh before that okay this time i'm gonna do this to point this point is one it to we have this one because after reversal we need to connect like this right so we also need to take 10 must be 2 so we can do connection for connection and then this is three as it is make sense so we're gonna increase freeze increase change decrease this is the minus one i do not need one so now but we want one more move so in this time previous the new tail so i'm gonna change to one and this is five then one four three two five so we able to make as this makes sense so okay let's start very slow and cold his head so yeah here so left is here and right you see here so i'm gonna move position here and then in this time i'm gonna lead you to left and right y left is one what is one not zero domain is this is one indexed so this time my five is current and that current is current next and then left i decrease left and then creating white this time we are here so we do make two pointer and connection is fret and tail is correct and then i'm gonna write is minus before uh minus one let me try it and i need next is called next this is next and then i will change next to fret like this and then both the fret current then current to next because this one is just connected that is the reason why i made temp and then i will reduce by this minus one so boop minus one minus so now we are here so it's time to connect this one to this one so uh-huh but so uh-huh but so uh-huh but we need to check uh quarantine's exist or not if the okay let's say left is one in this time this one is the taillight so at this time frame on current none this one is not execute and that current is flared all right so if corner and then i will lead to con next is four next one right for next one next to four so one next connection next is for voice flash otherwise and then if correction is not exist and then p is head so head is fresh right and then if otherwise that means there are only one item or something else so at this time tell most people and then i'm gonna return head looks good thank you
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
1,761 |
and countries abroad today we're going to approach problem 1761 a minimum degree of a connected Trio in a graph 17 is the age that I started programming so no if you didn't start before you were like 11 like some of these nerds um there's still hope for you and 61 is the age by which I hope to retire because um trying to take a yacht around the Catalina ymics I don't know anyways let's go ahead and get a get to this problem so we're trying to find the minimum degree of a connected Trio and a graph what does that mean I don't know I haven't really read the problem yet so let's just go and get into it okay you're so you are given an undirected graph okay you are given an integer n which is the number of nodes in the graph and an array edges where edges I equals uvi in a case that there is an undirected edge between UI and VI Okay cool so it's already telling us right now this is a graph problem my favorite what I can solve hopefully there's no dynamic programming or something trickery or place just a direct graph problem maybe a little graph traversal something fun like that a connected Trio is a set of three nodes where there is an edge between every pair of them foreign okay so there's a triangle right so connected Trio is like hey it's me and Mario so I have these three nodes right they're all connected to each other like this there's an edge between every pair of them right so this is a pair of nodes there's an edge between them and this is the last pair of node and there's an edge between them so yeah I'm just making sure that it has to mean that they're directly connected right because you could also be like if there wasn't that condition then you could be like well this is a trio right this is a trio because they're connected but no they have to be directly connected so with that okay this would be a direct connection so triangles there should be triangles in the graph that's what a trio is um the degree of a connected Trio is the number of edges where 1.1 endpoint is in number of edges where 1.1 endpoint is in number of edges where 1.1 endpoint is in the trio and the other is not okay so for this system here right if we had additional edges maybe coming out of here I don't know why I circled this okay like that right where one endpoint is in the trio and one is not okay so this is a part of the degree because one end point of this blue connection is inside of the trio while the other is outside of the trio right same with these additional ones that I'm coloring now all right these are also uh degrees because one end is in the trio while the other is not versus these connections here right here and here both ends of these Edge connections are in the trio right because if both ends connect to these green nodes right they're in they're both ends are in the trio so they're not counted so the degree of this example would be one two three four five or five okay so I think before we even continue okay well return the minimum degree of a connected Trio in the graph okay so there's really two stages to this problem just right off the back think of first we need to find all trios and second we need to calculate the trios degree well when we look at the basic idea of a degree of something right like this has degree three we'll do a different color um let's go with yellow so this has total degree three not Trio degree I'm just talking about this node right because there's three edges coming out of it there's I can't count there's four edges coming out of this one right and there's four edges coming out of this one so the total degree of this Trio is what so we can get the total degree of this system of every node by taking the count so we take the sum of the degree at each node and we divide it by 2. now why do we divide it by 2 well because we over count right so for this edge here right we're going to end up counting it twice because we're going to count it once for this node and we're going to count it once for this other note so we need to divide by half because every node will get counted twice because every note inside right the edge touches both sides so it adds a degree components to both sides so it's counted twice so we divide it by a half so that we only count every Edge once right so for this system we have one two three four five six seven eight right so there's eight total edges right and then we want to eliminate the uh the red edges right because they aren't a part of the trio so for any Trio there's going to be three additional edges that create the trio right no such other link can exist right so the edge weight is in this minus three does that make sense because we count all the edges we divide it by a half and that will give us the total degree of this Trio system but we don't want to count the edges that are both connected to uh endpoints of the trio right these red ones and there's always only going to be three of them because you need a triangle or three edges to create the trio so the degree or let's write in Black because we're confident about it so the degree of a trio uvw is one half degree of U plus degree of V plus degree of w minus three all right because this part here will give you uh this part here will give you the whole degree the system and then this three will minus out the edges that are part of the trio so that's not going to be hard so how can we find a degree of each node well let's um let's go ahead and do that um so first thing we'll do is we'll create a graph and a degree graph and this one will both be default decks because you know we love default decks around here or no since n is given we'll uh so the graph will be a list range n okay now getting one of those issues because it starts at one and I keep making that mistake so we'll do n plus one and there'll be a zero node in our graph that just never gets touched and then our degree will make it a set and I'll show you why we're doing that in a moment again in range n plus one okay and then what we'll do is we'll look at each UV Edge in edges and we're going to create this graph so to create a graph we say you know graph at U has a connection to V and graph at V has a connection of U and then the degree of U we add in v and the degree of V we add in u now some of them are looking to say like you're doing more operations than you need to but you know this is 2N space so I don't really care there's probably a little bit better like a little cleaner way of doing this but you know I need end space to create G and I need n space to create degree that's 2N it's still in I'm not going to worry about it if it makes it easier for me to think of the solution so if I need to later think like okay there's probably an easier way where I can eliminate something but just my intuition is telling me that I want to do both and hopefully that's the right way of doing it but I understand that it's a little weird looking you could do this okay I don't want to start playing this game because then I start doing weird things okay so let's make sure I can run that okay so we're gonna do that all right and then we have the calculation So Def um degree of U V and W so I'm just going to copy the formula exactly so it's one half times the length of degree of you we'll just do a sum because we're fancy degree of x 4. ah length of degree of x for X in uew and then we have the minus three for the members of the trio so this would be the degree of a trio we'll call it Trio degree okay so now we have that function here so now we're done with the finding the degree we built a graph we built this degree thing that may not make a total sense why now why we're doing it but when we go to part two it'll make just I should have probably done things in a different order but okay how do we find all Trio so I kind of did part two first because it was easier but how do we find all trios well I think the only way you can really do this is by let's look at this example here so we have four we have one we have two we have five we have three we have two and three and six okay so when we look at this as a graph this will have neighbors two and three and this will have neighbors one and five and this will have neighbors two I'm just doing it in uh graph form where each node has a list which is the list of its neighbors four has a neighbor one two and three one and five and see I already messed up this has neighbors one five and three one three and five three has neighbors one two six hopefully I did not forget anything I probably should have just printed it out from the screen but whatever okay so how do I know if I found a trio well what I can do is look at a node for every node I look at this note and I say for each of my pairs of Neighbors right so this is going to take N squared time which is not great but for each of my pairs of neighbors are they also direct neighbors so I look at my neighbor and I say hey are you a neighbor of three right that's what I asked too I say hey are you a neighbor of three because three is my neighbor and two says yes I am a neighbor of three yes well if I'm neighbored with two and three and two's neighbors three well then we have a triangle right I'm friends with him and I'm friends with you and your friends with him well hey then we're all mutually friends with each other right so if I look at each pair of notes and I say hey are you guys Neighbors then this system works um so for example if I looked at two now and I said okay I have pairs of neighbors one in five so I could ask five hey are you neighbors with one is going to say no I'm not neighbors with one and since it's not neighbors with one that means that there is no Trio right because in order if there'd be a trio there'd have to be a connection here and if there's a connection there that means that five neighbors with one and we have another Trio in a system so to calculate this it's going to take n cubed time because we're gonna have to look at each node nodes and we're going to look at N squared pairs of nodes to make a calculation and then using the set we can ask if someone's a neighbor an efficient time um then using the list we can look through each pair of neighbors easily okay so let's go ahead and do that all right so we're going to look at each node we don't need to look at node one okay and then we're going to say for U in range length of G of node for v in range okay now this is why it's confusing okay for I and range for J in range I plus one length of G of node so I'm looking at each pair of vertices that would mean that u v equals g of I G of V ER do you have node so these are my neighbors UV I'm sorry I'm right so I'm looking at the nodes ith neighbor and the notes jth neighbor right and I'm gonna ask okay I'm gonna call this you sorry I just want to make sure this is all good and I'm going to call these VW now I'm going to say if W is in degree of U so this means if my neighbor is Neighbors with my other neighbor then we form a trio right so if that's the case then we're going to have our Max Min degree equals float what is it supposed to return okay we'll just put Infinity say Min degree equals Min of itself so if there was another solution and Trio degree of uvw and I believe that will work if W and degree of my neighbor V so I'm asking if my one neighbor is a neighbor of my other neighbor then we form a trio my neighbor's neighbor and then we return Min degree if Min degree not equal float Infinity because if it equals float Infinity that means it never changed so it never found a value else negative one okay there's going to be an error because it's the first time yeah Trio okay I need to stick to someone told me that I need to stick to uh either camel case or whatever you call the other thing spacing with underscores oh I didn't return that foreign strange what's going on here that's not going to change anything okay so what did I do wrong here oh how embarrassing so I create the graph View v u degree of U add V degree of V add U we're going to sum the length of degree so the number of neighbors that you have for each of these things it's where that works still that something very wrong is going on here foreign so I'm gonna do a little debugging here this is very embarrassing I thought that this would be right but I'm definitely missing something um Let The Little Prince can't solve you know what I mean all right one two three one point five why it was the sum of this some of this is nine one two three four five six it should only be six wait one two three four five six seven eight nine oh because uh I'm an idiot so my first assertion isn't correct because oh okay so when this thing counts all of its nodes right the only ones that get double counted are the ones that are inside the trio right so the only nodes that get counted twice are the ones that are actually inside the trio but the ones that are outside the trio don't get counted twice so if we just count the degree these ones will get counted twice so this will get counted twice and this will count it twice so we don't need to divide by two the divide by two only works if you count every note in the system but some edges you count at one some edges get counted twice um yeah because I can't believe I didn't notice that so instead we can just minus six because all the edges will be counted once except for the edges that are inside of the trio which we don't want to count and since they're inside of the tree they're going to be counted twice foreign let's see if this is fast enough I'm pretty sure that n cubed is the runtime for this and if I win I'm going to give myself this little mint right here come on I want the mitt oh that doesn't seem good at all it seems slow time limit exceeded come on man it's n cubed see what's going on here foreign but it's a little heristic to try to increase the runtime slightly I'm gonna be giving you over the line hopefully foreign here is if you don't want to over count systems you've already tried right so now it only looks at each one once right so it won't over count but it's still failing why is n cubed oh yeah I'll put lemon exceeding yeah foreign Cube solution so why is this not and Cubed okay so the problem is that this is still n cubed so the runtime here is kind of unfair I just quickly looked at something which you know gave me the idea so for less than G we're gonna say G of U sort all right so we'll sort the list that way that it approaches things um it doesn't reapproach things it doesn't need to approach again just a thought I'm not sure come on man foreign Cube like the other ones but it's just not as n cubed I mean it's not as pretty foreign that's why sometimes these tles are unfair because you know this is n cubed but it's not you know yeah me imagine doing this in a contest and just being like this just as fast as it could get we can do this too and D is less than Min degree so don't even bother going forward but that's just an extra calculation that's okay significantly it is checking if something's in something though I can't get rid of this reverse equals true sometimes man shoot for the star you can land on the moon you know what I mean Okay so foreign okay this solution works but it's just not foreign okay so there's a if length of or when your early termination here so if a length of graph of U is look greater than or equal to foreign you're kidding I didn't know that uh yeah if he can wait another 10 minutes 15 minutes okay I'll get uh genie on the road we'll be there as soon as I can okay bye-bye thank you everybody
|
Minimum Degree of a Connected Trio in a Graph
|
count-sorted-vowel-strings
|
You are given an undirected graph. You are given an integer `n` which is the number of nodes in the graph and an array `edges`, where each `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`.
A **connected trio** is a set of **three** nodes where there is an edge between **every** pair of them.
The **degree of a connected trio** is the number of edges where one endpoint is in the trio, and the other is not.
Return _the **minimum** degree of a connected trio in the graph, or_ `-1` _if the graph has no connected trios._
**Example 1:**
**Input:** n = 6, edges = \[\[1,2\],\[1,3\],\[3,2\],\[4,1\],\[5,2\],\[3,6\]\]
**Output:** 3
**Explanation:** There is exactly one trio, which is \[1,2,3\]. The edges that form its degree are bolded in the figure above.
**Example 2:**
**Input:** n = 7, edges = \[\[1,3\],\[4,1\],\[4,3\],\[2,5\],\[5,6\],\[6,7\],\[7,5\],\[2,6\]\]
**Output:** 0
**Explanation:** There are exactly three trios:
1) \[1,4,3\] with degree 0.
2) \[2,5,6\] with degree 2.
3) \[5,6,7\] with degree 2.
**Constraints:**
* `2 <= n <= 400`
* `edges[i].length == 2`
* `1 <= edges.length <= n * (n-1) / 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* There are no repeated edges.
|
For each character, its possible values will depend on the value of its previous character, because it needs to be not smaller than it. Think backtracking. Build a recursive function count(n, last_character) that counts the number of valid strings of length n and whose first characters are not less than last_character. In this recursive function, iterate on the possible characters for the first character, which will be all the vowels not less than last_character, and for each possible value c, increase the answer by count(n-1, c).
|
Dynamic Programming
|
Medium
| null |
1,509 |
everyone welcome to my channel so in this video i'm going to try to solve this problem and at the same time i'm going to follow the general interview steps while trying to solve it so first of all let's restart this question to get a good understanding so minimum difference between largest and smallest volumes removes so given an array numbers you're allowed to choose one element of nums and change it by any value in one move so return the minimum difference between the largest and smallest value of nums after performing at most three moves so let's say we have the array containing four numbers five three two four then we are going to output at zero that's because you can change the array to containing identical numbers so we change five and three and four into two and then the diff between the max and min is going to be zero okay so essentially the question is asking about we could randomly select three numbers from the array change them to anything we want but the thing we want finally is the minimum difference between the large and largest and smallest numbers in the array all right so let's see the constraints so it says the length of the ear is anywhere between 1 to 100k and then each number is between negative 1 billion to positive 1 billion so having said that let's think about the ash cases so the ash case i can think about is if we contain uh one number two number three number four number which means smaller than or equal to four numbers then we can change the array into uh identical then for sure is gonna be zero as the output value so um let's see how to solve the general cases so what i mean general cases it means we can't we have more than four numbers uh in the input array so let's see how to solve the general cases so the first way you can think about is kind of brute force um since it is asking us to find the diff between the largest and smallest thing it reminds me to do the sorting first so let's say the first proof of solution is about starting so let's take an example let's say we have uh we have example 2 as the input then after sorting the array is going to be like 0 1 and 5 10 and 14. so after sorting um we can change any of the three numbers into anything but essentially although it says uh just a change rate of the numbers it's very much it's pretty much the same to me just to remove the reader with the numbers from the array because we don't want to change the number to be anything worse so for example we don't want to change the way into a billion so that's not going to help us find the final answer so let's say if we just remove three of the numbers from the array then what we could do is uh like we don't really need to do the move so essentially what we do is we just remove the number so it's very so for this question it's just identical whether we do the number change or we remove the straight numbers so let's say we have the array sorted so we have four different ways to remove three numbers from the array so when i say four numbers that is because um we don't want to remove the numbers in the middle because it's not going to help so let's say we want to if we remove 1 5 and 10 from the array it's not going to help us because we leave the largest number and the smallest number in the array so that's not going to help us find the final answer so instead what we want to do is we want to remove the smaller numbers which means the beginning of the array where we want to remove the larger numbers which means the end of the array so we could choose rid of the numbers from either side or some kind of combination so let's say we remove three small numbers then we have the array left as 10 and 14. so if we remove two of the small number and one large number then we have 5 and 10. and similarly we could have one five left and if we remove all of the large numbers of three large numbers then we have one zero left there so of course the smallest diff between four choices are going to be the last choice which is zero and one so in that way we can solve the general cases so the runtime is going to be unlocked and that is because you're going to do the sorting so n is the length of the array so that so since we mentioned that we can remove we just remove those three numbers either from this beginning or from the end it makes me uh so it feels to me that we don't really need to sort the entire array so instead what we need to do is we just need to find the four of the smallest numbers and the fourth of the largest numbers and then mimic the process we do the number removal so in this way let me repeat that so if we if so if we look at the optimal way to solve this problem essentially the first step you need to do is we need to find the four smallest and four of the largest numbers that's the first one and then we just mimic the steps he talked about so the step we talked about is about like for example you have four of the smallest numbers so let's say we have s1 s2 s3 and s4 and via l1 l2 l3 and l4 so else s2s s1 four are the four of the smallest numbers l one two three four uh four of the largest numbers so they are all sorted in us and the other so like i said uh we could mimic the process about like we remove all the three smallest numbers or remove the two small number one largest number so something like that so that leaves us four of the choices if we remove four three of the smallest one then we have the div as l4 minus s4 so if we remove two small one large one then we are looking at l3 minus s3 so if we remove one small and the two large then we are looking at l2 minus s2 and then if we remove all the three large numbers then we are looking at l1 minus s1 so we could just define the smallest one among all of the four different choices here so here uh we are looking at the runtime as linear that is because to find the small for smallest and largest numbers it is going to take us linear time and the second step mimicking the step we talked about it is going to be a constant uh runtime so to find the fourth of the smallest or largest number it reminds me as to use priority queue to solve this question so having said that i think we have everything to get us to do the coding work so let's start to do some cleaning work on top of it so first of all like i said do some ash case checking if nums dot lens is smaller than five then you're just going to return zero otherwise um we are going to have the priority queue um so yeah so you have the first priority queue as a main heap you don't need to do anything special try already you have the private queue containing four numbers and then the second way you're going to define the mass keep so the large numbers are getting we get from the mean for the smallest number you get from the max heap so we have four and this one we need to have collections dot reverse other and then um the next step is we try to fill the mask keep on mini heap and at the same time we make sure the size of the heap is gonna be four so it goes through the numbers within thumbs array i insert it into the heap so we will say okay me heap dot add num and max keep that num as well and in case the size scroll over four we need to remove numbers from that so if the size is larger than four then we need to say okay me heap double maxi double all right so that's pretty much it uh to find the smallest and the four smallest and four largest numbers then we need to define the uh the thing we talked about we have the smallest as new into four and similarly we have the largest four as well and then we go through everything left in the heap so smaller than four plus i so for the largest one for okay so for the smallest one we want it to be sorted and it is going to be from the mass keep so the top element from the max heap is going to be the largest one um so it's uh it's going to be the largest one so in this case it's going to be 3 minus i so we want the smallest one to be sorted as any other so that means we are going to fill this array in reverse and reversely so you have mass keep that pull so for the main heap um so for the main heap is going to be as on the other so we have the largest i as a heap.4 all right so that's it and then we have the let's say we define mean div as equal to knee as you go to continue the max value it goes through all the four different choices like i talked about so min div is equal to mass dot min and if this would be largest i minus smallest i and finally we just returned so for simplicity i'll just rely on this platform to help us do the to do the debugging work so first task is works let's do more of the test cases all right so it seems like everything works well so that's pretty much it for this uh solution so if you have any questions regarding the solution or regarding the piece of code feel free to leave some comments below if you like this video please help so subscribe to this channel i'll see you next time thanks for watching
|
Minimum Difference Between Largest and Smallest Value in Three Moves
|
replace-employee-id-with-the-unique-identifier
|
You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes \[5,3,3,4\].
In the second move, change 4 to 3. nums becomes \[5,3,3,3\].
In the third move, change 5 to 3. nums becomes \[3,3,3,3\].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
**Example 2:**
**Input:** nums = \[1,5,0,10,14\]
**Output:** 1
**Explanation:** We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes \[1,0,0,10,14\].
In the second move, change 10 to 0. nums becomes \[1,0,0,0,14\].
In the third move, change 14 to 1. nums becomes \[1,0,0,0,1\].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 0.
It can be shown that there is no way to make the difference 0 in 3 moves.
**Example 3:**
**Input:** nums = \[3,100,20\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes \[4,7,20\].
In the second move, change 20 to 7. nums becomes \[4,7,7\].
In the third move, change 4 to 3. nums becomes \[7,7,7\].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Database
|
Easy
| null |
1,685 |
hey there welcome back to lead coding in this video we will be solving the second question of lead code biweekly contest 41 name of the problem is sum of absolute differences in the sorted array you are given an integer area numbers sorted in non-decreasing order sorted in non-decreasing order sorted in non-decreasing order build and return an integer array result with the same length as nums such that result i is equal to summation of absolute differences between numsai and all the other numbers in the array in other words you can see the equation so basically looking at the first example we can know that for computing the answer for the 0th index we have to find the absolute difference of 2 with all the other numbers so we have to find the summation of that obviously the difference of 2 with 2 is 0 so that is why we can ignore this and moving forward we have 3 the absolute difference is 1 then with 5 and 2 the absolute difference is 3 so the total summation is 4 so the answer for the 0th index is 4. similarly calculating the answer for the first index the difference of 2 and 3 the absolute difference is 1 the difference between 3 and 5 is 2 so the answer is 1 plus 2 that is 3. similarly we can compute answer for all the other indices so if we compute the absolute differences for the current index with all the other indices it is going to take n square time but as the constraints are high we need to compute it in big o of n so there's something that we can do let me show you with the help of this example so if this is the array and if you want to compute answer for let's say 6 so the answer for 6 will be 8 minus 6 10 minus 6 so we have to add them and if we go behind six all the elements are smaller than or equal to six because the order of the given array is non-decreasing non-decreasing non-decreasing so for these indices which are behind six the answer will be 6 minus 4 and 6 minus 1. so here we can see the shift because the elements which are at the right of 6 are greater than or equal to 6 that is why we can write that element -6 and all the elements that element -6 and all the elements that element -6 and all the elements which are behind 6 are either smaller than or equal to 6 so we can write 6 minus that element so we can utilize the order that is given to us that is non-decreasing order given to us that is non-decreasing order given to us that is non-decreasing order and what we can do is if we combine these two things it is nothing but 6 plus 6 minus 4 plus 1 so this is what we have to compute this is nothing but 2 times 6 minus summation of all the elements which are at the left of 6 so we can call this as l sum that is the left sum summation of all the elements which are to the left of 6 and let's say there are x number of elements to the left of 6 then we have to do x multiplied by 6 minus the summation is going to give us the absolute difference for the left side elements now talking about the right side elements so this is nothing but 8 plus 10 minus 2 times of 6 this is equal to the are sum summation at the right side minus 2 times of number of elements which are at the right so let's say there are y elements to the right of 6 so 2 multiplied by y so this is what we have to compute so this we can either do it by using prefix sum or what we can do is we can take the total sum the total summation of the array and let's say that is sum now while coming from the left side to the right side we can keep another variable that is going to count the l sum the left sum so when we are maintaining the l sum the right sum will be the total summation minus l sum minus the current element so that is how we can get the right sum as well so now we are going to look at the code to get better clarity of it so as i told you first of all you have to calculate the total summation so sum plus equal to a this is the total summation now n is the size of nums and we have to create answer of size n now we have to compute it so let us keep l sum this is equal to 0 and the right sum we are going to compute at the same time also in order to keep track of the elements which are at the left and which are at the right we can do it using the index also that is the i index which we are going to use for the iterations but let us for the sake of clarity keep the number of elements which are at the left so l num it means the number of elements which are at the left and okay we can compute the number of elements which are at the right inside the loop so for in i is equal to 0 i smaller than n i plus we are going to each of these elements and yeah so the answer for i is equal to number of elements which are at the left that is l num multiplied by the current element nums of i minus the total summation of elements till now that is l sum plus the total summation at the right side so that we have to calculate it over here into our sum is equal to the total summation minus l sum minus the current element that is nums of i so r sum the total number of elements which are at the right int r num is equal to total number of elements that is n minus 1 the current element minus the number of elements which are at the left so that is l num i'm just doing this for the sake of clarity otherwise i could have used this sum directly and keep subtracting the values from it and i don't have to create all these variables but here it would be more clear so rsum minus the number of elements which are at the right side that is equal to r num multiplied by the current element nums of i and after this we have to increase the l num plus and l sum plus equal to the current element for the next iteration i have to add this because this is now going to be the left element for the next element and hence the number of left element are going to increase finally i can return the answer let us try to run this now it is giving us correct answer let us try to submit and it got accepted talking about the space complexity uh we are just using space to create this answer other than this there is only constant space so if we ignore this answer then it would be constant space solution and about the time complexity we are using big o of n here to compute the total summation and big o of n here as well to calculate the answer for each index so if you like the video please subscribe to the channel and press the bell icon so that you can get notification to our latest videos thank you
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
30 |
hello and welcome in this video we are going to solve problem number 30 of lead code that is substrings with concatenation of all words so in let's go to the description and try to understand this okay so we have given a string s and the array of fasting words and we have all the strings of words are of same length so we can see that we have given hosting s and uh area of words and you can see that length of all the testing in words are of same thing that is of length 3 in this case and length 4 of in second case okay and a concatenated string is a s in s is a substring that contains all the string of any permutation of words of concatenator so we have to find out this concatenator hostings okay substrings so what is this so if we are con we are going to concatenate all the permutation of these words then this is going to be 4 bar 1 and second one will be bar 4. so all the permutation we have to check for all the permutation in this string so we have to find out if any of these permutation is present or not so let's starting we can say that for sorting barfo we can say there is a substring bar which is present which can be built from this words okay so we can see that 0 is going to be our first index and again at index 9 we can see that group who bar is present so we have to again insert these nine in our result and we have to return that in second case there are no testing that can present so what are the concatenated that can be built after with after concluding this so words good based word can be one concrete interesting and another one can be word based and so on word based good there are many options that we can build so we can say that none of these is present in this string so we will be returning a empty list in this case so how we can solve this problem let's first try to understand this then we'll be building some algorithm based on between that and writing the code for same so for let's check for this input s we will try to start checking from beginning so first we will check the first element that first three that is bar present in this yes bar is present again we'll be checking is four percent yes who is present so and then we are done with all the words so you can see that at zeroth index a permutation of all the strings is present so we'll be turning 0 in that case again we'll be checking for the next from next index our erf is not present again we'll be checking for next index our F1 note presence and so on at last will be coming at next 9 where you can check that who is present and we will be checking again the net for the remaining one that is bar yes bar is present so after that we can see that all the strings are present in the substring so you can see that this is a concatenated substring so we'll be turning 0 9 in that case so how you can check this so all that for that will like we checked for let's say there are four also yeah also here okay so in that case and of who is also here in that case we have to check for both so we have to keep count of all the strings here and check for all those things okay so how you can keep count of that we can keep count of using any that after something like hashmap so we will be building a hash map we will do that will be taking care of all the count that is 4 is 1 and bar is 1 in that case in this case let's suppose not to enter okay and we'll be checking is all the occurrences of 4 is present in that surfing or not if yes then we'll be checking for all the occurrences of bar and we have already founded all the kinds of four bar and let's say another string are present then we can say that this shifting is going to be one of our result Okay so we understand this let's try to write the algorithm for same so first we have to declare a hashmap that we are alternating so has my account is going to need in which we'll be doing count all occurrences of word not word all occurrences are passing of words okay and then we have to find out the length of all the concaten interacting how we can find out the length of all the concatened resting is going to be length something like the length of one a string multiplied by all the numbers so let's say uh length s length that is length of I think is going to words dot words 0 dot length Okay and what length of what is going to be length words dot length Okay and total number of length of a string s is going to be n equal to s dot length so this is going to need so we'll be keep editing from beginning and till when we have to check for up to like for the last three and three that is six character we don't have to edit like if you will find out that to be bar is not bar is present and then we'll be checking that is equivalent from here so 4 is not present so we don't have to check from a so till here we have to add it so from beginning to B we have to attitude so we will be doing 4 I equal to 0 to n minus word excellent into word dot length that is length Okay so we don't have to add it till last okay that is because this is going to give a error that is index Auto boundaries exception okay now after this inside this we have to check whether all the occurrences of true bar or lets any string is present in this suffering for or not so we have to check for only shifting of length 6 in this case so and so in general case what will be going length of Shifting what is the length of such thing that is going to be length of 15 is going to be s length into Len okay so again we are going to need hashmap for that hash map that is seen okay and we'll find out the substring substrate is going to equal to s dot substring I2 I Plus length that is s line into length okay and we have to check whether this shifting is containing all the a string of these words or not so how you can check that we can check by keeping all the counter of length of Aslan will be count all the excellent substring of this substring and then we can check with that whether our count in scene is equal or not if it is found to be equal then we can say that this substring is the permutation of all the words of this word okay these words array okay so we'll be doing the same count all the occurrences of substrings of length excellent of such TR okay and if scene and count are equal then in that case we'll be storing the result I in result and at last return the result okay this is going to be our approach and using this algorithm we can solve this problem so let's go to the compiler and write code for same okay so first we will check if s dot length is equal to 0 or s equal to null or what's equal to null or words dot length equal to zero in that case we have to do we don't have to do anything just return list of a string new array list of okay and after that you'll be declaring a high snap that we have this discussed earlier a string of integer for counting all the words this is going to be our counts okay now count all the occurrences of a string from words so for all the string from word into accounts dot put word count dot get a default if it is not present then in that case default is going to be zero Okay so over 0. and then return and then increase the counter by one okay after that we have to declare a string list of integer to restore all the result and then we'll be running the for loop from I equal to 0 to I should be lesser than s length that we have discussed so first found out the all the lengths s length is going to equal to s dot length so in that case s length is length of s string and then it's going to be length of what so then words Dot length and then let's say s length is going to be length of words 0 okay and N is going to total length of a string s n is going to be s dot length you can change this accordingly Okay so if you're greater than n minus s length into Len okay plus one and I plus now we have to find out the Sorting substr that is going to be s dot substring of length I2 I plus till the length of this s length into Len okay so we'll be doing I Plus excellent into Lane okay there is a error that we forgot this is going to be S length with L capital okay then we have to declare a hash map also that is going to be a string of and integer type this is going to your scene new s map now count all the currencies of words all the conservation from words and we will be checking that whether these scene and count is equal or not so we'll be doing this using into I equal to J equal to 0 and J should be lesser than service Dr Dot length and will be in the increasing our index by J plus equal to length of is a string from the word so s line so again we have to find out the searching of first tooth in the first test case from we have to find out the Shifting the first three characters so that is going to be sub that is we have to find all the word let's say what is going to be sub Str dot substring of length J2 J plus length okay then we'll be counting this using that something like this so just copy this and paste it here and change a little bit what is same so just change the count with scene yeah and if after that we will check whether s dot length sorry weather scene is equals to counts if it is then we have found our one concatenator testing and we will be storing that in our result Dot add I and at last returning result so it's time to run this let's check if there is any error yeah so we got error sorry words dot length this is a rate don't have to do okay so first test case has been failed and second third so I think with a mistake okay so after it has been accepted and uh one thing you can do like something like we are checking this congratulation for every time we can do one thing like we can move this part in a separate function and we can call that and keep checking so this you don't have to write this here so we have to keep all the code and put something somewhere in another function and we can keep calling them so that's what you can do by yourself okay so I am leaving this for yourself so we have solved this problem and uh I hope you must have learned something from this video in that case please make sure to like the video subscribe to our Channel and don't forget to share this video among your friend thank you
|
Substring with Concatenation of All Words
|
substring-with-concatenation-of-all-words
|
You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**.
A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated.
* For example, if `words = [ "ab ", "cd ", "ef "]`, then `"abcdef "`, `"abefcd "`, `"cdabef "`, `"cdefab "`, `"efabcd "`, and `"efcdab "` are all concatenated strings. `"acdbef "` is not a concatenated substring because it is not the concatenation of any permutation of `words`.
Return _the starting indices of all the concatenated substrings in_ `s`. You can return the answer in **any order**.
**Example 1:**
**Input:** s = "barfoothefoobarman ", words = \[ "foo ", "bar "\]
**Output:** \[0,9\]
**Explanation:** Since words.length == 2 and words\[i\].length == 3, the concatenated substring has to be of length 6.
The substring starting at 0 is "barfoo ". It is the concatenation of \[ "bar ", "foo "\] which is a permutation of words.
The substring starting at 9 is "foobar ". It is the concatenation of \[ "foo ", "bar "\] which is a permutation of words.
The output order does not matter. Returning \[9,0\] is fine too.
**Example 2:**
**Input:** s = "wordgoodgoodgoodbestword ", words = \[ "word ", "good ", "best ", "word "\]
**Output:** \[\]
**Explanation:** Since words.length == 4 and words\[i\].length == 4, the concatenated substring has to be of length 16.
There is no substring of length 16 is s that is equal to the concatenation of any permutation of words.
We return an empty array.
**Example 3:**
**Input:** s = "barfoofoobarthefoobarman ", words = \[ "bar ", "foo ", "the "\]
**Output:** \[6,9,12\]
**Explanation:** Since words.length == 3 and words\[i\].length == 3, the concatenated substring has to be of length 9.
The substring starting at 6 is "foobarthe ". It is the concatenation of \[ "foo ", "bar ", "the "\] which is a permutation of words.
The substring starting at 9 is "barthefoo ". It is the concatenation of \[ "bar ", "the ", "foo "\] which is a permutation of words.
The substring starting at 12 is "thefoobar ". It is the concatenation of \[ "the ", "foo ", "bar "\] which is a permutation of words.
**Constraints:**
* `1 <= s.length <= 104`
* `1 <= words.length <= 5000`
* `1 <= words[i].length <= 30`
* `s` and `words[i]` consist of lowercase English letters.
| null |
Hash Table,String,Sliding Window
|
Hard
|
76
|
14 |
hello everyone let's look at longest common prefix the problem statement is write a function to find the longest common prefix string among an array of strings if there's no common prefix return an empty string for the first example the input of flower flow flight so the output is fl for the second example input are dog race car so output is an empty string because there is no common prefix among the input strings to solve this problem we can take a couple of steps here first let us consider when the input ray length is zero we can simply return an empty string second for the longest common prefix it must be the prefix of the shortest element so we can find this shortest string from the input array and then we look through it compare its prefix with other elements to check if it is a common prefix for the implementation let's first consider the first case if the lens is zero we simply return an empty string to find the shortest item in an array we can use a race building sort method we're passing a function to determine the order we want to make the result in descending order based on its length so having this sort method we can have this input string in a descending order and then let's get the shortest element moving on let's try to loop through the shortest element and we want to have this eye outside of this for loop it is because when we return the longest common prefix we need to use this i so let's get the prefix for the current eye we have this i plus 1 this is because the second parameter for the substring function is the n index and the end index value is excluded in the substring result so we have this i plus 1. for the same reason for this loop condition we need to make i less and equal than the shortest dot length we can compare the prefix with all other strings in the array so we can use another array building method called avery this every method will test all elements in the array see if we return true for the provided function it will return true if all the elements return true and the statement here it will check if all elements in the string starts with prefix so if this statement is not true then we can break the loop and return the substring let's submit it passed let's look at the complexity for the space i think it's obviously it is constant and for time i think it's o of m multiply n so n will be the length of the input array and m will be the shortest length for the element thank you for watching
|
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 |
468 |
today's problem is to validate a given ip address that is you will be given an ip address and you have to say whether it belongs to the ipv4 version of ip address ipv6 version of the ip address or it does not belong to any of these categories that means it is invalid so you have to return one of these three values now let's see the definition of ipv4 and ipv6 ip addresses and which of them are valid and which of them are invalid so here i have written the v4 version of ip address and v6 so this these two the first ones are valid so here you see that we have four components we have first component a b c and d and they are separated with a dot and here again you see that there are different tokens here we will have eight tokens here we have four tokens here the tokenizer is dot character here they are delimited using this colon so that is the one difference you can note straight away not all of them are valid and we will come to that and these are delimited by dot characters and how many of them are there are four components so we need three of them here we have seven components eight components so we need seven of them so this is one difference now uh we should not have dot in the end so there should be at least one character between the dots or as the components abcd none of them should be empty here the same thing here we will have more a b c d e f g h so none of them should be empty and in ipv4 and ipv6 there are some other differences apart from delimiter here the values are between each of these values are only numbers here you see some alphabets as well as numbers in general they are hexadecimal values so not all the alphabets will be present so it will not be from a to z but it will be from a to f these are the hexadecimal characters and these are decimal characters are from 0 to 9 in total 10 characters because these are base 10 representation so 0 to 9 that is modulo 10 any value you take modulo 10 it will be between 0 and 9 here you will take modulo 16 and modulo 16 values are between 0 and 15 so for 0 to 9 we have we don't do anything but we don't allow double digits so for 10 we keep a 11 is b 12 is c 13 is d 14 is e and 15 is f we will not have 16 these are the 16 values and this a can be small a or capital a similarly b so these things are allowed so the range is a to f and 0 to 9. so each character should be one of these uh 6 plus 6 12 plus 10 22 values no other character so you will see that it follows all of those then uh let's go into the uh more detail so let's dive into the one of these components so we have looked from high level now let's go into the individual components will all lie between 0 and 255 both inclusive so it cannot be more than 255 so if it's 256 or 500 or something like that any component then it becomes invalid and here we will not allow leading zeros so this zero one is not same as one it should be written like this only so the number of digits can be 3 since it's from 0 to 255 maximum it can be also one digit 2 digit and 3 digits but not all three digits its value should be less than 256 so this is invalid here you see a 256 which is more than 255 similarly this is invalid since d is missing here the last part so this is also invalid due to this leading zero now let's look at the ipv6 rules so here we have four digits each of them are four digits all the eight components but if there are leading zeroes you can remove them for example this is also valid this is one digit this is four digit both are valid but here you are not allowed to have leading zeroes and you can see some small a capital a both are valid so this is valid this is also valid and this is also valid we have replaced both the zero zeros by single zeros but we have not removed this leading zero but you will not consider this as a series of zeros there is a delimiter between so you cannot write two consecutive columns and write just one zero since all of them were zeros so this is not allowed all the components individually should be non empty a b c d e f g h so that will become invalid if we write like that so the job is here very simple only thing is that you need to take care of the different rules so what we will do or let's define the rules for these so here for ipv4 we have to see that first we split it into tokens so for each token t what we will do ah we will check if its length is 0 or more than 3 so its length cannot be more than 3 since more than 3 would mean either some leading zeros are there or its value is more than or 999 so both are not allowed we will come to leading zeros in a minute so uh if length of t is equal to 0 or length of t is more than 3 then we return neither let's write n here for neither in actual code we will write neither then the second condition is that if first element of this token this is we are talking about for each token so this is a t first token second token third token fourth token this entire thing is ip so we are talking at token level if t 0 that is first character is 0 then again we return neither so leading zeros are not allowed now we have to check the validity of each character so for c in this token for all characters in this token what we will do if not is digit so if c is not digit that means it's not from 0 to 9 that is some alpha numeric characters are there then we again return neither and if integral value of this token that is its valid everything is digit there are no leading zeros and its length is also within this range now we will check whether its value is between 0 to 255 or not so if this is more than 255 again we return neither so this we check for each of the tokens and finally we will return ipv4 that is it is a valid ipv4 address similarly let's write the cases for ipv6 again we will split it into tokens so let these are the tokens t so for each t we will check if length of t is equal to zero or more than four we return neither so here the length can be maximum four it cannot be zero that is empty it cannot be empty and what else for each character in this token if c is not hexadecimal or hex digit then return neither and x digits are from 0 to 9 capital a to capital f small a to small f so if it's not among these characters these are not hexadecimal characters so we return neither and finally after this loop we return valid ipv6 now we have created rules for v4 and v6 now when should we apply which one so it's simple uh whatever i p is given to you ip is the input that is given to you and it's a string so what we will do we will check if i p contains three dots so this is the first path let me write here we have ip here this is a string and what we will do we will check if it contains three dot characters or it contains a seven this colon character or this is the other case any other case then we return neither here we don't need to expand this branch further and we will expand these branches any one of them not both so if it's this case then check the validity of ipv4 if it's this branch then check the validity of ipv6 which we have already defined the rules so only one of them will be checked if it's not among these return neither so no need to go further now let's write the code for this once you list down all the possibilities writing the code part should be trivial provided you know how to split strings in different languages so let's write it in all the three languages c plus java and python so first we will check which one should be check which branch we should go to ipv4 v6 or neither so if count is a function available in algorithms so you have to provide two iterators ip.begin two iterators ip.begin two iterators ip.begin to ip dot end and then which character you want to search so if this count is equal to 3 then here we will write the ipv4 logic so we will fill this first let's write the high level code else if the same thing so here we will write the logic to check ipv6 characters and if it does not go into any of these then we return neither so in this question either you have to return ipv6 ipv4 or neither and the return type is string now we will fill these based on our logic what we have discussed so we need to split it into tokens so we will use string stream here in c plus it does not have a ready-made split it does not have a ready-made split it does not have a ready-made split function like java or python so let me add one check for that last character last component being empty that is it's a dot b dot c dot d so if the if d is missing this string stream will not be able to catch that so let's write a explicit case for that or this will not be the case with split functions in java and python so this check will be only for c plus so if i p ip dot size minus 1 that is last character is dot then return needer and we will proceed now so we will keep looking for this token and it will be kept in this token variable so if token dot length is equal to 0 that is its empty or token dot length is more than 3 then return neither so this is for leading heroes so leading zero is only acceptable when we have just uh one character there so not all leading zeros are invalid let's say we have we are talking about ipv4 so let us say here we have hundred then we have a zero then we have five so here the first character of this token is zero but it's not invalid it's valid since its length is one so let's so if it's zero better its length v one otherwise it will be invalid now what next we have to check if all the characters are digits or not so for scene so we already have a function is digit in c plus we also have functions like each alpha or each x digit so character check also we have done now we need to check if the value is more than 255 or it's less than or equal to 255 so if s2i string to integer token is more than 255 return neither and if none of these scenarios occur we return ipv4 so we are done with ipv4 now we will write the logic for ipv6 uh here the length should be not be greater than 4 then we will check if these are hexadecimal characters or not so here the difference is x digit and here it simply is digit between 0 and 9 this is between 0 9 8 to f and finally so here also we will need this last thing should not be colon and i think we are done here let's try so let's check why our answer is wrong so it's an ipv4 so it should come here this is valid this seems fine if token is zero so this would be equal to not we have not to assign it but comparison let's try again if it fixes and this gives correct result let's submit and this solution is accepted now let's look at the time complexity it's around 4 milliseconds let's try once more i have seen quite a bit of fluctuation in timing within our different submissions again it's in the same range so let's leave it for now or we will move to java solution so let's copy it this will be mainly for logic there will be too much syntax change in the case of java so let me write it separately only so here we will apply a filter here we will add the ipv4 check if the count of this character is uh three similarly we will add the check for ipv6 just like here and then finally we will return neither and now it let's convert it to java so what we have to do uh we have to split this ip into tokens so the way to do that here is much simpler simply write ip dot split and it will split it into tokens and we will iterate for each token which is this loop and we are done now let's this length is valid and so here each digit is not valid it's capital d and here also you need to change integer dot percent token is more than 255 return zero return neither and now let's write the logic for ipv6 so this function is not there in java so what we will do we will write our own function so if not c is greater than equal to zero if it is greater than equal to 0 we will check it should be less than equal to 9 or if it is not in this range then it should be between a to f or capital a to f or so we got a couple of errors here this looks like a typo and this each digit is not found since it's inside character and this is also wrong we should have changed this to this and the solution in java is accepted finally we will do it in python 3. so if this count is equal to 3 then write the logic for ipv4 for each token we will check if len length of token equal to 0 or learn token so this line is also done so here in python we don't need to check for each digit we can check the token itself so what we will do if not token dot is digit so this we can directly check so we have combined both the checks into one we return neither so here we will check if each character is between 0 and 9 or not 0 and 9 and a2f so again we got a wrong answer for ipv4 not is not required we have already done not equal to and this python solution is also accepted
|
Validate IP Address
|
validate-ip-address
|
Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type.
**A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses.
**A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where:
* `1 <= xi.length <= 4`
* `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`).
* Leading zeros are allowed in `xi`.
For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses.
**Example 1:**
**Input:** queryIP = "172.16.254.1 "
**Output:** "IPv4 "
**Explanation:** This is a valid IPv4 address, return "IPv4 ".
**Example 2:**
**Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 "
**Output:** "IPv6 "
**Explanation:** This is a valid IPv6 address, return "IPv6 ".
**Example 3:**
**Input:** queryIP = "256.256.256.256 "
**Output:** "Neither "
**Explanation:** This is neither a IPv4 address nor a IPv6 address.
**Constraints:**
* `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
| null |
String
|
Medium
|
752
|
1,436 |
hello guys and welcome back to lead Logics this is the destination city problem this is a lead Cod easy and the number for this is 436 so in this problem we are given with an array Parts where parts of I gives City a and City B so this is a pair of cities means there exist a direct path from City a to City B so there is a path from City a to go to the city B and we have to find the destination city that is a City without any path outgoing to another city so uh we need to find the Final Destination or the city which has no outgoing path the which means that is the final destination from that you cannot go anywhere so that is the final destination and you have to find that there is a note in the question it is guaranteed that the graph of path form a line without any Loop therefore there will be exactly one destination city so this note actually ensure that there is one and only possible answer so let's see through an example so in this example one this is the input so from London you will go to New York from New York you will go to Lima from Lima you will go to sa Paulo okay so sa Pao becomes the Final Destination because there is no more path from sa Pao to another city this is the final destination so that's why we return s ball now in the next problem you go from B to C and then C to a so the final answer is a and in this from a to zed so the final destination is z so now let's see through uh the approach how we are going to solve the problem so for this uh for solving this problem we are going to use a hash set to store all the cities along with the it outgoing path we are going to iterate through the paths and add the starting city of the each path to the hash map and then I trade through the paths again and check the destination of each path and then if a city is not in the cities it means that there is uh no more outgoing path from the city so that's uh that's what we are going to use uh a hash set containing all the staties with outgoing paths then compare with the city is in the uh given array and if a city is not in the hashmap return that so uh let's see through an uh dry run suppose we have the input one so for this we are going to insert London New York Lima into the haset and when sa Pao comes uh it will not be in the uh list of cities without going edges so the sa Pao will be our possible answer and we going to return it so from London we go to New York to lima to sa Pao so sa Pao is actually a so now let's come to the code section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel so this hash head is to store the cities with outgoing edges then we are going to iterate then we'll add the all the cities from which outgoing path is there and then we are going to compare it with the city which does not have an outgoing part so this is the destination if contain our destination then we are going to return the destination otherwise we can simply return so this uh code runs for the sample test case let's run for the hidden test cases as well so it passes the um it passes with a good time complexity and a good memory complexity initially when I run uh try to run it was giving me 100% of the run time and was giving me 100% of the run time and was giving me 100% of the run time and so you can also check the C++ Python and so you can also check the C++ Python and so you can also check the C++ Python and JavaScript code by going into the solutions panel and here is my solution you can see this one you can also read the intuition approach complexity and check the Java C++ Python and JavaScript code and also C++ Python and JavaScript code and also C++ Python and JavaScript code and also remember to upo me so I hope you understood the logic thank you for watching the video have a nice day
|
Destination City
|
get-watched-videos-by-your-friends
|
You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
**Example 1:**
**Input:** paths = \[\[ "London ", "New York "\],\[ "New York ", "Lima "\],\[ "Lima ", "Sao Paulo "\]\]
**Output:** "Sao Paulo "
**Explanation:** Starting at "London " city you will reach "Sao Paulo " city which is the destination city. Your trip consist of: "London " -> "New York " -> "Lima " -> "Sao Paulo ".
**Example 2:**
**Input:** paths = \[\[ "B ", "C "\],\[ "D ", "B "\],\[ "C ", "A "\]\]
**Output:** "A "
**Explanation:** All possible trips are:
"D " -> "B " -> "C " -> "A ".
"B " -> "C " -> "A ".
"C " -> "A ".
"A ".
Clearly the destination city is "A ".
**Example 3:**
**Input:** paths = \[\[ "A ", "Z "\]\]
**Output:** "Z "
**Constraints:**
* `1 <= paths.length <= 100`
* `paths[i].length == 2`
* `1 <= cityAi.length, cityBi.length <= 10`
* `cityAi != cityBi`
* All strings consist of lowercase and uppercase English letters and the space character.
|
Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly.
|
Array,Hash Table,Breadth-First Search,Sorting
|
Medium
| null |
931 |
what's up everyone today we're gonna be going over Lea code 931 minimum path falling and the input is a 2d grid and the output is going to be one integer and what they want is to find the minimum path from the top any of the columns to get to the bottom and what we can do is go either straight down or left or right at most 1 so from 2 we can go to 6 or 5 or 4 from 3 we can go to 6 or 5 excuse me so of course we can't go out of bounds now the way I solve this one was to use a 2d grid of DP I'm gonna populate my 2d grid and then at the end I'm going to return the minimum number in the last row of my DP array so this is also going to be 2d grid now the first thing is to go layer by layer because each spot is has a dag dependency on its predecessor except the base case is going to be just this row itself because that's the minimum cost to just to get to the first row now the way I handled the edge cases was if an index is on the edge if a number is on the edge then it's just gonna get its upper and upper right our upper and upper left otherwise it's gonna get DP from the previous 3 so let's get into the code so int M is gonna be in grid the length int n is gonna be grid of 0 and length this is just the height and width and then in DP is new int MN and I'm gonna initialize for int I is equal to 0 I is less than n I plus DP of 0 of I is it gonna be set to let's call it grid of 0 and I this is just the base case so that one this piece of code is gonna fill up this line now let's get into the meat of it okay let's get into the movement now we have the for int I equals 1 is less than grid well we already have it so and I plus 4 into J is equal to 0 J is less than n J plus if J is equal to 0 which means if I'm currently on this one it's going to be DP is going to be the minimum of these 2 plus itself DP of I of J is going to be a grid of I of J plus math dot min of DP of I minus 1 oh no yeah I minus 1 in J comma and DP of I minus 1 J plus 1 what this means is this guy is going to be 4 plus either 1 or 4 plus 2 this guy is gonna be 5 if else if J is equal to n minus 1 DP of I of J isn't gonna be grid of IJ plus math dot min DP of I minus 1 and J or DP of I minus 1 J minus 1 that's for this case so this one is going to be either 6 plus 2 or 6 plus 3 that's gonna be 8 now when we come here all we have to do is write else L so DP of IJ is it going to be a grid of i of j plus math dot min of the three things above it plus itself so it's gonna be the 5 plus 1 plus 2 it 3 it's gonna be sick DP of I minus one J comma DP of I minus one J minus 1 comma DP of I minus one J plus 1 I know this isn't there's no math dot min which takes three but you get the idea so now once everything is filled out so seven is gonna be seven plus five or seven plus six it's gonna be twelve eight is gonna be either eight plus five or eight plus six or eight plus eight u plus five and then nine is gonna become either 9 plus 6 or 9 plus 8 and 9 plus 6 is 15 and then we're gonna return 12 because it's the lowest number on the bottom row which is the output so that's how I saw the code 9 31 if you liked this video please like it and subscribe you and let me know what you're thinking the comments below it'll motivate me to make some more thanks
|
Minimum Falling Path Sum
|
maximum-frequency-stack
|
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`.
**Example 1:**
**Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\]
**Output:** 13
**Explanation:** There are two falling paths with a minimum sum as shown.
**Example 2:**
**Input:** matrix = \[\[-19,57\],\[-40,-5\]\]
**Output:** -59
**Explanation:** The falling path with a minimum sum is shown.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 100`
* `-100 <= matrix[i][j] <= 100`
| null |
Hash Table,Stack,Design,Ordered Set
|
Hard
| null |
947 |
all right so let's talk about the most stones removed with the same rule or column so you're given to the array and then you have to either remove the stone if they have the same rule or the same column so this is a 2d plane i'm going to just draw the diagram and then these are all positive right so i'll just give you a hint so let me just quickly draw the uh coordinate so zero it should be right here right zero one should be right here one zero should be right here right one two should be right here and what else two one should be right here right two should be right here right so if you notice um this is pretty straightforward why like uh there are how many stones six stones and based on this right there is a connection for sure like they are in the same uh same row or same color right so basically you can just what you can just draw uh draw a look uh connection so if you can connect every single stone with each other and then you will know okay this is the connection which is uh one connection in this 2d array so you just subtract one which is five so which means you have to remove five stones so if you don't believe it right all right move on the next one so this is gonna be 2d plan zero 1 2 something like this right and this is three right okay i'm going to just draw the that one so zero right zero two right one right here two zero right here right and then two should be right here right so uh based on this right uh how many connections you have you should have two connections why this is one connection right this is one connection and this is another connection itself so you have two connections so how many stone you have one two three four five minus two connection which is what three so this is three so how do you use the connection so if you know the union fine right and then you will be able to understand really quickly so i'm going to just uh write down my union file and then you would just follow along because the union find shouldn't be too difficult to write and i'm going to explain why i'm doing this so for the union 5 i'm going to have an array and basically i'm going to just point my stone for every stone to myself so if i have a six stone right so i'm going to point every single stone to myself then later on later i will just update my current stone with another guy right with another stones so i'm going to say in the rate i'm going to say notes right and i definitely need a size i'm going to talk about the size later so probably uf i need to pass in the plus in the end right you know and i'm going to just initialize my size to go to earn and also initial my what uh in array right and then again i need to point my every single uh stone to myself right so it's gonna be one no say i equal to i okay so this is initialized right so for the union fund you need to union so right so it's probably avoid union and you have the union to stone i'm going to call a and b right so uh if you want to union a and b then basically you need to find the current root for the current term a and any current b right so you need a fine function so probably in i'm gonna because you have to return some number right so i'm gonna say ins probably i would say roots right so uh well uh if you can cannot find the parent of the roots it's not equal to is equal to a root then you have to keep going up this is like free and then you want to keep finding who is your parent and then if you can find it then you need to update your uh no route to node this is what if you find your folder just for example you need to find your green folder and then you need to update what you need to update your route to your father so you will keep finding your ancestor and then this is going to be pretty much it right so you just have to return it and then again back to union so we have to y we have to find root a equal to finally a right find a and then root b equal to finally b right so i can just checking if root a uh is not equal to b so which means they are at a different uh different connection right now so i need to connect together right so using the notes and root a i will say the root a to the ruby so i will connect the root a to a loop b so uh this is going to be pretty much it right so by the full size how do i know like um the number of the connection they have right so if they connect together right i'm gonna decrement my size right uh this is gonna be pretty much it because if you connect together right you don't need another extra uh note right so this is pretty much it so i at the end i just want to have a return value for the in so probably public in size i'm going to just return size right so how do you actually write your main function remove stone so you just have to check while you check the first index with another first index second index with another second index and then so on right so i'm going to say in equal to one so that stone.length right stone.length right stone.length right and then what else uh and then initial my uf union fine right new uf harmony and right you have installed right and then for in i equal to zero right i listen and i plus and then my second value is going to be what j equal to i plus one and then j less than j plus so i need to traverse every single uh strong with another stones so it's gonna be what that's for in this case now i need to pull out my stone one i'm gonna say a equal to one a equal to strong stone say i and then b equal to strong j and again this is an array right stone is 2d all right so if i pull out one element so it's going to be 1d array all right so just making sure and then i'm going to just say if the index a0 is equal to e0 right order a y is equal to b one right i can what i can connect my uf union to what i and j right so i don't care about the actual value in the stone i'm careful of the index because the index is also represent the stones right so at the end and yeah i just want to return the total stone minus the connection um in the union fine right so this will give you the solution so let me run it and then hopefully i don't make mistakes and it looks like i over time all right so i found out my mistakes so which is right over here you don't want your current route is equal to your parent uh so you have to say if they are not the same right you want to keep going up and then you up you want to update your current uh note and this is going to be pretty much it right so uh back to here so yeah pass the test so just making sure you know the union fine i mean i made a typo right here so you want to find out your current uh current node in the union file with your parent and then basically you just want to find your the ancestor for sure so this is going to be the exponential so let's talk about the time in space this is going to be what this is going to be time this is all of un this is all open so it's n square and in the union fine which is what you basically use what laven right basically but i would just i'll i would just say logan and then this is a square times logan and this might be shorter but the worst case will be longer and yeah so let's hope let's talk about the space this is space and the space is going to be the number of stones depending on n so uh this is all of n for the space and then and square log for the time and this is the solution i'll see you next time bye
|
Most Stones Removed with Same Row or Column
|
online-election
|
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone.
A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed.
Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_.
**Example 1:**
**Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 5
**Explanation:** One way to remove 5 stones is as follows:
1. Remove stone \[2,2\] because it shares the same row as \[2,1\].
2. Remove stone \[2,1\] because it shares the same column as \[0,1\].
3. Remove stone \[1,2\] because it shares the same row as \[1,0\].
4. Remove stone \[1,0\] because it shares the same column as \[0,0\].
5. Remove stone \[0,1\] because it shares the same row as \[0,0\].
Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane.
**Example 2:**
**Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\]
**Output:** 3
**Explanation:** One way to make 3 moves is as follows:
1. Remove stone \[2,2\] because it shares the same row as \[2,0\].
2. Remove stone \[2,0\] because it shares the same column as \[0,0\].
3. Remove stone \[0,2\] because it shares the same row as \[0,0\].
Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane.
**Example 3:**
**Input:** stones = \[\[0,0\]\]
**Output:** 0
**Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it.
**Constraints:**
* `1 <= stones.length <= 1000`
* `0 <= xi, yi <= 104`
* No two stones are at the same coordinate point.
| null |
Array,Hash Table,Binary Search,Design
|
Medium
|
1483
|
1,602 |
hey everybody this is Larry this is me just doing a bonus premium uh question I haven't done one in a couple of whatever so uh let's do a medium one that I haven't done before and yeah let's go ing give me some good OMG and yeah uh find nearest write note in binary tree is today's uh um 1602. come in the wood of a binary tree and a no Jew in the in a tree new return the newest node in the same level that's to the right of you or returned overview is the right most note in this level um I mean I don't mean this is that bad um I think the Curious thing is just about you know what is the complexity we're gonna give you but like everyone just do something linear time in your space this is relatively trivial um can I do a little bit better return the node do you turn the note okay or none if not um yeah man I don't know I mean I yeah I guess so yeah I mean if we do it in order traversal it's gonna be the next note so I guess in that case it's gonna be all of end time of H space where H is the um uh height of the tree so um so yeah let's do that and then we'll go and then we'll just go traversal and this is an in order traversal um of node and maybe even level away and then maybe we just have one that's like um like a found variable that's none right um and basically we just maybe even just something like next one is the other Force basically the idea is that when we're at this level um that we're looking for oh no oh yeah um I mean but the idea is still the same I mean I have to figure out how I want to code it but it's that when you see well one is that you're trying to find a node and then after you find this node the next one is going on this same level it's going to be the one that is the answer is the idea um so yeah so maybe I could even abuse it's next node level um naming is hot Next Level node is you go to I don't know say negative one right um doesn't really matter but yeah so oops so no there's none we just return otherwise uh we want traversal I guess traverses to work uh no dot left level plus one Traverse know that right level plus one technically I guess we want to do it in order though in order doesn't really matter I don't think well either way it doesn't really matter actually any of the traverses don't really matter because it's the level dependent anyway but in any case so if node uh is equal to U then next level node is to go to level uh yeah maybe a little bit earlier because we're gonna do some other stuff but also something like if next level node is you go to level then non-local found as you go to this non-local found as you go to this non-local found as you go to this current node and then you can return um we could just return it from everything really but uh yeah so maybe we can just do if found then we return as well um so I guess technically we still mess up if you kind of go up if you return from here and then it just goes to here so maybe I just do something like um yeah let's just do something like next level node is back to negative one again or something silly this is just silly uh yeah and then we return fan and this should be mostly yet unless I missed the state uh in my head or something like this uh yeah and let's give a quick submit ah cool worked on the first try doesn't feel like that happens very often with me these days but yeah um this is gonna be as I said linear time because you have to look at every node in the worst case it you know there's really no way around it uh of each space where H is the height of the tree also no way around it but other than those two things we only have two extra wearables right the idea is that if we keep them varying that we're using uh actually any of the traversals like we said I believe um yeah we use any traversals meaning in order pre-order or post order pre-order or post order pre-order or post order um as long as left goes before right really then um then yeah you then this should be good um yeah and this is the lower Bound for that anyway that's all I have with this one let me know what you think uh yeah stay good stay healthy do good mental health I'll see y'all later and take care 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 |
160 |
hi everyone welcome to the loophead today in this video we will be solving june deep code challenge and the question for today is intersection of two linked list the question is easy tagged and it states that given the heads of two singly linked list had a and had b return the node at which the two lists intersect if the two linked lists have no intersection at all return null for example the following two linked lists begin to intersect at node 7. the test cases are generated such that there are no cycles anywhere in the entire link structure note that the linked list must retain their original structure after the function returns okay so here what we have to do is we need to return the intersection point or the intersection node at which both the linked lists that we are given are intersecting so in this case we have a1 a2 c1 c2 c3 and b1 b2 b3 c1 c2 c3 and these both linked lists are intersecting at c1 similarly in the next example we have four one eight four five and five six one eight four as the two different linked list and they are intersecting at eight four five so we just have to return the height of this node that is uh return the node as head from where the intersection begins so in this case we will have to return eight so these are intersected at eight now next we have this one nine one two four and three two four so these both intersect at the node two so our output is intersected at two now next we have these links since three two six four and one five have no common point of intersection does we'll return no intersection over here so these were the examples um this is how what we need to do over here that is we have to return the intersection point of the two linked list how would we approach this problem the first approach would be uh to keep two pointers and start traveling each linked list but in that case uh what will happen is we will never encounter a situation where both pointer would be intersecting in such cases because the length of linked list is different so what we will do is we will just equalize the length and since in this case uh the length of first link list is five and the length of second one is six so the difference is one so we just move the pointer of the large linked list by one and now you can see they are parallel they'll start parallely and move until they encounter uh a node which has equal data so um it'll start here and it will move this way and once it reaches over four it is gonna sorry it is just gonna return this so this is what will be happening in our naive approach but we can do better than this uh instead of just subtracting the number of extra nodes what we'll do is we'll just start from the first node of each linked list itself and we'll just start moving one at a time let me just help you visualize the same so um initially our pointers will be at the head of the um each linked list so the first pointer is that head of the first link is the smaller one and the second pointer is like the head of the uh second linguist and we'll just start traveling and this will be moving one by one and once the first pointer is at the last node of the first link this it's position will be the next position would be the height of another link that is now it will be pointing at the head of the second list and uh now once the second pointer reaches the um last note for the second english it will now start pointing at the height of the first link now you can see that the lengths are managed and now they will be traveling equal number of iterations and would be encountering the same node and returning so this is what is going to happen so let me just drive you through the board okay so the first case would be when any of the linked list is empty in that case there would be no intersection that's wheel return minus one so if head a equal to none or head b equal to none in that case we would simply return -1 in that case we would simply return -1 in that case we would simply return -1 so next we will be having two pointers that is l1 comma l2 which is equal to head a and head b that is the heads of each linked list initially until l1 and l2 are not equal that is until they do not encounter an equal node we are just going to iterate them so um in case where l1 reaches the last node of the first linked list we are just gonna point the pointer l1 to the head of the next linked list that is head b otherwise we are simply going to shift l1 to l1 dot next that is the next node and similarly for l2 if we encounter the last node of the second linked list by the pointer l2 we are just gonna um update our pointers position to head of the first linked list otherwise we are just going to update it to the next node so l2 is equals to l2 dot next and we will simply return the node where the um where both the pointers intersected so it can be either l1 or l2 i'm just gonna write l1 over here and let us see whether it is accepted or not if there is no error so yeah it is accepted and let us try to submit this code and see whether this works or not and i think yeah it does let me just yeah so it was accepted and now so this was our sixth day history if you like this video make sure to hit the like button share with your friends subscribe to my channel until next video stay tuned thank you bye
|
Intersection of Two Linked Lists
|
intersection-of-two-linked-lists
|
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
For example, the following two linked lists begin to intersect at node `c1`:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
**Note** that the linked lists must **retain their original structure** after the function returns.
**Custom Judge:**
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
* `listA` - The first linked list.
* `listB` - The second linked list.
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
**Example 1:**
**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
**Example 2:**
**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
**Example 3:**
**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
**Constraints:**
* The number of nodes of `listA` is in the `m`.
* The number of nodes of `listB` is in the `n`.
* `1 <= m, n <= 3 * 104`
* `1 <= Node.val <= 105`
* `0 <= skipA < m`
* `0 <= skipB < n`
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
599
|
1,748 |
Hello, we are together again in another toast, today's last isamu. Friends, we are given an intelligere series with Yürek elements, and in it, Yürük elements with Unique elements. He mentioned that there are numbers that are seen only once in the series, and in this series, friends, are there all the numbers that are seen only once? We are asked to rotate it. If we look at it is given as one, two, three, two. The elements that are seen only once in this series are 1 and 3. Since the elements that are seen only once are 1 and 3, the sum of them, 4, is frozen. If we look at it, Friends, it is knitted in this series. It is seen only once. There is no element, so the remaining number is 0. Yes, now if we look at the second one, here it is 12345. All the elements are seen once, since the sum of all of them is 15, it returned the value 15 to us. Here, friends, as you will immediately notice, the first thing we need to do is how many numbers are in this series. So being the frequency is already the simplest logic in this, a dictionary. So it's a feeling to always create the logic and in this vertical city and as the governor, we need to keep the element itself in the Governor room, how many times the element is seen in this array. Then again, never iterate within this dictionary. If the elements are yusub, that is, which elements appear only once, it will be enough for me to sum them to the ground. For this, I create a dictionnaire, where intelligere integers tivolis, and I also created a variable in the form of Sam equals o, which is added up a little, then there are friends. Here it is less than zero, pointless point, lighty Plus, it is iterating through all the elements, we got on together, Şerif in my teeth. More precisely, I iterated at that moment. If there is an element, I know the name of it. If there are two, do not increase the value of this element by 1. If it is not there, friends, I am adding that element to the one I have now. Gamze Via V1 I added one as the number of times it was seen as I saw this element for the first time. Then, Friends, I now have my teeth in my teeth. I kept track of each element and the frequency of each element, that is, how many times it was mentioned in this series. Then, by scanning the contents of this dictionary, I actually scanned which thing's value was. If it is one of them, that is, if it appeared once in the series, will ten extractions be enough? Look, there are 3A, persona teeth, by making an iteration in the form of We, something, two things, if your partner is one, it means that this element is mentioned for me. That is, it has been seen once in the original name. So I'm going to plus it equals and this Forest then friends, I 'm going to be returning a variable, well, I'm going to give it a 10. 'm going to be returning a variable, well, I'm going to give it a 10. 'm going to be returning a variable, well, I'm going to give it a 10. Our code is here, the success form of the screen is there, now we can submit our code. I also say the screen in 96 milliseconds and all si people's salary is twenty-nine percent faster than this. We have twenty-nine percent faster than this. We have twenty-nine percent faster than this. We have worked in a way. Because friends, the basic logic here is actually in our data structure. This usually happens all the time. Because there is a data in the form of this is always used as a stitch, so we will do something, each element in a dictionary and how many apples are in the array. First of all, I keep the information that it has passed many times. Then, it travels through this stitch and that other one. I mean, it takes the elements that appear once in my original Array and returns their sum. Here, friends, that's all I have to say about this question. See you in the next video. Goodbye. stay ya
|
Sum of Unique Elements
|
best-team-with-no-conflicts
|
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array.
Return _the **sum** of all the unique elements of_ `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,2\]
**Output:** 4
**Explanation:** The unique elements are \[1,3\], and the sum is 4.
**Example 2:**
**Input:** nums = \[1,1,1,1,1\]
**Output:** 0
**Explanation:** There are no unique elements, and the sum is 0.
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 15
**Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
|
Array,Dynamic Programming,Sorting
|
Medium
| null |
950 |
hey everybody this is larry this is me doing an extra problem uh on the code daily challenges august 10 or uh on 2020. so yeah let's kind of do it to do one that we haven't done before and let's see sometimes i get a premium one okay that's good uh hit the like button hit a subscriber and join me on discord especially if you like these bonus questions and let me know in the comments so that i could keep doing them i might stop it at a certain point but you know if you if enough people you know keep it alive then maybe i'll do keep doing extra problems anyway today's problem is reveal cards in increasing order so you're given an industry away deck there's a deck of cards where every card has a unique integer and it is decks of eye you can order the deck in any way in any order you want and all the cards are faced down initially like the top card of the deck we will take it out of the deck uh if there are still costs we can pick the next card and put in go back to step one stop what i don't know that i understand what's going on here okay so you take the top card of the deck reveal it put it off the deck if there's still cards in the deck then put the next top card down at the bottom of the deck just still and we will go back to step one otherwise stop okay so we can disorder after some reordering we get we view two and then move to the thirteen to bottom three eleven to the bottom okay um so basically you want so you have this algorithm and you want to reorder this stack such that this is the case okay um i think what i would do is just do a simulation and then get the original numbers that way right what i mean by that is that okay so okay i think the first thing we should do is just simulation and this is going to take um o of n time uh even though n is only 1000 anyway so it's fine but because the idea here is that um every time you reveal or every loop we will have to call it so then you get this recurrence of o of n then m over two and then n over four dot so it'll be o of n in the number of reviews anyway i mean it has to be because that's the number of cards but also in terms of iteration because that's fine so yeah um and after that we'll get the order of uh the deck of cards and how things reveal that we can map it to the initial deck so let's do it um first we will sort because we the input order doesn't really matter it seems like because we're gonna we could reorder it anyway but then now we want to say um let's say n is equal to length of deck and then we want to say uh maybe a shorter deck is to go to uh let's just select the egg and then maybe i for i in range of n right i think this has to be a list um yeah and then now we just do the simulation right um and then here we go maybe lookup is what we call it and then now we do the simulation which is that while link of s dec is greater than zero um we do uh top is equal to s dec dot pop left right and then look up of top is you go to like current or something right so this is like the index maybe t for time you want to say okay fine let's do t for time so t is equal to zero and then yeah and then we increment one at the very end and then of course we have to do another we will do the next number and then we put it into the bottom right at the end again this is basically step two okay so then this now we should have you know let's take a look right so we ran it for the first case it has seven numbers so yeah so now we have an output here and yeah so that means that the smallest number should be at zero and then the second smallest number here and then 2 3 you know and so forth right so that's basically the idea so that means that our answer is equal to uh let's see uh look up of uh i'm trying to do it in one line maybe i shouldn't but that's okay uh so that means that the i smallest number in deck so the lookup so yeah ends no i think that's because i did it in a weird way so yeah so what i want is for i in range of n say right um then answer of lookup sub i is equal to uh deck of i think that's good um basically it's saying okay so yeah this is the look up we got we want the smallest i think i did it the other way yeah i think i did it the other way whoops okay then i guess this could have been one liner okay yeah basically the i've number of the answer is going to be the original you know x number and now actually now did i see it i guess we could have just you know done it in a one-liner it in a one-liner it in a one-liner but yeah because i forget which or i couldn't visualize in my head um which way uh it which um just like yeah i have to sign it now and visualize it so yeah okay i get the classic you have to attempt to one code too quickly so give me a second i just want to run at least for the input so that looks good so let's give it a submit cool um it's a little bit slower than others but uh it's going to be n log n for the sorting and i think that's most of the work um you probably could reason out the logic but i feel like you know you would have to prove it like i said this is so other than the sorting this is going to be linear time and yeah and then your space because you know we do a lot of linear spacing i don't think they have to explain that so yeah um that's all i have for this one let me know what you think stay good stay healthy to good mental health i'll see y'all later and take care bye
|
Reveal Cards In Increasing Order
|
x-of-a-kind-in-a-deck-of-cards
|
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`.
You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.
You will do the following steps repeatedly until all cards are revealed:
1. Take the top card of the deck, reveal it, and take it out of the deck.
2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.
3. If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return _an ordering of the deck that would reveal the cards in increasing order_.
**Note** that the first entry in the answer is considered to be the top of the deck.
**Example 1:**
**Input:** deck = \[17,13,11,2,3,5,7\]
**Output:** \[2,13,3,11,5,17,7\]
**Explanation:**
We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it.
After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\].
We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\].
We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\].
We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\].
We reveal 11, and move 17 to the bottom. The deck is now \[13,17\].
We reveal 13, and move 17 to the bottom. The deck is now \[17\].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
**Example 2:**
**Input:** deck = \[1,1000\]
**Output:** \[1,1000\]
**Constraints:**
* `1 <= deck.length <= 1000`
* `1 <= deck[i] <= 106`
* All the values of `deck` are **unique**.
| null |
Array,Hash Table,Math,Counting,Number Theory
|
Easy
| null |
83 |
hey people so today we are going to discuss lead code problem remove duplicates from sorted list so in this program we are given a head of sorted linked list and we have to delete all the duplicate nodes that are present in the given linked list and we have to return the linked list in the sorted form so if I have to give you an example like if there is a linked list which has notes one and two since one is repeating twice we have to remit remove this node and this link as well and we have to return the remaining nodes in the form of linked list okay so that's the whole problem is all about if this is the link list that we have one way of dealing with it is to completely Traverse through entire linked list and copy all the numbers that we have into a list okay and we'll be after the traversal of the linked list we'll be getting a list of values one and then you convert this into a set of values if you perform set operation on this you will be getting set of uh one and two and you again convert it into list and it will be 1 and 2 and now you Traverse through this entire list one element after the other and you create a linked list out of it and return its head then it will be one which is pointed to 2 and you return this head okay so this is one process okay so for this like since you are using this extra space and you are traversing to the entire linked list twice so the time complexity would be order of n for traversing throughout the list two times and the space complexity would also be order of n since you are using extra space for set and list okay and also for the linked list in the final step so this is not an effective solution this is just a Brute Force solution now we have to move towards an updated and optimized solution uh let's see how we deal with this problem so in these kind of problems we generally use a concept called two pointer concept which is quite popular technique in linked list problems and let me explain you how so in this kind of problems we'll be using two pointers let's say first here and a second pointer and we are using these two pointers and we are trying to modify the linked list with these two pointers according to our problem requirements so that's the approach that we are going to follow in for this problem and let me explain you how we'll be having two pointers let's just say first and second pointers and these will be pointing to head okay uh let's see this is the head pointer and first will be pointing to head pointer and for a second pointer would be pointing to head dot next pointer okay and what we are trying to do is we are going to iterate through this entire linked list and we'll check if the first Pointer's value and the second pointers value are same or not if it is same then we are going to remove the second node and we are going to update it with the second dot next so our second node will be pointing to this node now and our first notes next value we are going to link it to the second node Okay so if I have to show you the updated linked list then it will look something like this so this is our first node this is our second node and this is the new link up so let's just say if we have one more node which has a two value here then we are going to have we are going to iterate this through the entire Loop right entire linked list right so now we are going to increment our first and second notes because we have just uh got done with the upgradation of the linked list right we are going to increment it so our first and second notes will now look like something like this so this will be our first node and this will be our second node okay once we have updated these first and second notes we'll be checking again whether our first values are same or not first dot value and second dot value are same or not if so we'll be doing the same step again we as I've just mentioned Okay so as second doesn't have any value it will be pointing to null so I'll be updating my second to null that is second will be coming here and I'll be updating my first dot next with the current second value and I am removing the these node okay so it will look something like this right so this is going to be our updated linked list so this is the whole problem and let's get to the code part first so if you look at the code this is the first and second pointers that we have uh initially initiated with head and head dot next as I've mentioned and this is the base condition that is if we do not have either one node or either two nodes let's just say if we just have a single node that is one and or else we don't have any linked list then we have to Simply return these whatever that is present right either if we have only one node we have to return on only that node if we don't have any nodes in our link list we have to just return this empty linked list right so that's what this step is doing and once that is done this is the traversal part that I was talking about so while we have both first and second notes we are going to check if we have first node and we have second node and if our first node dot value is equals to Second node dot value which is in this case as I've just mentioned if both the values are same then what we are going to do is we are going to update our first dot next with second dot next that is this node we are going to update the next value of first node with the second dot next value and we are updating our second node with the second node dot next which will be looking something like this and this process keeps happening until we have both first node and second node and both these values are same so once this is done this while loop is getting executed and getting out of it and we'll be checking if we have both first and second node then we have to iterate right let's just say if we don't have this step or else let's say if we have something like 1 and 2. right and our first pointer is pointing to this node and the second pointer is pointing to this node then after getting into this while loop we have to move forward right because at every iteration we are moving one step closer to the right end of the linked list right so that's our Aim so at our first step we have to move here our first pointer should move here and second pointer should move here and similarly one step by step we have to move towards the end of the linked list right so for that step this is the incrementation part once this Loop gets executed we'll be left with the sorted list which does not have any duplicate nodes okay so this will be our final link list that we'll be getting uh after this Loop gets executed and so we are just returning the head of the linked list so that's the problem guys and the time complexity for this would be order of n since we are traversing through the entire linked list and the space complexity remains order of 1 since we are just taking two uh constant variables first and second so this is a pretty optimized solution rather than the um compared to the Brute Force solution since we have optimized the space complexity here and yeah that's it for this video so if you like this video please like comment and subscribe to my channel that keeps me motivated to make more videos thank you
|
Remove Duplicates from Sorted List
|
remove-duplicates-from-sorted-list
|
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List
|
Easy
|
82,1982
|
956 |
Hai Gas Welcome To Me YouTube Video Today We Are Going To Solve That Daily Leaders Challenge And Today's Problem Name It Tallest Billboard So The Problem Statement Date You Are Installing A Billboard And You Want It You Have The Largest Miss Of Equal Height Okay You Example on collection of roads date content d date can be valid together if you have roads of length one two and three you can also give two yards date you make a port of length six so return d is largest then its length being equal Tell me equal keeps us and they have you maximum D length now we can see further condition how to do what can we do some roads jeevan hai bhai jinko belt kar one pillar of length 6 and I have an one braid of lance it can Act this date bill have 2 pillars I have stable of 66 length how is it ok I have rods done I belt them and guide 4 and 6 done so I bill connect d maximum length of d pillars available that would be by the way I am maximum We have to tell the length, what do we have to do in the question, okay, so I put it on road number 2 again, pillar number, you ca n't do it in the first example and 6 right, now see, I will do it, now let's check, so initially I have one, okay so. If I do it in constructing it, I will have it. Either if I do it in constructing the road available, then it will be OnePlus. Pillar is still there, its pillar is still zero. If I do it in constructing it, then it will be pillar. P will be the length, it will be done or I should not make it the road, so I bill get D to right, then after that comes to me road number three whose length is pillar number zero on D. Last road date is off length to six. If I do it, then I will have the value. If the line of play tu will remain zero, if I do it while constructing the pillar, then the length of play tu will also be there, then the length will have to be checked by doing bill by region. Right, then I have the time which is sorry for me. Pass is the maximum length possible. Look, the notes will reach zero. Clear the maximum possible. Remain. Give the bill. Change the note. Whoever can give it here. There were three zeros here too. Three zeros here too. If this thing has not happened then what is the length of pillar one. It was already ready, in that I will have to increment the road of ID, if I ID speaker completely, the function which is completely executed, after that I will have the final answer start in the answer variable and I can return time, then we will get the value of N in the question, write time complexity and We see this thing okay, here is power of 3 using dynamic programming date is from zero you and value of n is 20 we have seen so index will be zero near me length will be one will be sum of d date is d length of me pillar One so pillar sum of which d values of main roads should be the which d values of main roads should be the which d values of main roads should be the maximum power, how can I have the maximum value, I have power up to max player 5000, now let us see this thing which will become DP, I will also have it from here 0 You write 5000 of 20 and I can reduce it by 20 * 10. You power three or four. If this time 20 * 10. You power three or four. If this time 20 * 10. You power three or four. If this time complexity is acceptable then it is acceptable. Okay, so let's see what is happening. Okay, how do you have 123 and 6 first? Increment the length of the Road One which is Sorry Roads of Intex Mobile. I have added it right. It is still there, I have done it right. So, when does the new difference come to me, when I add the Road of ID to Pillar One. Okay, if I add to my first true, zero minus one is equal to -1, see virus, if I add lens one minus, then my new distance will be equal to the previous distance - Road of previous distance - Road of previous distance - Road of IDFC, the reason for that is previous displacement. Zero new displacement ki jo length wo tha let way want-1 ki jo length wo tha let way want-1 ki jo length wo tha let way want-1 If I don't do anything then my distance today it will be this if I add road to it filler one made na pillar you made what will happen next I have a road, let's check this also, if I have a road in the previous road, if I add in the road pillar, then the length of the road will also be the previous distance, so 3 + 3 = 6, if I add in the road, you. so 3 + 3 = 6, if I add in the road, you. so 3 + 3 = 6, if I add in the road, you. I give sorry pillar tu add kar da ho road of length will be that will be the previous dismissed - note length and 3 - 3 0 If I dismissed - note length and 3 - 3 0 If I dismissed - note length and 3 - 3 0 If I don't do anything then distance is life again I will be having six plus zero represents me if I By following this combination, the thing that is doing zero percent here is that if I go here, then I will get the difference between the lines of pillar, whatever you get, it will be zero, it means this combination. Through this, the lens that I am getting is equal, right of D is being given to both the appellants, so if the length is equal then now I have valid candidate but D is the answer. Now I have to check whether this is maximum and note if this is maximum then This will be the answer, okay, we have understood this thing, now let's see the difference, from this difference we can find the final length of the length that I have, just by difference, let's see this is my distance from here to here. This is the thing that I will do as director, pillar you, what difference will be zero, it will return through it, the answer I will return will be what is it, D sum of I pillar, length of me pillar one and play, you will find the difference between D. Length of pillar and pillar tu is zero ok, similarly this part which will be difference between d length return is ok so these which I will handle now from minus infinity I will show you the time of code zero so I have understood that this is me What is he giving by returning coming D and even is giving by returning and lens you are right P is equal we have capital L K so this will be even, 12 of 12 will be right so these five who will return all to me will be fine. Well, let's see here, zero indicates zero and what was the option that I had added six side here, then I have zero displacement. Okay, what was the difference here, three distance was six. When I added six, then I have If I got zero, I had added six to it, meaning in any out of one of the pillars, I had added 6. From here, the length I will get, how much will I get, equal to six, because although you had made my six a pillar, So, what will be the time and what should I add and the time must have been incremented, right, here six will return three, but I will have time, 9 was returned, if I add more to it, then I will get 11, here I have added one. I did it right in pillar one, so I will add one more here, my total degating is this well, so if I have the value of sum is 12, then how much lens will be equal to 12/26, then the maximum length I will get 12/26, then the maximum length I will get 12/26, then the maximum length I will get or whatever I can freelance. So through this particular combination of D roads, I will get 6 and we can also set that I am getting equal to six, both roads are equal to 60, you and the one who will be even will be 6 12, we are getting 12 days. Okay, so we have to find it like this, I got 12 from here and from this pass, when I expand it through the net, I got 14 from here, what does it tell you? So it is saying that if you do not do the first floor, then I will give you something else. A valid combination will be found from where both will be equal for plus their head I am getting 14 so 14 / 2 is 7 right so I will get seven so 14 / 2 is 7 right so I will get seven so 14 / 2 is 7 right so I will get seven what will I get seven represents the length of the pillars through this part I am getting maximum If so, then I will dispatch it to me. Obviously, returns were being received from this one, and I will return the final answer from this one. Okay, so first I will do the maximum, then I will divide it with you. If I get it then I will get the answer. What am I doing? Like here there was index from zero, here was first index, second India, in the middle of third test, like here there was one, I will do three. After that see if the difference I have is zero. It happens like in this particular, how is it a valid one, how am I returning zero in the base condition, here there will be 6 returns, do not get confused by this because actually returning zero is fine and the length of the road is 0 + 6 = 6 so the length of the road is 0 + 6 = 6 so the length of the road is 0 + 6 = 6 so the return from here is 6. Why am I making it zero? Okay, so here I have the value of difference is zero, so I am making the return to us as zero. This is the best condition. If it is not zero then I am a very I am doing minimum value and return, why am I doing this for all this? Look, I will do this statement here, I will get six from here, I was getting 12, okay, but what do I do in 12, which is zero here. Through zero, here too I make a minus infinity value, here also there was a six, so I make a minus infinity here too, then - make a minus infinity here too, then - make a minus infinity here too, then - infinity plus value will be minus infinity here, if it is ok then six - infinity will be minus infinity here, if it is ok then six - infinity will be minus infinity here, if it is ok then six - infinity - infinity will remain, then minus infinity. - infinity will remain, then minus infinity. - infinity will remain, then minus infinity. Which will be the maximum of six and minus infinity, which will be six, so from here I will finally return six, so this is D way, you neglect these non-zero values. Okay, non-zero values. Okay, non-zero values. Okay, I will return a very negative value that if it is very big, then this How in our constant is possible only up to 5000, it will be a very big value, so they can make it this - 10 very big value, so they can make it this - 10 very big value, so they can make it this - 10 you power five in place of infinity, don't fox it now, we will see it later in the members' time, will see it later in the members' time, will see it later in the members' time, further how we have three, either my There are three things, either I leave it today, do n't use it on the road, then the distance from the previous distance will also be passed to me here, just the index will be incremented, so what was the other way for me through this? What do I say in Road One? It will be the new lens. It will be the number one plus road fighting. What formula I had, it was the description. I added Road of Id in it. This will be my new design next. I will go on and Rhodes you had to pass me then I know what it is returning it will return me what is the maximum possible from D Sindhu plus one to D last index which I have Current difference is equal to difference plus product And what I have got, I am returning it here, so in this we have given me till now but an index it, what am I doing in this, I am adding it in Road One, if I add it in Road One, then it is in front here. It was discussed that if I add the value in Road Tu, I have the value of Road of Idli, if I add Inspector's key and one bed, I have the result, the answer which was returned from here, six will be added in it, then 6 will be returned from here. Look here, you will understand that it is 6 liters from here, okay if I explain to you, there were 6 returns from here, so I must have returned six, this part has added and done, so I will not go from here. Here the answer will be two, 3 from here a and six from here the total will become nine from this thing I am late doing here if I give my pass the previous distance value we told not to return the maximum and maximum of d sum of d So the d three parts that I have got, so the maximum answer's one will return one aam tu coma three, then its power of time will still be n. The dynamic parameter in this, we have a function, so the index of is two. So there is always some print, okay what is the range of English 020, what can be the difference after that, see, I am also changing the distance once to 0 - √86, I had the also changing the distance once to 0 - √86, I had the also changing the distance once to 0 - √86, I had the previous difference from late, now I have If I mined it, then first Road of Example 1 had become -1, then Example 1 had become -1, then Example 1 had become -1, then after that, every next D, how would I have made mine - 2, after that, every next D, how would I have made mine - 2, after that, every next D, how would I have made mine - 2, then -3, if -3 had become -3, then -3, if -3 had become -3, then -3, if -3 had become -3, then what was the maximum power, what was the minimum value of here. What should be the value of difference with you Shakti hai mines which is equal to 5000 What should be the maximum value Shakti is the maximum sum of D Road which again is equal to ₹ 5000 of D Road which again is equal to ₹ 5000 of D Road which again is equal to ₹ 5000 then what is not in the range with me What became of the range of index I had with me 0 was 20 and the difference of the other variable that I have was -5000 ₹5000 So by doing this which I know new defense is zero based indexing then ₹10000 is the last index date and then ₹10000 is the last index date and then ₹10000 is the last index date and this product. Now what I did if I have difference + 5000 which we had added here five thousand + 5000 which we had added here five thousand + 5000 which we had added here five thousand I already calculated its value if it was -1 negative I had set -1 if it was -1 negative I had set -1 if it was -1 negative I had set -1 -1 represents also haven't -1 represents also haven't -1 represents also haven't completed de value food If you have to do this particular state on computer, then I will return it directly. If not, then come back to me with the answer that I had returned and store it in your DP as well. Right, there will be complexity in the new time, that is just the number of state. Deepika is not there and then I will have length of D road negative values are also coming right very negative values are also coming right very negative values are also coming right very minimum value is coming to us then we will reduce the answer to zero please subscribe my YouTube channel like this video and if you have any other query and comment And write me on ranji recommendation in comment area thank you
|
Tallest Billboard
|
number-of-music-playlists
|
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000`
| null |
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
6 |
in this video I will explain Lead Core problem number six zigzag conversion in this problem you are given a string and the number of rows and the string has to be expressed in a zigzag fashion what do they mean by zigzag fashion for example let's take the English alphabet for example A to Z and the number of rows is equal to 5 in zigzag fashion you are just drawing the string from top to down that is a comes in the first row b c d in the consecutive rows and we travel up again along the diagonal then again down then again along the diagonal and again down one way to solve this problem is you will just create a dimensional Matrix and you will fill this and you will arrive at the solution but if you look at a very important observation right what are you doing here you are traveling five steps or the number of rows down and they are climbing number of rows minus two times up then again number of rows or five times up down and again three times up or along the diagonals so if you look very closely here you can directly from the string how can you form the string that is what is the difference between a and I the difference is H or 5 into 2 minus two y we are traveling 5 times down and we are also traveling 5 times up but i and e will be excluded since they are the diagonal element so it is 5 into 2 minus 2 that will be 8 that if similarly the difference between C and K is also a similarly B and J is also 8 but the interesting part comes when we have to add the H G and F also that is the diagonal elements also we don't have this problem for the zeroeth row and the last row so if you look closely here it will just be whatever is the difference minus 2 at each step right why because J and I are getting excluded so if the difference was 8 initially for the first row the difference is 6 similarly for the second row the difference is 4 and for this Row the difference is just 2. so what will be our formula the actual difference will be number of rows into 2 minus 2 and the diagonal difference at each row we can use this formula and find the diagonal difference and we can just at each step hydrate and append this particular index till the end of the string for example what do you do a that is 0 you will add 8 and arrive at I you append a I then you go to Q then again to Z when do you go until and unless the string is over you do this task a IQ Z then again for the second row you do the same task but remember you have to add the diagonal element first then you have to add J so this task is repeated again until the string is over again for every row until the last row and here you have the answer what is the time complexity here if you look every character is just I treated over one time so the time complexity will be n and this space we are not using any extra space so it will just be 1. thank you for watching the video please do like and subscribe
|
Zigzag Conversion
|
zigzag-conversion
|
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
**Example 1:**
**Input:** s = "PAYPALISHIRING ", numRows = 3
**Output:** "PAHNAPLSIIGYIR "
**Example 2:**
**Input:** s = "PAYPALISHIRING ", numRows = 4
**Output:** "PINALSIGYAHRPI "
**Explanation:**
P I N
A L S I G
Y A H R
P I
**Example 3:**
**Input:** s = "A ", numRows = 1
**Output:** "A "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000`
| null |
String
|
Medium
| null |
23 |
welcome to january's leak code challenge today's problem is merge case sorted lists you are given an array of k linked lists each linked list is sorted in ascending order merge all the linked lists into one sorted linked list and return it if you recall with merging two sorted linked lists we could use the two pointer solution what we do is point to the head of both of these linked lists check to see which one is less add that to a output linked list and then move that pointer ahead uh once we finish with one of the linked lists we will add the remainder since these are both sorted uh the remainder to our output and that's going to create a merged sorted list but the problem with that is we have k sorted list right so why don't we use that two sorted merging two sorted linked lists uh but do it just iteratively for like one and two then whatever gets returned out of that we'll add three then whatever returns out of that we'll add four and so on and so forth so what i'm going to do is use a write a helper method call this helper and this is going to just merge two sorted linked lists and we'll just have the l1 and l2 these are the heads of both the linked list so we will first initialize a dummy pointer as well as a current pointer with the list node just whatever is zero and while we have l1 and l2 we are first going to check to see which one is less if l1 that value is less than l2 that value then we will add the l1 value to current.next current.next current.next we're going to regenerate the linked list or the node we'll say node.l1.value like this make sure to node.l1.value like this make sure to node.l1.value like this make sure to move ahead our l1 to the next one and if otherwise the opposite is true then we will just make it this node of l2 that value and move ahead rl2 instead make sure to move ahead our current pointer as well otherwise we will just be continually adding or replacing the next one with the same with a different list node once that's finished we need to check to see what's remaining so if l1 is remaining then make that equal to current.next otherwise if l2 is current.next otherwise if l2 is current.next otherwise if l2 is remaining then make that equal to current.x current.x current.x finally we just return our dummy.next finally we just return our dummy.next finally we just return our dummy.next which is going to be the head of this merged sorted linked list so now that we have our helper method uh what we can do is first initialize our output to be the list of zero and for the remaining linked list we are going to run our helper method so 4l in list starting with the second one let's just input output with the helper as well as the l and finally we turn the output here so this solution would work uh we do need to take care of some edge cases like if not list then we should just return nothing otherwise if this or the length of this is one we also should just return list zero none of this matters right here so let's make sure this works and this should get accepted oh but it doesn't isn't that interesting okay so this doesn't work um apparently it's too slow i could have sworn this used to work but i guess it doesn't work anymore so can we do better than this well let's think about how we might be able to check to see each one of these heads of the linked list and what sort of data structure we can take advantage of to check which one is the minimum between all like three or four okay one of these so right now i guess it's inefficient because we are iteratively checking each one and it's going to do a lot of extra work we are sort merging and essentially sorting two and then doing it all over again and again so can we do it all at the same time somehow some variation of what we just did but checking all k lists the problem is we don't know how many there are so what data structure would help us keep track of what's the minimum here what about a heap what if we add it to a heap the head of each one of our linked lists check to see which one is less or the least one the minimum one pop that off and keep track of which linked list we pop that off of so we'd have to keep track of the index number and we have that here linked list one is zero linked list two is one so on and so forth each time we pop off we could just update our list to now move ahead our linked list to the next one make sure to now add that one to our heap and then just continue on the algorithm until we've exhausted all one of these lists and that should be a lot more efficient we are doing a variation of the two pointer but except we're using a heap to keep track of all of this so let's try that what i'm going to do is instead of using our two pointer solution i'm going to create a heap and this is going to be an empty list so for everything in our list we're gonna get the top pointer or the head pointer and we need to enumerate this so we'll get the index value as well as the i guess i'll just call it l for ifl in the numerate list we will add to our heap and to do that we have to do a heap push to our heap here but keep in mind we need to keep track of the index number that's why we pulled it out here so let's get the value of our head and keep track of our index like this now one thing to note is it's possible that one of these linked lists is actually empty so we should just say look if there's an l then do that so let's make sure this looks like what i think it should and this should have one two oops oh okay we printed it of course yeah so this is the index number zero one two and these are the head values one two now these are all in a heap right now right so all we need to do is pop off the minimum one and what we're gonna do is move ahead our list at that index number and then add that to the heap again so i guess we'll have to have an output here and what should i make this well it'll be the same thing let's say dummy equals current this would be a list node of zero so while there's a heap what we want to do we want to first pop off the minimum one and that's going to be done automatically for us we can just say heap pop off of the h and it's going to pop off the index while the value right and let's call that value and our index number so now that we have that we need to add that to the next current pointer so current next is going to equal to list node value and we also need to make sure that we're going to move ahead our list node so that we could add to our heap the next one from the linked list that we just popped off of so how are we going to do this well i suppose we say if list i dot next exists then we're going to pop that off and add it to our heap so the heap we will keep push to our heap list the i dot next and i guess we need to get the value as well as the i that we used now one thing we need to note is we need to make sure that we move ahead our list i to the next one so list i is going to equal list i dot next finally make sure to move our current pointer and that might be it let's return our dummy dot next see if i missed anything and that looks like it's working so let's see if this works there we go that's accepted it's much more efficient the other one might be easier to understand but this is the better solution obviously when we're kind of taking care of that sorting all at once it's going to be a lot more efficient we're not going to be doing repeat work all right thanks for watching my channel and remember do not trust me i know nothing
|
Merge k Sorted Lists
|
merge-k-sorted-lists
|
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order.
_Merge all the linked-lists into one sorted linked-list and return it._
**Example 1:**
**Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\]
**Output:** \[1,1,2,3,4,4,5,6\]
**Explanation:** The linked-lists are:
\[
1->4->5,
1->3->4,
2->6
\]
merging them into one sorted list:
1->1->2->3->4->4->5->6
**Example 2:**
**Input:** lists = \[\]
**Output:** \[\]
**Example 3:**
**Input:** lists = \[\[\]\]
**Output:** \[\]
**Constraints:**
* `k == lists.length`
* `0 <= k <= 104`
* `0 <= lists[i].length <= 500`
* `-104 <= lists[i][j] <= 104`
* `lists[i]` is sorted in **ascending order**.
* The sum of `lists[i].length` will not exceed `104`.
| null |
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
|
Hard
|
21,264
|
46 |
hello everyone let's look at permutations the problem statement is we are given array numbers of distinct integers we want to return all possible permutations and we can return an order let's look at first example the input numbers is one two three the output is array of arrays so it has one two three one three two three one two three two one the second example input is zero one the output is 0 1 0. third example input is 1 the output is also 1 but inside a sub array this is a typical problem we can use recursion to solve it the idea behind the problem is say if we want to find the permutation for one two three and four and then we can first take one out and then we find the permutations for two three and four and then to find the permutations for two three four we can take two out and find the permutation for three and four and then find the permutation for three and four we can take three out and then find the permutations for four so we have this recursive structure and then when we jump back to the top and then we can take two out and then get the permutation for one three and four and so on and so forth let's look at the code implementation here let us first handle all the basic cases so this is our three basic cases the lens is 0 1 and 2. let's look at our recursion function for the input array we can try to take individual element out and then get the permutations for the rest of the elements and then we concatenate the original element with the permutation result so we definitely have a loop and then let's leverage the javascript inbuilt method let's use map to loop through the input method and for the map we need to pass in a method for individual n let's first use this filter method to get all the rest elements and then let's run the permutation so we get the permutations for the rest of the element and then let's do the concatenation so here this n this element is the element we take out and then the i is our permutation result and then in the end we can simply return this guy let's look at the structure for this eye this i will be something like this array of arrays so we have sub arrays inside array so when we run a concatenate n with element i we want to concatenate n to the sub arrays so to do this we can simply flat the sub array the depth is one so this will be our solution or we can also even simplify the solution using flat map this is equivalent we're adding a flat one and then let's further simplify this inner callback method let's take this replace this and then put the map all the way in the bottom and then we can simply return this guy this will be a solution when we leverage all the javascript inbuilt method let's submit looks like we have a problem here let's um try to solve that problem so i guess for this check we can ignore because the lens is minimum lens is one so for this one okay i guess the problem is we need to put it here okay let's sum it again it passed let's look at the complexity here i guess for space it's n factorial n is the size of the input array because full permutation the total solution is and factorial because for the first position we have n options that's to pick one out of n numbers to put at the first position and second position we have n minus one and third n minus two and so on and so forth so in total the space complexity is n factorial for time is also in the factorial this is because we have this recursive structure and first time the loop how many times we need to look through that's n the second time we need to loop n minus 1 the third time and minus 2 and so on and so forth so that's a space and time complexity what if we cannot use the inbuilt method what can we do to simulate the process i would propose we have a recursive helper method and the parameter we're passing is array start index and index it should look like this so this is to get the permutation for the input array from index start to index end and then for our input array noms what we should call it perm nums let's start a zero and this nums the length -1 we should call it the length -1 we should call it the length -1 we should call it like this apart from this we should have an array in a global scope and then in over this recursive helper method we can push the result into this rest array let's look at how we can simulate the process so definitely we need to have a loop for the input array and move from start to end and then inside the loop we want to run the permutation for the rest after we're taking out the first element that's to run perm same array that's i plus 1 that's the next element the end is still the end by doing this we'll get the permutation for the same array and then starts from i plus one to the end and then for the second time in this loop what we need to do we need to swap the position it's like first time we take one out we run the permutation for 234 and the second time we need to swap the position between one and two becomes like this we get we run the permutation for one three four we need to swap the position how we can do that we can simply either use a helper method to swap or we can use this in-line expression so we can swap start with i so it's like we swap one and two and third time we swap one and three and after this we need to restore this input array we need to revert it back to one two three four before we do the swap between one and three so that's why we need to restore this input array we need to run the same slope again after we jump out of this previous permutation so we do the same thing here to reiterate so we first swap i we start and then we run the permutation from i plus 1 to end then we swap it back and then for the next situation i increase but start remain the same so we swap again we do permutation and then we swap it back let's look at the termination condition for this recursive method we're passing array start and end if start e consent then we can simply return and stop doing it again so if starting index equals n index we simply push this current array here we need to have a copy we cannot just push the array into our rest because later this array the index will get swapped in the end it will everything will be the same so we need to have a copy of this array and then return so after doing this we have our everything pushed into rest and then we can simply return s let's sum it again uh we got this another problem i guess we need to uh first define before we call it and another small thing here is uh it should be start plus one because we're here we swap i and start so we should get permutation from start one to n let's try to uh sum it again this time it passed yeah i'm sorry it took us a couple times to get it accepted so for this recursive method we did not change the size of the input array but we swap some of its indexes it's here and then we can have this uh star index and end index once they meet we simply push this array into our rest so if the whole process have confused you feel free to uh print out the stock and indexes and this input array and we can see even more clear what's the recursion process and also probably we don't need this anymore finally let's look at another solution it is to construct a recursive tree from top down it's like deep first search for tree let's look at the code and we still need this rest and this for this recursive helper method we no longer need uh these two let's remove them and then we still need our for loop but this time it should uh from zero to the shoot from zero to norms the length that's the depth of our tree uh let's first do this so when we call it we can simply pass uh empty array because this array the size of this ray will change and then once this array the length equals num dot s we can push it array inside so that's our stop condition and here is no longer swapping if you change you should change to this and then we need to change the size of this array so what we can do is already push numsai we push it in and then we run this again and after this we simply pop the value out and because we when we build this tree uh we need to make sure if array has already have these nums uh we don't write it again so that's uh if it's already includes namsan we simply continue let's try to sum it first uh it passed the structure here we have is really similar to our previous solution we push a value in and then we pop it out to restore this array uh we also have this if condition here this is to stop us from pushing the repetitive value inside this array and if this has uh confused you uh feel free to print out the array before i push before and after push and pop up value so it will be more clear at which layer of the recursion we are at right now like we have one two three four and then we push one two three four in and then we jump up to four and then two three and then we push four again and we push three again so we have one two three four and one two four three and for the complexity the time and space remain like this if you have any further questions please leave a comment below thank you for watching
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
1,011 |
today we are going to talk about another very nice interview question or neat code problem 101 1 so this question talks about a conveyor belt that has packages that must be shipped from one point to another within D days so we are given an array of packages that there's weights specified so it's like package one has weight 1 2 has been 2 and so on and you want to ship all these packages within 5 days now what the question asked is what is the return the least weight capacity of the ship that will result in all packages on the conveyor belt being shipped within 2 days so in this example that what that means is we want to write this array into 5 parts because D is equal to 5 and it'll mine this and make sure that the sum of each part is kept minimum so for example one of the combinations can be 1 comma 2 comma 3 4 5 6 seven for my eight seven eight and nine four then we have divided the area into five parts but what will be the least capacity of the needed is thumb is the maximum of the sum of these sub errors so the sum for this is 6 this is 96 this is 15 and this is 19 so the ship should be unser unsalted butter to answer is 90 is it the minimum no because there is other configuration that can result in a lower minimum weight capacity needed so that is what the solution shows here which is 1 2 3 4 / 5 and 6 comma 7 8 9 and 10 / 5 and 6 comma 7 8 9 and 10 / 5 and 6 comma 7 8 9 and 10 so our how to figure out the solution for this problem so I lay out the logical step smear through which we can reach what kind of fundamental computer science theory can be used here so let's see so the first question we ask is like we define the problem range what will be the minimum weight that the ship would require the capacity of the ship would require so the minimum weight will be 10 because we have to ship this package and he's on one of the ships on one of the days and it has to go like either alone or with other packages so if it either goes alone then if it goes alone the ship has to be has to have the capacity or at least 10 now suppose the value of D is 1 in that case we have to make sure that all the packages go together so value of May value so in that case the capacity of ship will be 35 which is the sum of this array so a problem space our solution space is do bounded by these two values the first value is the maximum element in the array the second value is the sum of all elements in the array well one of the options can be one of the solution one can be we try all faced from 10 to 55 in this case what we do is we assume that this ship's capacity is 10 we try to fit it in to fill fit all these packages into 5 days so if you imagine is as 10 you what you will do is try to put everything on the ship unless until it reaches 10 so in this case it's this then you start the next day in which case it's just 5 because you cannot add 6 now the next day is 6 for my 7 6 it's just 6 because you can order at 7 and so it will be 8 9 and 10 so in this case if the weights ships weight capacity is 10 we can we will need 1 2 3 4 5 6 7 days which is more than D so what we do is we increase the capacity by 1 assuming every assume that the capacity is 10 now we do it for capacity 11 and you try to pick things up again and it doesn't work and similarly we go on to capacity 12 then 13 then 14 then 15 under religious until we reach our answer which is 15 so this is one option with this kind of like a brute force approach so in this case the time complexity of our algorithm will be so for every time we try to fit the weights on the ship for D days its we traverse the entire array so for any weight capacity we do an O n and the number of weight capacity in worst case will be O of max - min can we do better so this of max - min can we do better so this of max - min can we do better so this bounded problem bounded solution space of from 10 to 35 give us a good hint that this can be quickly have to search our answer between this range now when we talk about search we can lower the complexity of algorithm by using binary search now what point how we can use binary search here is we try at any capacity between 10 to 55 we know whether we would want to go in the lower direction on the higher direction so this problem efficiently supports the concept of pi through binary search to be applied so let's see what with the time complexity will be in case of a binary search so for binary search we have four we will still do or end or every capacity that you want to check but we will not go through all the elements from min to max if the time complexity of that with the log of next management so this is how our time complexity will look like if you use by research for this problem so let's get to listen to writing the code here we have initialized our min and Max now after you have the min and Max and live with what we do is try to just write a planet about try to do the binary starting with min and Max we keep read return value as 0 for now if the meaning like if by default our return value 0 so we start off by loop from the starts from min and which is less than equal to max we will keep doing this will keep figuring these lines within the while loop is the typical binary search algorithms we find the mid and then we try to find the number of days required for this capacity with this capacity so we first try to fit everything in the mid so let's see so let's try to write number of days required so this will return N and for this capacity so we send in all the weights and then we have to pass so maybe we assume that because in the constants we have that there will always be the D is always from between 1 to 50,000 and the weights are from 1 to 50,000 and the weights are from 1 to 50,000 and the weights are from 1 to 500 we assume that there will at least be one weight which is which will be positive so we say we start with D is required as equals to 1 now 2 for each we W n Ebates we do current that seems rates down to zero this will be the weight in our current ship so it's current plus is equals to W current is greater than capacity we will if the current is greater than capacity we will do a days required plus and we want to assign current as W because we have it is already exceeded so it won't fit this w won't ship fit in this ship so we have to put it in next shape initializing base is required it is equal to one also helps here when because in the last even when this condition is not satisfied we still need an extra shape for this so starting with one helps us with that let's return is required okay and here what we do is we do it is required is greater than D which is that means we need more capacity so we move our men to mid plus one now okay we need more capacity else that means we have sufficient capacity so this can be one of the possible answers to force be initialized red yeah do is required because this can be one of the possible answers and then what we do is we reduce we try to reduce our max to make -1 so let's try to execute this code one of the examples we see that this is the wrong answer quad is 500k so actually we have initialized stays required under 12 and we actually require the capacity so the capacity we are test me test it for they required is minute it would be change your car to ma'am and let's try again okay so now this shows that I ate solution let's try some more examples which test some of the edge boundary conditions so this is not very let's see if we can fit these into three days in what is answer required six and six that make sense let's try another example here tail 116 evens correct let's try another one and yes it works so this is the binary search solution for this problem and we also went to what depths are required for figuring out that this is a binary search of that binary search needs to be applied here so like subscribe to this channel like the video leave a comment if you like the solution and
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
382 |
foreign with the lonely Dash and today we're going over leap code question 382 linked list random node which states given a singly linked list return a random node's value from the linked list each node must have the same probability of being chosen implement the solution class so that's going to give you a class called solution and it's going to give you the head value of a list a linked list and all it does is it initializes the object with the head of the singly linked list that's pretty simple and straightforward it's giving you the linked list then they're going to give you a get random function and basically they want you to write something that chooses a node randomly from the list and return its value right that's what it has to do all the nodes of the list should be equally likely to be chosen so even though they make it look pretty complicated it's a simple concept so how are we going to solve this well we're going to use this example right here example one it's a singly linked list one points to two points to three and all we're going to do is go through one time this linked list and we're going to stick all the values in Array so this one would look like one two and three now we have a length for this array which is three and then once we have that information we're going to give a random integer generator which is that exists in pretty much every language we're going to use random interject integer generator and we're going to say hey give me anything that is between 0 and 2 right because if the length is 3 we're thinking in indexing so that would mean we'd want indexes is 0 1 or 2. right so it's a total of three but it's indexed uh zero indexed and so the random integer will give us one of these three numbers and then we're just going to return whatever value is in this array at that generated um that generated integer as an index so it's pretty simple pretty straightforward let's take a look up here at our constraints and see if there are any edge cases so for our edge cases their constraints basically just say that there's going to be a number of nodes in the linked list and it's going to be anywhere from 1 to 10 to the fourth power so we're not going to have an empty linked list so that's pretty simple all of the nodes are going to have values and they're going to be integers between negative 10 to the fourth and 10 to the fourth so we're not going to have a uh any issues there and at most 10 to the fourth calls will be made to get random so again nothing to consider there no edge cases that we're terribly worried about let's get to writing some very simple pseudo code okay getting straight to our pseudocode the first thing that we're going to have to do is create a function because it's we're actually provided the option for two functions I think when we do this uh let's just make sure I want to make sure we're doing this yes so if we're looking at it yes we're given one function and two functions with which to mess around with so uh we need to start by create a function that will add all of the values of the linked list into an array or a list right so we're just we have to iterate through a linked list because there's no way to find the length of a linked list without iterating through the whole thing so while we're doing it we might as well just create an array at the same time once we're done with that we're also going to have to create a function that produces a random number using the random Library based on the length of the created array and most languages that we're going to be studying python Java JavaScript there's going to be something that's already been created in a library that will produce a random integer so we will be using that and once that's done all we're going to be doing is returning the value at the random number that was produced index and that's it that's all of the pseudo code in order to write actual code for this question so let's copy and paste it and get coding okay here we are in the Java work area of the lead code website on linked list random node and we're just going to kind of follow along with our pseudocode sort of so in order to solve this the first thing it says we need to create a function that will add all of the values the linked list into an array list so this is our first function the first thing we really need to do is create an array and I want this array let's see private array list it's going to hold of course integers integer uh there we go integer and we're going to call it nodes and it's going to be a new array list bam Okay so we've created an empty array list that's going to hold all of the values from the linked list that we were provided now we need to create that while loop that will actually add those items so while the head of this linked list exists so while it's not null what are we going to be doing well we're just going to take the values of each time we go uh each element and we're going to add it to this array so this dot nodes we're going to add whatever the head value is so hopefully that makes sense but since it's a while loop and we is a loop we do need to move the head each time we go through so head dot next so for each element which we're just going to say is head we're going to be adding the value into this array okay so that hopefully that makes sense so that's how we're creating a function that will add all of the values now we need to create a function well the function is called get ready random that produces a random number using a random Library based on the length of the created array okay so we can kind of figure that out slightly so we're down here in our other um our other function and we need a bunch of information and the first information we need is to figure out the length of the array that we just created right and so I'm going to say this dot nodes dot size is going to be whatever that length was now interestingly if we are going to reference this nodes array we're going to have to make sure that this array is globally available so we're going to take it out of this function and we're going to put it way up here where everybody can access it so we can access it here in solution and we can access it and get random so now this is going to tell us how many elements are in this array okay great now we also need to figure out how we are going to get a random number so in Java we can just call math.random math.random math.random and what that is going to do is produce a number anywhere between 0 and 1 and that's it zero and one and yeah that's it but we need to connect these two together in some way right because uh getting a number between 0 and 1 doesn't do us any good when we're trying to figure out an integer to use as an index so what we're going to do is multiply whatever number that was randomly created by the length of or the size of the array that we get and that's how we're going to figure out a number that's at least all greater than one um but we also need to ensure that it is an integer okay so we're going to stick all of this inside of let's see some parentheses and we're just going to make sure that it's going to come out as an integer and that should be everything we need we just need to declare it as a variable uh so we're going to say it's integer we're going to call it choice and it is equal to all of this stuff so hopefully that all made sense where we're saying making sure this is going to come out as an integer because math.random is going to produce a number math.random is going to produce a number math.random is going to produce a number between 0 and 1 completely randomly and then we're going to multiply it by the size of the array so that we can get a number that is an integer we can use as an index to the array that we are going to have to find a random value in and all we're going to have to do is return a value at a random number index so how do we do that well we're just going to say return this dot nodes and we're calling this array up here dot get choice so we're getting our choice and we're saying hey what is the value at this index in this array and that should be everything that should be all of the bits we need I'm going to hit run and hope I didn't make any mistakes it's three milliseconds not bad hit submit and see how we did against everybody else in the world and all test cases and it comes out pretty good we're hitting almost 100 percent in run time and our memory is not the greatest at 55 percent but it's a very straightforward way of solving question number 382 linked list random node using Java foreign
|
Linked List Random Node
|
linked-list-random-node
|
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?
| null |
Linked List,Math,Reservoir Sampling,Randomized
|
Medium
|
398
|
95 |
hello and welcome to another video in this video we're going to be working on unique binary search crease 2. so in this problem you're giving an integer Annie when you want to return all the structural unique vsts which have n nodes of unique values one to n or turn the answer in any order so for n equals three is our example here we need to do this so essentially what we need to do the way this is going to work is you need to take every single node so we have one two three we need to make a root and then we need to take the left and the right and make all possible subtrees there so for this it's pretty straightforward like let's say we're going to make a root here so if one is the root then we're going to say okay one is the root now how do we split the left and the right essentially right like what are we doing there that's going to be our question and so we need to actually try to build the less than the right at every single point if that makes sense so what we need to do is we need to say okay for a structurally unique BST if one is the root how many different ways can we do this right if one is the root that means that this part has to be on the right side right so for this subtree how many different ways can you do this for this two three so there's two ways you could do a two three right you could either do two three or you could do three two and so essentially we're saying okay now let's recurse down once we say okay one is our root we're going to say let's take these two ways and let's actually combine those and then for the left side of the tree right so for the left side of the tree is just null so this part is just null always but then for this right side we need to say okay let's recurse down and let's actually get this part of it right so let's actually redraw all this and kind of explain it one more time in a better way so we have one two three essentially what we're doing is we're trying every single root and then we're saying okay for this root let's recurse down let's get all the left and the right combinations and then let's add that to the root so once again we try this as the roots if one is the root we're gonna have one here now we need to recurse the left is nothing so that's just the null node and the right is this part so when we recurse into two three we can either make two the root in which case it would be like this right this is the only possible tree or we could make three the root which would be three two and then this is going to return over here and we need to plug in both of those to the tree with the root one so one two three would be like this right one two three or we also have one three two both valid trees and then this is gonna be like this all right so we tried one as the root now let's try two as the root so if we make two the root let's actually get rid of some of this and let's also get rid of this so we're gonna say okay let's actually change this color and make to the root now what's gonna be the last one what's gonna be the right well the left has to be this and the right has to be this so for this there's only one possible combination right it's always going to look like two one three because there's only one note on each side so this is like the this is the subtree with two is the root so if we have two one three but you can kind of see what we're doing we're just picking a node as the root and then we're recursing one level down where we're saying okay let for that let's just make it a left and right subtree and let's get all the combinations there and then for all of those let's just like Loop those together so for everything in the left and everything in the right let's combine those in every way we can it's going to give us all our notes okay and so now we tried that now let's make three the root right that's our last case three is the root so let's do this in another color so we're going to make this over here let's make this in blue and let's also delete so we're going to say let's make three the root now there's no right so there's only a left one two and so how many different ways can we make one two so one two you can do two different ways right you need to make one-thirds or two right you need to make one-thirds or two right you need to make one-thirds or two thirds if one's a root you're gonna have one two or you can make two the root and then that would be two one so those are the combinations of three as the root so actually I didn't mean to delete this three with two as the middle so this was actually this tree here two one three okay now for this we have these two combinations that we're going to be returning so for three as the root we're going to have either three one two right or and you can see the right is always null or we're gonna have three we're gonna have two and these are our trees and so this is all of our trees and we can actually take a look did we miss any so we do have five trees and we do have five trees so essentially let's write down our algorithm one more time just so we can kind of get a sense of what we're doing let's turn it over here so we're gonna have a left and a right value and we're going to Loop through let's actually make this a little bigger after I type it so if you see better so let's Loop through the numbers and let's just set a route then we rehearse the left and right side of the tree and get all valid trees each and then finally we need to combine all those possibilities plus the root we picked into a tree trees I guess and store in the output okay so essentially that's what we're going to be doing and we can make this anything bigger so there you go that's what we're doing we have a left and right value where it's just going to start with like 1 and n and then we just pick a random route like we're gonna pick one we're gonna pick two we're gonna pick three and then we get the less than the right based on the Ruby picked the left has to be less than the root so if the values were like one two three four five right and we picked three as the root the left has to be this side and then the right has to be this side because all the values on the left have to be less than three so then we would be passing in one five initially and then if we pick 3 as the root the left would have one and two and then the right would have four and five and then obviously you can't have the case where like let's say this is a root then we're gonna actually pass in zero and one and that's going to symbolize uh actually we're gonna sorry we're gonna pass in one zero and that's going to symbolize like an invalid index so then we can just return none because you do want to return none for the empty node because you are going to combine none with the rest of the tree so like if the right side of the tree is like this let's say two three or three two the left side could just be the null node and then we have to combine that with both of these so the left is going to be null with this one and the left is going to know what this one if we try to try both okay and there is also one more case so there's actually the case where you're doing repeated works if you have like one two three four five and let's say you pick four as the root now this is going to be the left side now we pick 3 is the root now this is going to be the left side well we could have also picked you know in this one two three four five we could have also just picked three as the root originally and then this would be the left side so you see like we're doing this one two multiple times so we can also add caching here where we can check if the left and the right is in our cache let's just give that back you don't need caching for this one to work it'll actually pass without caching and have a decent time complexity but if you want to make it a little bit better you can add capture so let's code it up now so we have a visited cache then we have a let's just call it a builder or something and we're going to have a left and a right here so let's just call that left and right and we do have a base case where the left is bigger than the right that means we don't have any valid nodes if left is greater than right let's just return the none in an array right you're returning an array of trees so we're going to return a non-tree like a null node return a non-tree like a null node return a non-tree like a null node essentially okay now what we need to do is we need to be looping from the left to the right so we can say for I and range Left Right plus one because it's exclusive then here we're going to need to build our left and right oh we also need to check our cache by the way so if uh left right visited turn visited right here as always so that's our caching perfect now let's actually uh go through this Loop where you're setting Roots so whatever route we pick we're going to have a left and a right so we're going to say left equals um what are we going to do here or we can call this like maybe left children or something or left subtree trees left trees let's call it trees equals this is going to be Builder and then it's actually going to be the left bound is the left and then the right bound is going to be I minus one because if you think about it like if we have five nodes like one two three four five let's say an i is three the right needs to be two and then if we pick this then the right is going to be zero so then we'll have one zero meaning invalid tree which means a null node which is what we want right if we make this here then the left side is to the left and there's nothing there so now we do right trees equals Builder and this is going to be I plus one right so same kind of thing if we pick the rightmost value it'll also be out of bounds because we have multiple five we make five the root then I plus one would be six so then we'll have six five which will also be left is greater than okay so now we have our left and right trees now we need to take every single combination in both of them and make and add those together so we actually do also need a result array or we can just say we can uh we can do that here I guess so we can say like four tree or you can say like left in a left trees four right in right trees right take every single combination and every single combination needs to be added into a tree and then what's the root going to be well it's going to be I right we pick the I from either so we could say visited uh let's actually make a result array here so we're going to say result we need side of the for Loop though make it here resulted this then we could say res dot pen and then we're going to say tree node with the value of I and then the left is going to be the left and then the right is going to be the right this is the left sub trees the right subtree so the left sub 3 is going to be left right subject is going to be this we're going to append that to the result and now we finally need to cache it equals the result and we need to return it okay so now we should be able to call return Builder and what our initial values so if you think about it our initial values need to be one and N right they need to start from one to n so our left is going to start at one our right is going to start at n okay let's see what happens hopefully I did everything right there maybe not so this needs to be right and there we go so you can see it's uh super efficient with the caching so I would recommend you adding that but if you didn't have it would also work it's gonna be a little bit less efficient so I will also say for this the time and space complexity is really confusing and really hard to derive so I wouldn't expect to have to derive it in an interview I would just say like kind of talk about what your function is doing roughly you know like you say okay for every single case I am doing this for Loop and then I am cutting my array into a left right and a so essentially I mean not exactly cutting the array in half but on average maybe cutting their in half so you could talk about it but it's some crazy thing like for over whatever like root end to the square I don't know something that you can't come up with in an actual interview yeah so that's gonna be it for this problem and if you liked it then please like the video and please subscribe to the channel and I'll see the next one thanks for watching
|
Unique Binary Search Trees II
|
unique-binary-search-trees-ii
|
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 8`
| null |
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
|
Medium
|
96,241
|
343 |
hello everyone so in this video let us talk about a problem from lead course and media level problem the problem name is integer break so let's start the problem statement goes like this that you're given an integer n and you have to break that into the sum of key positive integers as that K is greater than equal to and you have to maximize the product of those integers you have to just break this number in two or more numbers such that the product of those numbers should be as maximum as possible that's over problem statement I just have to find another product so n is pretty small whenever I see small numbers either it will be done by backtracking or maybe modification of DP I just got some hint out of that only but let's move on to some solution path what you can understand is that the first thing which I which comes to my mind is okay let's say that if I have a number let's say five let's take one example of 5 only let's say I have a number five so for even for any problem any random problem first try to find out some examples and try to see can you find some pattern around it so let's see for five options can be I break it into one and four because one plus fours have to break into the number such that the sum of a number should be equal to that number but the product should be maximized so the product of them should be four or I can break into two plus three and three plus two or four plus one is same only but let's say two and three so the product is six which is maximum so this 5 can be like from five you can get a maximum number of six by breaking it down so the answer for this is X now let's say if I take a next number that is let's say 10 for 10 I can break it let's say one in one and nine okay and let's say uh one and nine and then I can also make it letter two and eight but let's say I can also make it five and five there were five and five we have break it down the five and five multiplication of five and five is twenty five but I can further break because I do that for five the maximum I answer I can get to break out five because if I break down five two into two and three the sum remains same so let's say if I break this into two and three the sum remains same so it is equal to 10 only but because from 5 I can directly get the maximum value of 6 and now I can get 6 and multiplication of 636 and that's the answer so for 10 the answer is maximum 36. so hope you get the points of what strikes my mind is that okay I have to somehow store the previous value what is the previous maximum values I can get one from that value I can bring out or build the next value so it's very simple now what you can do is that first started values you can get the answer that for one there's no answer because it always starts from two I can only make it into one and one so the answer is one into one is equal to one only so for two it's equal to one for three I can break it into two a two and one so the answer is but base of 2 into 1 is equal to 2 only for 4 I can break into two which is equal to 4 I'll drop 5 you can start doing this operation so what you can do is that from five I have to break five into two numbers and if it breaks down more it will be handled by this particular case in which I will store and make a DP okay that D2 will store that for a particular number what is the maximum number I can get by dividing it and multiplying it with its different values so for 5 it can be divided into one and four okay then 2 and 3 and 2 and then four and one among all of these values can I like can I further break one and four down so I have two options for everything I can either keep one as it is and break down four what I mean by this is let's say if I have number that is let's say three and eight okay it's maybe because see if I break down three I will get two so from 3 I will break down three as two into one which is a smaller number so it's not better to divide three I hope you get the point so it's not always to choose the smaller value the DP value is not the best way because if I like divide three more smaller it will get into two which is a bad thing I will pick at the point so what it eventually leads us is that I should not always take out the like the smaller value like I should I have four options eventually if I can just multiply these two either I just I have the sum as let's say 11 8 plus 3 that is eleven so I have the sum as eleven so let's say I have number eleven I have to break this into two numbers so I have a breaker into three and eight so either multiply three into it or I can use the DP value of 3 multiply with eight or I can use a DP value of 8 and multiply with three or I can use a DP value of both and multiply the DP value will store the max like the maximum I can get by dividing it and the other value is like if I don't divide it if I just take hope you get the point that is the overall thing and for every value is calculate out and we'll just lead down to n is very small so it will be very small thing so we just find it for DP value let's initialize a very uh let's say it is from 58 I'll just exercise with 100 so 100 numbers I can get some starter number so let's say for D PL one I just initialized one so that if I hit the condition I know that it is one only but two it is equal 1 3 equal to two I start with 4 for 4 I said so add the number that is I will iterate over so I have to break into two numbers but so let's say I start from one so if I take the first number is one the other number will be numbers minus one okay I hope you get the point so let's say I want to Total sum of 11 I want to break in two numbers the first number is one so the numbers will be ten so one plus ten okay so if the first second number is 2 it will be nine so if J is irritating or every possible number okay one two three four till the numbers length whatever total numbers is okay so the first number is I can just take out one and the other is neck numbs minus X so I have two numbers now for these two numbers I have four options okay I have to maximize this DP of I over these four possibilities the four possibilities are just multiply these two numbers or I will just DP of X into y x into d by both the DPS open okay and just maximize it over all the values and over all the possible two numbers I can divide the total number into and if it further divides then it is generated by DP values only just want to maximize it about DP I just spit out the DPL if that's the world uh logic and the good part is not too much difficult to grasp if you just understand and just take some examples it becomes very frequently very quickly to graspots of knowledge as the logic and bye
|
Integer Break
|
integer-break
|
Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers.
Return _the maximum product you can get_.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** 2 = 1 + 1, 1 \* 1 = 1.
**Example 2:**
**Input:** n = 10
**Output:** 36
**Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36.
**Constraints:**
* `2 <= n <= 58`
|
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
|
Math,Dynamic Programming
|
Medium
|
1936
|
344 |
let's reverse strings now sure i can always use the same inbuilt reverse functions for this in a cheeky way but where's the fun in that so we will be dealing with manipulating the positions such as position zero or position four in this five letter word since strings are immutable meaning that i cannot change them internally i am going to use a list with individual characters remember swapping from a few lectures ago we can use that same concept to swap the letters in a list for this problem i need two owls a left owl and a right out and they both will eventually need to hang out they both start at the left end of the list and the right end of the list respectively then step one i move the letter y with the right owl to the swap variable and then move the letter o with the left owl to the right owl and then i move the y from the swap variable to the left out it's just like the pizza sandwich swap plate example which we did before now my owls jump one position my left owl goes right and my right out goes left just by one position now repeat steps one two three and notice that my letters get swapped now the owls meet at the middle position to grab a worm sandwich for lunch and my entire list has been reversed let's see how this looks like in code my left owl is at position 0 the leftmost end my right owl is at position 4 which is the total size of 5 of the list minus 1. i run a loop with the condition that the left owl value is lesser than the right or value when they are the same the loop exists and it prints the levers list inside the loop once again in step one i have a swap variable which gets the value at the right outposition in step two the right out position is the value at the left out position and finally in step three the left out position gets the value in swap then i make the left out jump to the right by one and the right i will jump to the left by one simply by adding one and subtracting one respectively
|
Reverse String
|
reverse-string
|
Write a function that reverses a string. The input string is given as an array of characters `s`.
You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory.
**Example 1:**
**Input:** s = \["h","e","l","l","o"\]
**Output:** \["o","l","l","e","h"\]
**Example 2:**
**Input:** s = \["H","a","n","n","a","h"\]
**Output:** \["h","a","n","n","a","H"\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
|
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
|
Two Pointers,String,Recursion
|
Easy
|
345,541
|
1,684 |
Hello friends welcome to a new video in this video I am going to discuss a Lead Core problem okay and this problem is based on strings so the problem is counter number of the consistent strings so you are Kevin are staying allowed string okay allow Steam and then add it okay um a string type added okay and a string is consistent if all character interesting appears in the string allowed okay we only need to return an integer type value okay this is contains some streams okay the what this question is saying to you is string they have some character a d b d a b a d a b okay so what this question is saying to you uh like in this thing you have two characters A and D but in this allowing their head A and B means this D is not present this allowed string right then we will not count that string next in next thing they have two string B and D but this D is also known as pressure in this allowed stream then we will again not count this thing the next thing is a is present a is also present to and the last thing is B but B is also present right this piece also present so we will count resting means then we can add testing in our result the next thing is baa this B is present a is also presented we will also count that string but the last thing is BP is present a is present but D is not present right then we will not count that string mean then this uh we will count only these two strings and the laser will be two okay I have this question clear to you now let's see how we can do this so at First Take A Boolean with a b and initialize uh it is true value okay and they can increase your variable count okay so we will at first reverse this words adding okay for we will use a for each Loop okay string is words okay then again we'll again Traverse each character right we need to cover each character okay so now where I character oh okay what of C column a store to get added Okay so now the last thing we need to do if allowed now taught contains word of C but I think you know this contents method it is a string type method means we can only use things but this is a character so you need to convert this character into a string to how we can do this we only need to add this thing okay sure so the thing is what I am trying to do here like take a first thing like a b we have a b okay A T so first thing is a d so first character is a means the first thing is the first character is a here we are con we are checking this a b is containing a or not yeah it is true okay fine the next character is d t is not contain um this Earth means the next cat is D this day is not contained right but we will use here means it then it will return false we'll use note operator and then we will initially B will uh initial SB false okay and if we're done we will start P true okay and then if um if then if we if B is fourth then we can easily break we hold we note we then we not need to check this if condition again because this is only say we found out that there have four characters present in a particular string that is not present in the allowed stringent we no need to check the whole string because um I already found us characterized that is not present in the last thing then we can just break the follow when we come out from the for Loop okay so then we will check if B is true if p is true means they don't have any character that is not present in the uh but in the particular string okay count plus okay then we return count okay let's take an arrange the example like a b okay to your first is character is a then we take a b is contained a yes two then this if condition is not uh execute the next character is again a 10 is all through again is a which is also this condition is not true then again a okay and the last character is B okay and this a b is contained P also then this for Loop is not executed um okay means this base becomes true okay only that kid only that case we will just increment this count variable okay I think it's clear now let's learn this code oh my God okay I think it's clear to you can optimize this code also but I here just try to understand a simple logic I think you can get what I am trying to um say I think you can understand this whole code so that's all for this video I wish this video is helpful for you thanks for watching
|
Count the Number of Consistent Strings
|
find-latest-group-of-size-m
|
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example 1:**
**Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\]
**Output:** 2
**Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'.
**Example 2:**
**Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\]
**Output:** 7
**Explanation:** All strings are consistent.
**Example 3:**
**Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\]
**Output:** 4
**Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent.
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= allowed.length <= 26`
* `1 <= words[i].length <= 10`
* The characters in `allowed` are **distinct**.
* `words[i]` and `allowed` contain only lowercase English letters.
|
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
|
Array,Binary Search,Simulation
|
Medium
| null |
136 |
what's up youtube today we're going to take a look at lee problem number 136 single number marked as easy let's get into it so the problem statement says given a non-empty array of integer nums given a non-empty array of integer nums given a non-empty array of integer nums every element appears twice except for one find that single one follow up could you implement a solution with a linear runtime complexity and without using extra memory so an example would be we will have in our input array two one so two appear to appears twice one only appears once one would be the element we're looking for another example would be four one two four is the only element that appears once and i'll put four i'm going to go through three approaches that i really like starting out with counter or hash table so in python we have something called counter which basically counts the elements in an array and assigns each element a number of how often they appear pretty much yeah that's why it's called counter so if we use a counter to count all elements in our array we would know which ones p just wants and which appear twice and then we just need to filter that counter and put out everything that has one as an appearance and there's only one that has that so we can just return the first element that fulfills that condition so let's call that one c and create that from nums and let's just print that right now for you to see how it looks like it's basically a dictionary or yeah in other languages you could call it a hash tablet hash table and as you can see we have two in here as a key and the value would be two so two appears twice one appears once cool right now all we need to do is go through that counter so for n in c so n would be a number in that counter could call it num as well but it's to n because it's shorter and if and the value of n in c we're gonna have to look that up using our dictionary notation if that is one we want to return n is the key one is the value in this case so it could be another test case let's put in some other values just put in a three instead of one and let's print that out as well again for you to see return and let's do it again don't have premium anymore so in this case a 3 would have the value one and we're going to give out that value because it's the only one that fulfills that condition and that works because uh python has that counter we could implement it our selves by going through that nums array and just creating our dictionary or hash table ourselves but counter makes it more convenient and you can use it for many problems on lead code that's why i really like this one anyways um creating a counter is of n complexity in terms of runtime and it also requires n space so we're just going to create that counter and then go through it once that should be o of n as well and then just do that comparison lookup is constant and return n so overall runtime complexity would be of n just like space complexity let's go to our second solution and when i'm thinking of arrays with just numbers and comparing them and how many appear once or twice i think of sets and set operations are often a good way to solve these problems using less resources and in this case there is a mathematical way of solving that which is quite clever and that's why i'm going to present it so set allows us to reduce that array to all its element just appearing once it basically tells us which elements appear in that array no matter how often so if we create the set of nums we get all elements just once and in this area numbers all appear twice except for one that just appears ones so if we sum that up double it that should be the sum of all elements appearing twice right and that is almost the case for our initial error nums just one element is removed so one just appears once apart from that everything is the same so if we compare that to this the sum of our initial array some numps we should get that one element because that one element makes the difference between yeah a complete array of everything appearing twice which we created here and the actual query uh array where which just appears once so the difference of that should be our result so we can straight up return the result of that equation and get an accepted output which is very cool in terms of runtime and space complexity sadly that doesn't really optimize anything it's just an alternative solution that is very cool to come up with because some goes through that entire array nums set as well to create that set and in terms of space we need to store we need something to store set and that's why we have o of n for both run time and space complexity exactly but there is a better way of doing that and fulfilling that follow-up condition and fulfilling that follow-up condition and fulfilling that follow-up condition of implementing a solution with a linear runtime complexity and without using extra memory let's get into it so for the final solution we're going to use pit manipulation which is outlined in your fischer solution which is very well done and the author should get more praise and so we're going to switch straight over there as an exception don't usually do this but i think this one explains it pretty much perfectly so for this approach it uses the xor operator and bit manipulation as i said so if we take the xor of zero and some bit it will return that bit so doing that operation with zero is just going to return itself so we're going to start out using 0 as to not change our input what's important here is that if we take the same two elements with our axo operator it's going to cancel out and return 0 which is perfect for our plan of getting the single element because every element that appears twice is going to cancel itself out so if we have 2 3 in our array two and two are going to cancel itself out and we have three left which is what we want right if we start out using zero um three and zero is going to resolve to three as well so 0 is just like a dummy we're using also the last point points out that exclusive or is quantitative so it doesn't matter which order elements come in for our operation to return the result in the same way so we could use that solution outlined down below to get time complexity of o of n and space complexity of o of one and if we run that code of course it's gonna turn out to be accepted but we can optimize this one even further by reducing our space complexity we can use the first element of our numbers area to even further optimize memory by storing our result in that first space so we're going to iterate through that array again but to our result in the first element first spot so we're gonna iterate from one and use the first element already to do operation which is going to look as following so i'm going to overwrite that by using xor on it yes and in the end we're just going to return that first element so instead of using 0 and then going through the entire array we're going to start out with the first element which is going to be itself anyways if we uh do xo with zero so we're just going to start out from there and then overwrite our result in that first spot and return it so that should optimize it even further and also give us an accepted output let's submit that code and hopefully get an accepted solution as well it's accepted that's been pretty much it for that video i hope you enjoyed it i think it's a cool problem it has a lot of upwards and it allows you to get quite creative use that counter solution come up with a brute force solution first which i didn't go through come up with a creative math based solution using that set sum and also use bitwise manipulation which is very cool and can apply to other problems as well it's probably the hardest to come up with by far but if you wrap your head around how it works and in which situations to use it can be quite powerful and allows you to reduce space and memory complexity anyways i'm going to go through more lit code problems on this channel i have an entire playlist based on sql or sql database problems and now i'm going through python so make sure to stick around and maybe subscribe and i'll see you all in the next video bye
|
Single Number
|
single-number
|
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,1\]
**Output:** 1
**Example 2:**
**Input:** nums = \[4,1,2,1,2\]
**Output:** 4
**Example 3:**
**Input:** nums = \[1\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-3 * 104 <= nums[i] <= 3 * 104`
* Each element in the array appears twice except for one element which appears only once.
| null |
Array,Bit Manipulation
|
Easy
|
137,260,268,287,389
|
1,685 |
hi friends uh welcome to followup in this video we're going to look at problem 1685 some of absolute differences in the SED array uh overall in this video we're going to use partial sum or prefix sum so this is our strategy so our plan will be the following first we're going to digest the problem requirements and then we do the analysis and share the code so now let's look at the problem digest so here we are given an integer array cols sorted in non decreasing order so this is a very important assumption so we want to build and return an integer array called result with the same lens as nums such that result I is equal to the sumission of absolute differences between nums I and all the other elements in the array so here is the um explanation in terms of some um mathematical uh symbols so let's look at the two examples here so for the first uh first one so the return is 435 so if we look at the first return four so you see 2 - 2 is zero 2 four so you see 2 - 2 is zero 2 four so you see 2 - 2 is zero 2 minus two and three has a difference uh it's one in absolute value two and five have a difference three in absolute value so what zero + 1 + 3 that is four value so what zero + 1 + 3 that is four value so what zero + 1 + 3 that is four so similarly you can interpret the three and five and uh for example two you can do the interpretation as in example one so here let's also emphasize on the constraints first the length of this list can be as long as 10^ 5 so in other list can be as long as 10^ 5 so in other list can be as long as 10^ 5 so in other words we need to think of 10 complexity we will do the coding secondly so nums I is less than or equal to nums I + 1 is less than or equal to nums I + 1 is less than or equal to nums I + 1 so it means that uh this list is in sorting uh order so it's bed above by 10^ 4 so with that St actually we're 10^ 4 so with that St actually we're 10^ 4 so with that St actually we're ready to do the analysis so as we mentioned at the very beginning so the strategy here is partial sum so actually here the thing is that uh for each General I so let's see for a given I this is the index right let's see index uh index I so we can uh compute uh the absolute difference right absolute uh difference with all the elements in the NS list so here the same so let's call the result is result I it equals to uh this one right so to the left of this index all the number is no larger than the current number so it's the difference will be nums I minus num zero and plus uh nums I minus nums one so the sumission up to this one nums I uh minus nums I so you can write nums I minus one but you know anyway nums I minus n i is uh is zero so then to the right of nums I all the numbers are larger than nums I so we are going to have nums I + 1 so we are going to have nums I + 1 so we are going to have nums I + 1 minus larger than or equal right and the more rigorous uh speaking so we have this one and also nums I + this one and also nums I + this one and also nums I + 2us nums I and in general so we have so the last one is nums n minus one let's assume the list has l n right the minus nums I right so if we want to do this problem by this way so actually you do know it can be o n of square and timecity that might not pass all the cases but if we do more computations or simple algebras we will see so if you see this one the first row here so we have uh from zero to I so this is the um this includes uh I + one terms right so in other words I + one terms right so in other words I + one terms right so in other words each term have nums I so we have I + 1 each term have nums I so we have I + 1 each term have nums I so we have I + 1 times nums I then minus so summation from num zero up to and including NS ey right so this part is nothing but the prefix sum so now if we look at the second row uh here all right so how many terms we have from index I + one up to index n minus one so index I + one up to index n minus one so index I + one up to index n minus one so we have this number of rows so n minus one so because the total sum is uh the total length is n so here we already have I + one uh terms so overall we will have I + one uh terms so overall we will have I + one uh terms so overall we will have nus i - one terms so here you know nus i - one terms so here you know nus i - one terms so here you know this is minus right n i ns i n z in other words we have a negative this number of um nums I and then we have uh nums I + 1 up to nums I so this is the nums I + 1 up to nums I so this is the nums I + 1 up to nums I so this is the summation nums I + 1 up to nums uh n summation nums I + 1 up to nums uh n summation nums I + 1 up to nums uh n minus one in other words the remainder right if you consider this one is a prefix sum um this will be the total sum minus the prefix sum so now let me do some more uh Al simple algebra right so let's count this one so here we have I + let's count this one so here we have I + let's count this one so here we have I + 1 so then I + 1 minus this one so we are 1 so then I + 1 minus this one so we are 1 so then I + 1 minus this one so we are going to have um uh this is uh 2 I right 2 * I so plus one negative 1 and 2 * I so plus one negative 1 and 2 * I so plus one negative 1 and negative that is two the minus n right so this is the number of nums I in this result and then what we have so here this is the partial sum right let's the parti sum we can use uh so this the minus one so it's negative 1 partial sum so let's see up to and include index I so this term is nothing but the total uh minus the partial sum the first uh I + one terms and then what we have uh I + one terms and then what we have uh I + one terms and then what we have actually is 2 * I + 2 - n * nums I then actually is 2 * I + 2 - n * nums I then actually is 2 * I + 2 - n * nums I then minus totalus 2 * partial totalus 2 * partial totalus 2 * partial sum up to and include the index I so this is our uh computational result so in other words we just need to have the uh partial sums and then we can do a linear temp complexity solution so with that said uh we can do the coding so it's actually it's very simple we just need to translate the above analysis into coding format and for the for this um for the use of understanding I will first come compute the partial sums actually in reality we can just use a running variable right so first I'm going to get n this is the length of this nums list right then um we can get the partial sum let's see just C partial let's say zero * n right so the first let's say zero * n right so the first let's say zero * n right so the first term is nothing but n zero right so then for the remaining term so we are going to for I in range one to n right so n is not included so what we are going to do is partial um so as the current index it equals the previous sum partial sum that is partial IUS one plus the current element and nums that is nums R right so with this done and also we can specify the last term will be the total sum so let's see total is nothing but partial at nus one or you can just write negative 1 right the last term so once we have this um preparations then we can do the result so you can use a pin operation or you can just specify a list n list but here I'm going to use a pin so then for I in range n right so notice that actually for this one due to the way we write this when I equal zero so this formula still holds right because part some zero is nothing but the first the item so what we're going to do is let's compute this one right so this is um so let's say total uh so here uh this should be total this is a plus right total minus two so we have total uh minus 2 * total uh minus 2 * total uh minus 2 * partial up to index I right and then we are going to compute this part 2 * I + 2 are going to compute this part 2 * I + 2 are going to compute this part 2 * I + 2 Min n times nums I once we got this one we are going to append right this to the result and finally we just need to return the result so this is a one way to solve this problem but before we make any further comments let's first do a test yeah it passes one example now let's look at the generic case yeah it passes all the cases so here actually for this problem the main thing is a partial sum so this actually very straightforward and uh another comment is this so here we specifically computed the partial sum but in practice uh you can do something like this you can uh see uh initialize a variable called the current partial sum right and then you do iteration and then each time you are going to increment that one maybe let's uh Implement one just to make it clear so here um let's see um we can do something like this let's see first uh total let's do sum of nums and uh then current sum so let's use nums um zero right and then for so let's um let's use uh let's use zero and then for current one so current is incremented by this nums zero right and then uh nums I so this partial I will be replaced by this current right and then we compute this one and then we return the result so now let's change this one to be version one so in this one actually we still you know use the V linear to compute as a total but then we use a running variable to compute the partial sum uh in the for Loop right so here we initialize a zero and then we first increment that right so this is just a one choice right so let's do a test uh here it's not right so let's see um nums of so here we have current increment not n zero n i so let's test yeah it passes one example now let's look at the generic case yeah it passes all the cases I guess um that's basically about it for this video and uh if you like the videos here and you want to practice more problems you're welcome to follow up our Channel and especially the different playlist within the channel thank you
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
250 |
hi guys um today i'll be doing this liquid question count unit value in the subtree so basically we want to count um the note if there's no child so there's no left and right trial we increment it by one so another thing is if the child and the parent has the same value we want to increment it by one yep so we will start by creating a integer count and we need a helper function because we are we will be doing recursion so helper we passing the route and we passing the count and we want to return the count at the very end the helper function is going to be boolean because it's just going to be true or false um is it true if the left and right is empty so okay let me just code this out we want to pass by reference we use the ampersand okay so if there's no left or right child we want to return true which is one okay then okay um so we are going to check for pulling left and right we are going to write the conditions here boolean result equals to we want to make sure that the left and right condition is met is it all yeah it's n so if there's no left child or if there's a left child we want to make sure that uh okay if there's a right child or a left child okay so there's no right child here so um i'm gonna like code this out before i explain because it's kind of hard to understand without just writing this out um root left okay so basically we are saying that hey um so is there a right child if there's a right child we want to make sure that the parent node and the child node is the same if this is true we want to add count plus equals to resistance because uh if blink resistance is true it's just going to be 1 and we want to return resistant yep i think this should be right yes thanks for watching
|
Count Univalue Subtrees
|
count-univalue-subtrees
|
Given the `root` of a binary tree, return _the number of **uni-value**_ _subtrees_.
A **uni-value subtree** means all nodes of the subtree have the same value.
**Example 1:**
**Input:** root = \[5,1,5,5,5,null,5\]
**Output:** 4
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[5,5,5,5,5,null,5\]
**Output:** 6
**Constraints:**
* The number of the node in the tree will be in the range `[0, 1000]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
572,687
|
83 |
what's up guys i'm xavier naidoo a hacker Winkley code encoding tutorials so please subscribe to my channel and check me out if you haven't already also a like on this video would help me immensely today I'm going over remove duplicates from sorted list so this is a pretty simple problem we just have to remove all duplicates so that you tell them it appears only once this is key right here yeah the element still has appear at least once so we just removed this one and this three so I brought it over I guess edge test case so if there's three ones we I should have it's going to we're gonna want to return one three so that's what we're gonna want to return so let's just jump right to this how would we solve this we're just going to well we're going to want to return head at the end since head is the pointer so let's create a list node called current instead of equal to head so this is what we'll edit and then we'll just loop through the linked list so wall current does not equal no and since we're gonna be looping through the list we want to make sure that current X cannot equal no because if current that X does equal no and we don't have that in there we'll get out of bounds pointer problem in Java at least so then we're going to check if current Val so we gotta check for the value equals dot next stop Val then current dot next equals dot next that's the next that's basically saying so if this is current next so if these two are equal it's saying set current in X equal to this so it's basically removing this one which is exactly what we wanted to do so else also current equals current dot next so let me explain this you have to put it in an else statement because we've the we have to account for multiple it could be multiple with duplicates not just one like this kind of makes it seem like so this makes this while loop kind of the else executes only when the valve does not equal the valves aren't the same so if we go through this let me scoot this over so we have current here current next well these two are the same so as you can see right here so we're gonna put move this over to here so this basically removes this so now this is current next and then it checks so we don't execute current equals current dot next because this executed that's why it's important to have the else in there and then so we checked it then there's still the same so it moves this one over to here so it basically removes this so now this is current out next and then so this doesn't execute again but now current dot next is still not no so we check one more time in this case we execute the else statement and current equals current so then we increment it and then head still pointing to the beginning of the list so that's what we return at the end and this should work hopefully from the first try didn't make any safe all right and that's it thanks for watching this is just oh man run time I believe it's over one space complexity because we're just creating a new node yeah so thanks for watching guys
|
Remove Duplicates from Sorted List
|
remove-duplicates-from-sorted-list
|
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List
|
Easy
|
82,1982
|
190 |
hey everyone today we'll be doing another lead code 190 reverse bits this is an easy one reverse bits of a given 32 bit unsigned in teacher and this is a very easy problem in which we are given unsigned integers integer 32 bits it's 32 bits and we have to reverse it and then return it and that's it so our easy way the most easy way i can find to do this is just from the end from the input just move to the left shift move to the right because we are going to avoid the very left digit any means step in each iteration and after doing this what we have to do is take it small by 2 take its mod by 2 min mod just a remainder by 2 and add it to our result and whenever we add it to our result we also want to right shift no not right shift but to left shift to the resultant and that will give us our result and to do that we will just take our results starting from zero for i in range of 32 because they are added to uh bit integer and for that we will just now like i said for resultant we will do left shift so this is right shift this is left shift by one and taking the modulo like this of the input value by do and adding it to our result like this so after doing all of this we will just left shift to no left shift but right shift by one to the our input and that will just uh give us the result and this was just bit manipulation if you know how left shift right shift and or we didn't use any and or but by shifting we got our job done and now i think it should work fine after resulting a result at res so let's see if this works or not this works let's submit it and that's it
|
Reverse Bits
|
reverse-bits
|
Reverse bits of a given 32 bits unsigned integer.
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`.
**Example 1:**
**Input:** n = 00000010100101000001111010011100
**Output:** 964176192 (00111001011110000010100101000000)
**Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**.
**Example 2:**
**Input:** n = 11111111111111111111111111111101
**Output:** 3221225471 (10111111111111111111111111111111)
**Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**.
**Constraints:**
* The input must be a **binary string** of length `32`
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Divide and Conquer,Bit Manipulation
|
Easy
|
7,191,2238
|
343 |
hello people today we'll be solving lead code daily equation 343 which is integer break and then we'll be moving to the step by step Java solution for it so the problem we are tackling today is about breaking an integer into the sum of positive integers to maximize their produ and we'll be given an integer n and we need to break it into uh K positive integers where K should be greater than or equal to 2 uh our goal is to find the maximum possible product uh which we can obtain from these K positive integers so let's move to the white board for the question states that for example if we are given um uh and say 10 okay so we can form 10 in let me increase the text size yeah so for example if we are given 10 we'll have to break this into at least K positive integer let's say 1A 9 okay the text is a little too big okay yeah let's say 1A 9 is one possible solution uh other possible solution could be 2A 8 uh other possible solu could be 4A 6 or let's say we can also have 2A 6 and we can also have 3A 4 other than this 3A 2A 2 and another one we could have let's say 7 comma 3 and we could have n possible solution so our goal is to find the maximum product which we can generate by breaking this integer n let's call it n into at least K positive inte into at least two positive integers so for example if we try to calculate the product of 1 and 9 this will give us N9 uh let's say for 2 and8 it will be giving me 16 similarly for 4 it will be giving me 24 and if I see for 2A 2 into 6 2 into 2 is 4 into 6 is 24 if I see for 3 into 4 uh I'll be getting 36 3 into 3 9 into 4 36 if I see for 3322 oh I'll be getting same result that is 36 and if I check for 7 into 3 I'll be getting 21 and we can generate n possible solutions but the answer would be this uh 36 as it is already given in the test case we can uh we can see here uh okay yeah we can see here this would be our output okay so uh let's move to the approach like how we have to approach this question okay and also apart from this we can also have one more observation like if we are having a number let's say n Which is less than or equal to 3 let it's a font size yeah okay let's say we are having a number uh let's say one for example for one we only have one possible solution to make this uh for oh sorry for one we have zero possible solutions because for at least making one we'll need zero and one at least two positive integers these both are will be required and this will give us the maximum product as zero for making two the answer should be one at least I'll be there are only two ways to form the sum of two which is 1 comma 1 and other than this uh other than this I can use 0 comma 2 but 0a 2 will give me a result of zero so we'll not use that if I go for three I can form three the maximum output which I can get would be two the maximum product which I can get would be two by using one and two if I try to use others for let's say 1 comma 1 this will be yielding me output as one so if I do this St here will be yielding out me output as zero and it will be yelding me output is one and if I go for yeah only these are okay we can also go for 0 comma 3 uh which will yield me output as zero yeah so from here we can make an observation that if we choose n Which is less than or equal to 3 we'll be getting maximum product is n minus one okay so this is a very important uh Edge case which we'll be facing as it is also one of the sample Ed cases where we have given n is equal to 2 so now let's move to the approach how we have to approach this question uh okay so yeah so firstly we'll handle the base case which we have just discussed that is if n is less than or equal to 3 we'll be simply returning n minus one okay so if this is not the case we'll be initializing a DP array of size n + size n + size n + one n + one and after that we'll be filling n + one and after that we'll be filling n + one and after that we'll be filling the values for dp1 comma dp2 comma dp3 because we have already seen in the test case that we'll be filling these values as 1A 2A 3 uh DP 1 will be assigned the value 1 dp2 will be assigned the value two and dp3 will be assigned the value 3 okay so now let's move to further so let's uh initialize a for Loop for performing this for I = to 1 2 Loop for performing this for I = to 1 2 Loop for performing this for I = to 1 2 I less than equal to 3 but we just simply do we'll do DP of I is equal to I okay so after this we'll be using another for loop from basically from four to n which will be given in the questions for okay so and the follow will initialize another variable let's say temp which will be our current I and then we'll use a for Loop for and J = 2 to I and then we'll check temp would be equal to Max of temp comma I into DP of I minus J yeah so I'll let you know in a few minutes like why we are using Max function over here okay so after this for Loop ends wait a second let's put this in basis yeah after the for Loop ends we'll just set DP of I would be equal to 10 and after this for Loop we'll be just returning DP of n so this is the sudo good for the question and if we try to see a test case for example where we are given n is equal to 10 let's say yeah so these are the indexes uh we here we have created a like you can see so here if you can see that we have created a DP AR of size n plus okay we have created a DP array of size n+ one n+ one n+ one so this will be providing us with 11 indexes starting from 0 1 0 up to 10 and for example we are we'll be having value for Z index 0 as0 only value for index one will be one so similary value of for index 2 will be two and value for index 3 will be three okay so up to this we have done now we'll be uh running the for this for n IAL to 4 okay uh let's see the form for this uh oh it's not okay so yeah for uh T yeah when I is equal to 4 yeah when I will initialize the temp variable with I then for I = for I = for I = 2 4 which is basically here four yeah so we'll be checking temp will be equal to Max of temp that is four or not temp array like yeah we use this CL for okay so here we'll be using a Max function because let's say uh at some point okay so basically what temp function will do it will what Max function will do for example here we are having I is equal to 4 so it will be we'll considering also considering the value that is 1 into 4 no sorry we will not be considering 1 into 4 but like zero yeah oh so the temp function will be considering like for example uh using some other way we have achieved a value of8 we'll be so we'll be just be continuing with the temp variable uh to keep a track of Maximum value and we'll what we'll be doing I into DP of num I oh here Al sorry here it will be it should be G yeah DP I minus J okay so uh this will be dating the value as I into DP IUS j i let's say I is 1 into DT of uh I 4 sorry I 4 - 4 - 4 - 2 DP of 4 - 2 that is basically second 2 DP of 4 - 2 that is basically second 2 DP of 4 - 2 that is basically second index that is one yeah that is one so here temp will be equal to four only uh if okay if we move to the next iteration where J will be equal to three okay say this is for JAL to 2 if we move Jal 3 we what we'll be doing 4 into DP 4 - DP 4 - DP 4 - 3 that is at dp1 we'll be having value as one and so temp variable will again be four only similarly we'll be doing the J will be running up to this only so now let's move to the next for I = to 5 yeah let's say I is equal to 5 now and now temp will be initialized to five uh now let's run a for Loop J = J = J = 22 5 yeah so here we'll what we'll be doing we'll be updating 10 for max value of 5 comma 5 into DP of 5 - 2 uh DP of 5 - 2 that is three so 2 uh DP of 5 - 2 that is three so 2 uh DP of 5 - 2 that is three so 5 - 2 3 so that is 3 yeah5 minus 2 and 2 three so here temp equal to 15 uh temp with y - 2 that is 3 and uh temp with y - 2 that is 3 and uh temp with y - 2 that is 3 and dp3 will be having yeah DP of IUS temp would be equal to 15 similarly we'll be running for all the test cases and now let's move to the coding window so first for the base case if n is less than equal to 2 N is less than we'll be simply returning n minus one and then we'll be initializing a DP in uh n + one for I = to 1 I Less Than = one for I = to 1 I Less Than = one for I = to 1 I Less Than = 3 I ++ DP I = I so after this then for and I = 2 4 L than = to n i = 2 4 L than = to n i = 2 4 L than = to n i ++ then we'll be initializing a temp ++ then we'll be initializing a temp ++ then we'll be initializing a temp variable temp isal to I for in J = 2 J L than in J = 2 J L than in J = 2 J L than I j++ then temp will be equal to math do I j++ then temp will be equal to math do I j++ then temp will be equal to math do Max 10 comma I sorry I guess I've done a mistake here it should be yeah uh here it should be basically J into DP of I so we'll be similarly we'll be updating here only yeah so here it yeah so the test yeah that's why it was given here a wrong answer let's have do this J to DPO and minus G yeah and here what we'll be doing after this for Loop we'll be just doing DP of Y would be equal to 10 and at the end we'll be returning DP and uh yeah return DPN so I guess this should work yeah this works so yeah this is accepted so this was the solution thank you
|
Integer Break
|
integer-break
|
Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers.
Return _the maximum product you can get_.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** 2 = 1 + 1, 1 \* 1 = 1.
**Example 2:**
**Input:** n = 10
**Output:** 36
**Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36.
**Constraints:**
* `2 <= n <= 58`
|
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
|
Math,Dynamic Programming
|
Medium
|
1936
|
399 |
hey what's up guys this is john here again so uh so this time i want to talk about uh today's daily challenge problem uh which is number 399 evaluate division and okay you're given like equations in the format of a divided by b equals to k where a and b are variables represented as strings which is this one the first one and the k is a real number floating point number basically you're given like a different a few equations here and then it asks you to calculate each of the queries here okay basically you know and if there's no if the answer does not exist return minus one okay so a divided by b right a divided by b equals to 2.0 which right a divided by b equals to 2.0 which right a divided by b equals to 2.0 which means that's like a to b is 2.0 and then b to c is 2.0 and then b to c is 2.0 and then b to c is like what is three right now the it asks you to calculate the a to c okay basically you know the a to c is like six right because the a to b is two and b two c is three so which means two times three it's six and then the next one is b2a okay so it's kind of reverse so b2a is like a one divided by two which is 0.5 which is 0.5 which is 0.5 and the next one is a to e so the e that does not exist okay which means it's gonna that's why this isn't the minus one and also a to a okay so a is divided by a which means it's equal to one and x is minus one okay so uh yeah i think it's because a is in the equations and x is not so basically if they are the same and the one and it's not in the equations so then we return minus one otherwise we will return one okay cool so basically i mean this one is like i think it's a classic like graph problem you know basically uh you build the graphs based on the equations here with the weight right the weight is like this it's like the k here but you build you need to build it uh like bi directions right so a to b is two b to a is it's uh one divided by two because we might uh we might need to calculate from b to a okay and once we have the graph here so for each of the queries here we have a basically the first element is our start okay and the second element is our target and we just need to find the target by using uh by using like a dfs search right and while we're doing the dfs search every time when we have a new node we're gonna like uh multiply with that value so that we can get the final answer here and since uh since it says that you may assume that evaluating the queries will result in no division by zero and there's no contradiction means that from a to c there's only one path so we don't have to worry about if there's any other path like from the e to f and then finally in the end we get to see we which so we can assume that i mean there's only a unique path from this uh start to the target so that we can safely uh just do a our dfi search in the graph and the last one is this one basically if the uh if they are the same and if this one is in the graph then we return one otherwise we will return minus one cool so i think that's pretty much what it is okay let's try to view the graph first okay so the graph is default dictionary uh list okay and then for i and then the next one is u and v okay from uh in enumerate okay enumerate the equations so graph this u dot append and v equals to k equals to uh okay values dot i okay and the other a reverse edge is like this right we build a add from v to u and where uh whose value is one divided by the values of i okay now we have the graph here all we need to do is just to populate our answer by uh by from and two right from and two we have a crease okay in chris e-r-i-s okay chris e-r-i-s okay chris e-r-i-s okay and then uh since we do a dfis i'm going to use a q here so the q is going to be uh the from first uh yeah so from and under one okay because we you know since we are restoring basically two values right basically the evaluation so the evaluation the values of the evaluation of the current node at the beginning the value will uh will be one things will be uh we need to we'll be uh multiply the values later on so that's why we start with one here and uh don't forget to create a set here because uh we need to remember which node has been visited otherwise will be and we'll be stuck in the infinite loop here and so uh while q okay we have a current node and then we have a value okay uh equals the q dot pop okay and if the note is equal to the target okay then we simply uh append the current value to it otherwise we find the neighbors okay find the neighbor in uh graph dot nodes okay and then uh if neighbor not in visited okay right then we just do a we insert we append to the end of the queue here by uh we append this neighbor uh is the value which is the value is the uh oh yeah so when i when we get the neighbors we also get the i mean the weight on this edge here right to get to this neighbor which is the v here so we have a value times v here or we can call it i mean factor let's call it factor here okay cool so and we also need to add this the neighbors right to the visited stat here so and in the end we simply uh do a answer dots appends no we have already done that okay but then let's handle this minus one case so um i mean if we never seen the target node here right we need to return like we need to set to minus one so in that case uh i'm going to define like a hash answer in the value here so at the beginning it's true it's always true right so sorry at the beginning it's always false and if we see a number here right and then we uh we set this one to true okay otherwise we are basically if not has answer and we just uh it means that we haven't seen the we haven't add append the values to the answer here so we now we append minus one here okay so this should just work i think yeah let's try to run this code cannot sign to function cost oh god what am i doing here okay um we're assigning a tuple here okay man what i miss what am i thinking here ah here okay neighbor yeah okay another toppo here oh sorry okay i think i forgot to handle this case here because you know for the aa here this while loop can handle that because uh yeah because the a will see will meet its own target here right but with x axis here we're assuming we x is also valid but it's not based on the problem here so basically we need to do this uh if right if f equals to t and if f not in the graph okay then we just do our answer dot append minus one okay else we can just do the do this right cool so i think this should work ah uh yeah because you know we're covering now we're also covering this aa case here so uh yeah where i basically were skipping this aa case else answer dot append one yeah i think this should okay submit so it's accepted all right cool i mean that i think that's it for this problem is it's a classic like a graph problem you know um not too much to be talk to be talking here basically we just built like graph based on the equation here first but remember be careful here we need to build the edges i mean on both of the directions since uh from this equations we can get a divided by b and we can also get the value for b divided by a and once we have the graph here all it's left is we for each of the queries here we just need to find i mean basically the total amount of the weight right the products of all the weights from the start node to the target node and here it's just like a little bit like uh handling for this uh for the same for the nodes that have the same values here right and then in here we just use it like an answer to check if we have find the answer for this queries otherwise minus one uh and space and time complexity right i mean here i mean this is pretty straightforward right i mean this is like the let's say this is m the length of this is m and here is the length off and here okay because this is also m right so and the queries end here so we have like a what's the yeah we have a like uh here is that of m okay and here uh here's we have a o of n times uh from unto basically this o of n time times m the equations right basically you know this is the o of timers and time o n times m because the worst case scenario is that we need to for each of the queries here we need to loop through the entire graph to be able to find the final answer okay so that's the o n times m and the space complexity is so here we have a this is a time so this is a time and a space so the first part this is like the uh o of m and second part is uh we have a q here and for each time we have a q and we have visited right so this part is also like uh o of m here so for the space complexity it's like basically the o of m okay cool i think that's should be everything i want to talk about for this problem yeah thank you so much for watching the videos guys stay tuned see you guys soon have a good night bye
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
1,737 |
hello friends today i'm going to talk about the difficult 1737 change minimum characters to satisfy one of three conditions you are given two strings a and b that consists of lowercase networks in one operation you can change any network in a or b to any lower case networks so your goal is to satisfy one of the three conditions the first condition is that every networking a is literally less than every letter in b in alphabet the second condition is every letter in b is slightly less than every letter in a in the alpha alphabet the zero method is both a and b consists only one distinct letter so you have to return the minimum number of operations needed to achieve your goal here and two examples and let me explain these questions so here for example we have an example one a apa with caa so we will have to change it um if we want to satisfy the condition y or condition two we have to change the networks you know a and b so um for example we can change it uh changing change b to c then every network here is smaller than c but right so we have to do the two operations and if we want to satisfy the condition too so we have to make uh the b is slightly less than a so we can change this b for a and the change in change the changes say a to aaa right so this satisfies the condition tool and if we want to uh satisfy this condition three continuously description is a little mis misunderstanding for the distinctions i think maybe we can just delete this thing so it means only one letter one special letter here so either way can change that so change it to this would be b or a i a that is this there is only one operations or we can change this is a only validation so is here is 2 and for here how many operations here is 3 so the answer is 2 amount of them which is the minimum number of operations and another example is this example t-a-p-a-t-d t-a-p-a-t-d t-a-p-a-t-d t-a-p-a-t-d with cta so while operations that is we can we find that all the uh numbers that is u4 y1 is smaller so we can changes is to see even one to satisfy the condition one so we haven't changed it only changes b so it's the answer is three here and if we want to uh certify the condition two uh well you can change this is where i need to change this d so this is a new changes is c here if you say here is d you will see here c a c so it's how many one two three four this is b so three plus two is five operations and if we want to make them um to satisfy the condition three for the continuous three we have to make them all the has the maximum number so here is dtt so it's also more than three so bigger than three so we have to submit so the answer for this uh is this part is this three the minimum number of operations actually if um for the source for the naive solution that we have to compare this is usually characters in a this is characters in a and compare every network with b and then we decide whether we need to uh to change the networks and to make satisfies the clinician one and also we need to uh to tell us the average nitrogen b to make sure every netherlands in b is and it'll be we do with every networking a to make sure every network in b is bigger than a so the way these two loops we can select they can get these answers for condition one and it's the same for the clinician tool we also do the two loops and for this conditions we do not need to for loops and for loops we only use again the maximum number of the occasions um the letters here and there's a length the total lengths minus the maximum number of occurrence of one letter so this will takes all m times and complexity if m is the length of a n is an angle b so is there any better solutions or second idea we will actually we can observe that um clear condition one and with condition two korean one with and the condition tool actually are similar because we can switch the input parameter sorry switches on the input parameters here so make the a less than b actually is similar as making the b less than a so we have only considered two conditions how we can make a and make a smaller than b actually we do not need to consider how to switch assume we have a network here is a whereas uh p network is here in cc we can find that there's always a bundling line between this between a and b if they are already separated so here this boundary line is b nettle is the metal now here if we change this the e there could be b network and or b or c nato right so we have we can traverse from the a b move to knowledge to start from a we start from b to z letters and check how many nettles in a is bigger than this is this center uh maybe called center letter our kind of harmony in b is smaller than this bound and then we get the sum of them this is the counter of how many oppositions for one boundary network so we have to get the minimum of operations for all the band metal so this in this way so we can solve this problem with o m times n times 26 so it's a constant so it's just om time f o m plus n time complexity and for the condition series because we just get the length a plus and angle b we when we mix them together actually and the moles that are the maximum occurrence of our vanetta and this then we get the smallest uh the number of operations let's write the code here so first way and to find the operations for one two operations a and b here and for y and b operations we can get her way that was from make we get uh we initialize our answers and so count is length a plus and length b and we tell us from the b to z we use a number of terrorists and we get the bond letter bond equal to binary is r plus or rd a and uh we can initialize code so then we'll use two loops in a and b if this the letter is bigger than the bond then we get the count plus one and for c i be if the cr is some smaller then the bound we get current increase by one and then we return the smallest of this all these operations so they will return us so this is the operation one two and then we define the observation for the condition three and further conditions we use a condition dictionary from python counter so they define the characters and they mix them together and counter a plus account b and we get a counter a plus b minus the maximum accordance okay we have finished the operation one two then we just call them together the minimum of them so operation vision one two a b operation b a let's check the code connections is something wrong creations okay let's check his other test case okay that's it thank you very much for watching see you next time
|
Change Minimum Characters to Satisfy One of Three Conditions
|
maximum-nesting-depth-of-the-parentheses
|
You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**.
Your goal is to satisfy **one** of the following three conditions:
* **Every** letter in `a` is **strictly less** than **every** letter in `b` in the alphabet.
* **Every** letter in `b` is **strictly less** than **every** letter in `a` in the alphabet.
* **Both** `a` and `b` consist of **only one** distinct letter.
Return _the **minimum** number of operations needed to achieve your goal._
**Example 1:**
**Input:** a = "aba ", b = "caa "
**Output:** 2
**Explanation:** Consider the best way to make each condition true:
1) Change b to "ccc " in 2 operations, then every letter in a is less than every letter in b.
2) Change a to "bbb " and b to "aaa " in 3 operations, then every letter in b is less than every letter in a.
3) Change a to "aaa " and b to "aaa " in 2 operations, then a and b consist of one distinct letter.
The best way was done in 2 operations (either condition 1 or condition 3).
**Example 2:**
**Input:** a = "dabadd ", b = "cda "
**Output:** 3
**Explanation:** The best way is to make condition 1 true by changing b to "eee ".
**Constraints:**
* `1 <= a.length, b.length <= 105`
* `a` and `b` consist only of lowercase letters.
|
The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )
|
String,Stack
|
Easy
|
1208
|
1,734 |
hi guys in this video we are going to discuss the problem decode X Art permutation which is from lead code so the problem statement states that we are given an encoded array of size n and the N is always even so uh this encoded array is generated using this formula which is encoded of I is equal to form of i x r Prime of I plus 1 and it is said that the perm array is always odd in size so you'll have a odd size for Pump and the perm has always has first n plus 1 natural numbers that means for example let's say you have n equal to 2 this is the size of encode array so the size of the perm is going to be n plus 1 which is three and the elements are going to be either one comma 2 comma 3 or 3 comma 1 comma 2 or 2 comma 1 comma 3 or 1 comma three comma two and so on all the permutations it could be any of these so that is going to be our perm array but the elements are going to be the first n plus 1 natural numbers right so at last we are supposed to find uh the perm array we are given encoded array but we are supposed to find the Palm array so for better understanding let's take an example so here we are given encoded as three let's resist to okay we are given encoded 3 and 2 so how this goes see this is I am taking for just unders understanding purpose this is not given okay so here the 3 is generated by performing xor operation on two and one that is 2 x r 1 gives you three and this tube is generated uh by performing xor operation on one and three so that is how we are going to get this encoded array so our task is to find the perm not the encoded encode is already given uh now this becomes tricky because you are given an output actually but you are supposed to find the input and you download the order of the input so let's see how we can solve this problem and remember that encoded size is always even and palm is always hard let's quickly move on to the solution uh so we are given this uh formula that encoded of I is equals to a pump I xor pump I plus 1 so I like to make small changes to this formula to get the desired results so what I'm going to do is I'm going to replace IE with I minus 1. so this becomes uh encoded I minus 1 of I minus 1 xor pump I right and now I am going to xor perform xor up I minus 1 on both the sides so now this is going to be like I minus 1 xor here that is encoded I minus 1 so when you do perm like you have perm I minus 1 and per minus 1 they both get canceled so you'll be having only this one so this is going to be bomb right okay I hope you know the basics of XR so uh please do check the basics of XR before watching this video so the end result then formula that I wanted you to show uh is this formula which is sperm I is equals to a n i minus 1 xor Palm I minus 1 so using this formula you can get the perm array actually uh the problem is that you are you have the encoded array so you'll get the values for this but the problem is you don't know the value of I minus 1. so for example let's say uh let's take I equal to 1 so the form of I that means one a n it is going to be I mean 0 xor P of 0 you know this value you don't know this value so only if you know this value you can proceed further so this is going to be the entry point for the solution you have to find the first element of the perm array first element of palm so when you know the first element of 1 it becomes easy for you to find the other elements for example P equal to 2 it will be n of 1 use the formula P of 1. so from the above statement you can get the P of 1 so you can apply directly then you can get P of 2 and P of 3 and so on so the entry point is that you have to find P of 0 that is the first element of I hope the you understood how I arrived at this formula and how I am going to start with P of 0 that means the first element so let's see what we can do to find the P of 0 so I am following these two steps to get the first element is uh the first thing is that you are supposed to find xor of all Palm elements so how do we find that because you do not have Palm elements right you do not have perm array but in the question it is said that it is the uh n plus one natural numbers right the pump array is the n plus one natural numbers where n is the encoded size so let's understand this approach by taking an example so let's take n equal to 4 and encoded is six five four three this example is already given in lead code I'm just elaborating it so what are we supposed to do we are supposed to find xor of all Palm elements uh we do not know the permanents but we do know that the elements are going to be the N plus 1 natural numbers where n is the encoded size right so here the size is in 4 so we need first five natural numbers okay what are those one two three four five you know to find xor you do not need the order so you can find if even if the order is different right so this is the first thing we are going to store xor all so that is going to be 1 xr3 4 and 5 right this is the first step to find the first element of perm like you do not know the order right so only if you know the order you can find the first element uh like the one could be anywhere in this uh Palm array right so to find that first element we have to perform these steps and the second is going to be find the xor of all except one we are supposed to leave the assume that the x of the power is going to be x y z is 5 right this is sperm so we are supposed to find the xor of the last four elements leaving the first one in order to get the you know first element but how do we do that we do not know the elements it could be any of these five elements in the four elements right how do we do that we can find this xor using uh the encoded array because see uh encode is generated like this right x y z a and a b right so uh this one leads to this right so how do we find the xor of all except the first one so what we are going to do is we are going to start from this point in the encode array and we are going to perform xor on the alternate elements like leaving this one I am going to perform xor on this element like this one life if the size is more than you know let's take you have 10 elements in encoded then you'll get c d e uh my next xor will be on this one just leaving the next one I am going to perform on this one so I'm going to perform the xor on the alternate encoded elements starting from the this point that means the first in I mean one index so you'll get this one like see xor except 1 equal to y z and a b right so indirectly you are getting this XR right so this is Bond we wanted to achieve so you got it and the xor of this is going to be xor x y z A and B right so this one we have already achieved using the first step right we just do not know the other order but we are getting x r so these are the two steps that are very crucial I hope you understood if you did not understand please go back to the same video and play this part so once you once we found the first and second steps what we're supposed to do is the P of 0 is definitely going to be xor of all elements and x r of all elements except one like if you see that xor of all is going to be x y z a b and xor of y z a b so when you perform this operation uh using the xor property two elements XR is zero so I am canceling it out a z one a gone BB gun so it'll be finally left with X this is the first element in our Palm so you are getting the first element as we wanted to right I hope the approach is very clear so let's try run this using an example so here I am taking the same example let us there in the lead code so the first step is to find the xor of all are which is the palm elements XR so we do not know the permanent so what are we supposed to do we are supposed to use the property that is already given in the question that is uh finding I mean the elements are going to be n plus 1 natural numbers so the N plus 1 natural numbers means four plus one that are first five natural numbers which is one xr2 we do not know the relative order so for xor we do not need it so this is the first thing we are supposed to do the second thing is find the xor of all except the first element so that is as discussed in the approach we are supposed to start with this element leaving the next one go for the this one like we are leave we are finding the alternate xor's of the encoded array starting from the index one that is 5X or 6. but we know that 5 is the xor of 4 and 1 and 6 is xor of five three right so this is I am just expanding it for better understanding of why we are doing this so third step is going to be finding the first element of uh the Palm peace Palm so the formula is xor of all so xor of all except one so xor of all is going to be 1 2 3 4 5 and xor 4 1 5 3. so is it similar elements get canceled out that means are they become 0 index are one gone three gone four gone five is also gone so clearly the first element is that is 2. in the primary so using this we can generate the other elements right so P of 1 is equals to as we've already seen the formula 0 xor B of 0. we know that this is 6 right 6X or 2. so it is going to be 4 and P of 2 is going to be in 0 1 and 1 P of 1. so N1 is 5 xor 4 so it is 1. so P of 3 so similarly you'll get all the elements the next element is going to be 5. and the last element is going to be uh three so this way we arrived at what we wanted that P is equals to 2 4 1 5 3. I hope the approach is pretty much clear so let's uh move to the code which is in this e plus so this is the C plus code so initially I'm taking an apartment to store the Palm values we know that the pump size is uh plus one of the size of encoded so that is this first one and we arrived this formula at term y equal to my minus 1 x r and go to a minus 1. so initially M the first step xor of all so we are finding xor all of starting from 1 to pump size which are the N plus 1 natural numbers you're getting at this step and next the second step is going to be Excel of all except one so I am starting at the index 1 of the encoded and I am finding the xor of all the elements in the alternate positions so that way we can get xor except the first element of the pump this is the second step right the third step is going to be the finding the first element which is xor of all and this xor of all X1 right I'm assigning it and then I'm finding the values for the rest of the you know elements so this way I found the solution and at last I'm returning the palm so let's see if this is running or not yeah yes it is running so that is what I wanted to tell and thank you so much for watching this video If you like this video please do share subscribe like comment
|
Decode XORed Permutation
|
bank-account-summary-ii
|
There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2]`, then `encoded = [2,1]`.
Given the `encoded` array, return _the original array_ `perm`. It is guaranteed that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[3,1\]
**Output:** \[1,2,3\]
**Explanation:** If perm = \[1,2,3\], then encoded = \[1 XOR 2,2 XOR 3\] = \[3,1\]
**Example 2:**
**Input:** encoded = \[6,5,4,6\]
**Output:** \[2,4,1,5,3\]
**Constraints:**
* `3 <= n < 105`
* `n` is odd.
* `encoded.length == n - 1`
| null |
Database
|
Easy
| null |
173 |
welcome back to the channel today we are going to discuss solute code problem 173 binary search tree iterator so the problem statement says that implement the bst iterator class that represents an iterator over in order traversal of binary search tree so bst iterator tree node root so this is the constructor so initializes an object of bst iterator class the root of bst is given as part of constructor the pointer should be initialized to non-existing non-existing non-existing number smaller than any element in bst and it will have two methods has next and next so has next should return true if there exists a number in traversal to right of the pointer otherwise it should return false and next moves the pointer to the right and then returns number at the pointer so they have given one example here uh and so we will be for example uh we will be given the uh root and uh these nodes actually so we can construct a uh binary search tree and it will be like so it so for example this is the same example i'm giving so one thing we have to understand here is the in order traversal they are talking so if we have a node like 3 7 and 15 so the in order traversal will be in the order like 3 and then say 1 and then 15 so it will be like in this order so it will be always like a sorted basically uh so for example the in order traversal of this tree will be like first 3 then 7 9 15 and 20 so the numbers will be in a sorted order so for example uh if you see next year then the next means first time the next one will ask the first time next will return three so that's what you are seeing here these three then again when we call next then it will give the second number which is say one in the order period so sorry so say one in this order so you will see seven here then when you call has next means whether any existing any uh remaining nodes are there which are larger than say one so yes we have three nodes nine fifteen and twenty so we will just return true here for has next and next means we will return the next larger element which is 9 so you will see 9 here and then again has next means do we have anything remaining elements we have 15 and 20 remaining so we will return true for the next we will return the next element which is 15 so you are seeing 15 here then for has next you are seeing true because we still have a 20 remaining and for next you are seeing 20 element here so we will return the 20 and for the has next we don't have anything remaining after this so we'll just return false so we have been asked to implement this binary search tree iterator class so let's just discuss quickly the implementation so i am actually going to use a priority queue class from a java api which is kind of a min hip or max he depending on the order we choose so here we will be using min hip so always when we have elements into this priority queue they will be in the order where minimum will come first so in the iterator itself i will pass a route and i have implemented this iterate method which will actually populate the priority queue uh using recursively so it will take root left and root right and it will iterate through the complete tree and it will populate the priority queue in the uh way like you know incremental way like three then seven then nine then fifteen then twenty uh and whenever when i am implementing a next method i'll just check first if it is not if the priority queue is not empty i'll just fall and i'll return that element otherwise i'll return minus one and for a has next i'll just make sure that the priority queue is not empty then i'll return a true if the priority queue is empty then i'll return false so this is a very simple implementation for the binary search reiterator so i have created the same test case that they have given us in this example so let's just quickly give it a run and make sure this works yeah so it's working correctly so we can try submitting this yeah so the solution is accepted so if you like this solution uh please consider subscribing to my channel and give a like to this video thank you
|
Binary Search Tree Iterator
|
binary-search-tree-iterator
|
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST):
* `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
* `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`.
* `int next()` Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST.
You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called.
**Example 1:**
**Input**
\[ "BSTIterator ", "next ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 3, 7, true, 9, true, 15, true, 20, false\]
**Explanation**
BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `0 <= Node.val <= 106`
* At most `105` calls will be made to `hasNext`, and `next`.
**Follow up:**
* Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?
| null |
Stack,Tree,Design,Binary Search Tree,Binary Tree,Iterator
|
Medium
|
94,251,281,284,285,1729
|
101 |
Jhal Hello Everyone Swam This Video Were Going To Discuss Problem Symmetry So Let's Move Ahead And See What Is Problems And How To Solve This Problem Will Give With The Root Of Every Like Will Complete Three Do Subscribe My Channel Subscribe Must Subscribe And Like This Channel This Is The Mirror Image Consider When They Talk About Rituals Are Different From Here For Semester And Not Wick And Tools Which Can Create That A Line Of Symmetry Benefits Rotator Image Like This Easily Create This Line Of Symmetry Lately Say BBC And Difficulties Image bad line of symmetry you 'll straight welcome over also ansy welcome and dey swift that's 'll straight welcome over also ansy welcome and dey swift that's 'll straight welcome over also ansy welcome and dey swift that's the president showpieces medical shop friendship is bread diner symmetry swift super impose subscribe and subscribe the Channel symmetry root to determine the way tree to bay seen its subscribe diy ocean * Welcome and this * Welcome and this * Welcome and this 250 welcome over this point and then I will come to Vardha Stree for welcome to know the discovery symmetric pyramid center which one will remain in the hearts of life I take the example you can see but you will super impose to good Rotating JIS Binary Resting the Line of Symmetry When This Tool Super Impose It's Two Three Lilium Like This One Between Note Super Impose Woman Sudhir Valedictory Folding Subscribe to this Channel Welcome to subscribe and subscribe the Video then subscribe to the Light of the two Distance From This Point Distance From Line Of Symmetry Similarly Destroyed But You Can See A Meanwhile To End Destroyed Evidence On The Lines Of Symmetry This Note Three Layer Pendant Three Layer Dividend Under Line Of Symmetry Benefits Symmetric Channel Subscribe And Remove All Its Root And Shatrughan Train Udaipur Liquid Call Me To The Video subscribe The Channel 's God Will Return True Love 's God Will Return True Love 's God Will Return True Love That If This Is Matric Mandatory To This No When Everyone Like This So After The Root This Hair Ko In The Left A The Sun Will Reach To This Not Influential Amir with his left vehicle to this right to food can come to know what is this point at images to know when they here and fearing to others like this how to right some land near that Vikram Pardes Values and Vinod this that Vikram Pardes Values and Vinod this that Vikram Pardes Values and Vinod this point doctor cemetery I am of Voters Right The Mirror Reply This Point From Left Hand Witch To 9 4 6 And Its Values From Sun To Pluto Hand Witch To 9 4 6 And Its Values From Sun To Pluto 323 324 Note Sid Mein Ranbir Veer Subscribe To Channel Not Have A Welcome To The Pile Symmetric Every One Property To Remember This Year And Share To * * * * Year And Share To * * * * Year And Share To * * * * Video Subscribe A Ajay Ko That Flat Se Per Given With The Spinal Tree And They Need To Check Were Its Center Or Not So Well Call This Method Symmetric Passenger Route Look Like This Point To The Return Shoulder returns through off the day use this channel tree and others not the guardian is subject to Uttar Pradesh condition 250 crore tsp you develop s one to front will oo status word seervi vo latest shabbir what will be the first subscribe The Channel Please subscribe and subscribe the Channel Ko Like This Morning No one of the property of this line of symmetry use flats in this site is still going to right The mirror images were going in this direction and similarly in this direction in the middle name the two Kal Swimming AP Login Button Mirror Image Dravid To Support This Two Industry As Well As Free Mode On Decided To Withdraw All In This Direction Loot Right Side Mirror Thursday Subscribe and subscribe the Channel Please subscribe and subscribe the Channel Ay Panasonic 2012 That Develop The Right Dynasty That Henna Sign * And To Go Loot Softer Getting Any One * * * Compare Loot Softer Getting Any One * * * Compare Loot Softer Getting Any One * * * Compare List Sunao Fasting Changes Boys To Bottle Tap The Same Time Not Boys Nurses And Will Continue With Child Line Of Symmetry December 21 2009 Channel Subscribe Now To That In This Condition Is Very Important Because She Will Directly Return Forms And Avatars And Not Sure Which Gives Video Channel And Equal To The Missions Channel Ko Subscribe Our Channel Video Channel Ko More Channel Subscribe and Share Thank You 112 This two is actually equal to and well this condition of two souls which proves that this point 4875 has happened no what we do it is a pun in the garden checking is two notes in one and does not Produce Is Want To Protest In The Tree To Figure Out The Elements From This Point To Three Creditor Mirror Image 09 2013 Hai To This Is The First Not Like This Is That First 10 Minutes Upvote Pears Sop Important Compare With Animals Life Without Food And To right leg, this point, to right, this is a free app, because of this, second happened under, will put animals right channel, which is not long, will push and who's left, which is the mirror image of animals right, listen welcome like this is that this is the Fourth Pushp Hai Alarm Set Is Note Mp Aur Sunao Will Appoint Players And Will Come A Day When Will U Stand Up For What Nalla Provident 40 Loot Bill Point To Entries Left Like This An Unknown Willpower More Element Which Three Languages And Was Right Languages And Was Right Languages And Was Right 12.2018 Like This Is Hai To This Vacancy Directly Comparing The Mirror Images Not Computing In One And Two Vijay Obscene Symmetrical Notes A Cross Line Of Symmetry Swain This Channel And International Simply Continue Channel Subscribe Will Continue Till E Will Power Lord Witch It Tubelight And Sunao Annual Point To Entries right with this note subject to willpower note witch animals left ventricle point two animals looted a noble saintly compare m30 consider using stack data structure witch point elements in prayer and reflection secretary radheshyam line of symmetry deposition in node in the left side and the mirror Image Opposition Radhe-Radhe-Radhe-Radhe Video 999 9999 and 12323 returned to subscribe Free word is condition is a sweet means the this point the trees are symmetric on me unwanted wipfan the same steps on this node and is not software position was left to animals loot like this A Fear Will Ask Animals Left Were Going To The Left From This Thank You To Take Its Corresponding Note Inside Right Side Like This They Are Putting Into A Fight With Sonal That General Posture Advance Right What Is This Channel That And Corresponding Love You To Post And Whose Left like this pack note mp e will pop design value witch adams left side to annual come to absolute law co like this e will stop this channel special 1872 welcome to previous and was right were which hair torch start can see in one is equal to Null And Musical Tour Null At The Same Time The Future Will Simply Continue On A Stand Still Not MP3 Or Sunao Willpower Nurse Software Point To Write A 500ml Point To Previous And To Right Which Is This Is In Help This Channel Also Which Animals Loot Supreme Person Who Shares It's Life Is This Point To Prevent Loot International Nurses Subscription Will Simply Continue On A Specific Additional And National At This Time Tribunal Is National Cemetery Specific It Means Darkness Notes In The Retreat To Traverse Through Setting Close Loop Line Of Cemetery This Channel Subscribe Now To Video And A Routine Articles Will Post Roots Light On This Side Along With Roots Left Which Is The Mirror Image Of These Nodes In This Site Map How To Belkum Jai Hind Is To Belkum A Star Is Not Empty E Will Pop Up To from the tay n0 like this is a will to another to that encounter 212 like this is to edward snowden to internal and does not equal to mail message condition comes to give false en-us roti to internal and external en-us roti to internal and external en-us roti to internal and external and 122 is equal to do It Well And Simple They A Sister Was Left With The National Holiday This Point Christmas Tree And For This Is Not And Did Not On Thursday Turn On The Subscribe To Switch Under Ironing Were Pushing Advance Right But Ironed For And Its Corresponding And Whose Left Leg This Is The Strike Is Not MP E Will Pop Null Entries Left Side Welcome To Absolute Law Which Hair A Well Pose Reel Which Animals Right Point To Go To Animals Right Leg This Is The Festival Null And Doesn't Equal To One Of The National Monitoring Comes To Know You Can See Me To Play List Notes And Subscribe Boys Channel Radhe-Radhe Video Boys Channel Radhe-Radhe Video Boys Channel Radhe-Radhe Video National And International Terminal In The Written For Ingrazo subscribe The Channel Please subscribe and subscribe the Channel You Must Like Video In This YouTube Channel Please subscribe To My Channel and press the Bell Icon 10000 update thank you
|
Symmetric Tree
|
symmetric-tree
|
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
**Example 1:**
**Input:** root = \[1,2,2,3,4,4,3\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,null,3,null,3\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Could you solve it both recursively and iteratively?
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
98 |
Jhaal Hello Bhai Welcome Tel Garm Kund Aisi Udayveer Victory In This Question Thursday Video subscribe and subscribe the Channel and subscribe the Hain To Is Seervi Subscribe Must Subscribe Now To 7 Questions Page Subscribe That Redmi Ignore Just Compare Value To The Root Not give the best wishes in the subscribe and subscribe the Channel and subscirbe media will not do hain instant and value ke pad se na aadha long midi naman hain aur fritters indore range baikunth valid value and need to check the left android 9999 ki naren jo Nav Vikram not well to end the were not Indore range simply return for wealth will not do this the rupee will fall in love with us that Sudesh complete supporting and in this code main here twelfth physics sample let's taylor swift do sacrifice will so it's working Like Share Subscribe Karo The Indweller 7 That Inst Of Defects That Is To Give False Cases Not In Line With The Benefit Condition Swift Code That Don't Submit Successfully Vitamins Places Of Editing Or Every Day And Also In Odoo Maintain Subscribe To
|
Validate Binary Search Tree
|
validate-binary-search-tree
|
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
A **valid BST** is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** true
**Example 2:**
**Input:** root = \[5,1,4,null,null,3,6\]
**Output:** false
**Explanation:** The root node's value is 5 but its right child's value is 4.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1`
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,501
|
269 |
hey everyone in this video let's take a look at question 269 alien dictionary only code this is part of our blind 75 list of questions so let's begin this question is actually a premium question that's why we're doing it on this website lint code and why the number here is different but otherwise the question the test cases and the solution should be the same let's take a look in this question there is a new alien language which uses the Latin alphabet which basically means they use the letters a to z however the order amongst the letters are unknown to you receive a list of non-empty words from receive a list of non-empty words from receive a list of non-empty words from the dictionary where two words are sorted lexographically by the rules of this new language derive the order of the letters in this language Okay so what exactly does this mean well what it means is that we're given a list of words at minimum two because we need at least two in order for us to like even Define any sort of order so we need two in the minimum and now what well we can assume that each of these words will contain alphabetical letters from A to Z but the order does not match the English order for example in this example that we have over here so let me go ahead and paste this in and again we use this website to do our premium problems in this example that we have over here really the order is w-e-r-t-f which means w comes before e w-e-r-t-f which means w comes before e w-e-r-t-f which means w comes before e in the dictionary EB e comes with 4r in this dictionary Etc so in this in the English language it's obviously not like this but in this one it is okay so now let's take a look at some of the key pointers here so first of all you can assume all the letters are lowercase okay I think that's all fine the dictionary is invalid if a string a is prefix of a string B and B appears before a and if it is invalid we want to return an empty string essentially what this is saying just to kind of make it extremely simple is that let's assume we're in the English language right and we're going through a dictionary we would never expect that something like a b come before a in the dictionary we would never expect this right because in the dictionary we would have for example a and then we might have like uh maybe like a b and then AC Etc right we might have something like this but we would never expect a b to come before a similarly maybe we have like a b c and then later on we have like a b um let's see a b for example like this again we would not expect right because like this element B here must come before this C over here for example if like these two elements are the same over here right then these two like I also have to follow the lexographical order so that's all that means okay so we understand like these two cases here so for example if we have like something like a b and then like we have a afterwards which means that this is maybe I can choose another one maybe we have like a c d and we have C here so basically this is our string B this is our string a so what it's saying is that string a is a prefix of string B it is string a is a prefix of string B and B appears before a b appears before a so obviously this is an invalid case so we're going to go ahead and return the empty string here okay now there may be multiple valid order of letters we want to return the smallest one in lexicographical order so this is not actually a condition on leaked code itself it seems to be only condition on this website here so I'll go ahead and explain this like when we come at the solution we'll come at the solution and we'll notice there's a problem in one of the test cases and so that's where we'll have to like fix this one here so I won't get into that one now but I'll come into it after and the final thing is the letters in one string are the same Rank by default and are sorted in human dictionary order um again not this is not really important right now but when you come to the test case or talk about it cases four and five so let's just skip that for now but anyway so we understand the question right so we're given a string like a list of strings that is supposedly what is part of an alien dictionary so maybe in the alien dictionary wrt comes before wrf Etc and from this we want to determine what is the ordering here now this question is actually pretty difficult if like you can't tie it to like some sort of like other data structure which you're familiar with but maybe let's see if we can like understand this right like what exactly is happening here well let's say I give you like two English letters right or like two English words maybe I give you something like um ABC and maybe the other word is like ABD what could you understand from this well from this one like if I asked you to compare these two letters and maybe arrive at some sort of um ordering right what could you come about well you might notice that like the a here and the a here they're exactly the same so we can't really understand anything from this so if we move inwards the B here is also the same so we can't even understand anything from this but when we move inwards once more this C over here is actually less than this D so what it means is that in our dictionary because these two elements these two letters are sorted but this one isn't this first one is it maybe there's like something over here maybe this is like um you know like something like this right as long as the first letter here is not sorted then we know that c must come before d so how I'm going to kind of represent this like C must come before D essentially like d over here has a dependence on C right and you might be able to tell like where I'm going with this but let's kind of continue let's kind of see like where we get out from these strings over here so maybe let's take a look so we have wrt and we have wrf so you can kind of see here that WR and the WR we can't really understand anything from that problem here we can understand t comes before F so we have the chat we have the we have to understand that t comes before f is dependent on by T okay so now that we've compared these two words essentially what I need to compare is like these two words then I'll compare these ones and then I'll compare these ones I can't really compare like this one with this one it doesn't really like help me in any sort of way I have to consider like two words at a time because like that's how it comes in the dictionary right the dictionary is always based off like the previous word so it really makes sense to just compare the current word and the next word Okay so we've compared like these two so now let's go ahead and compare wrf and then ER so what can we understand from this well we actually notice here that the first letters are different and if wrf comes before ER what it means is that W comes before e w comes before E now it doesn't mean that like for example maybe this was like a right it doesn't mean that R comes before a because we only can understand based off of like this first letter over here we can't really understand anything after this so for example in the English language maybe we have something like the word apple and then we have like banana over here well clearly like a can before B but like P doesn't become before a right so it's not that this entire thing is sorted but just based off of the first letter we can understand a mapping and then we can just break off right because we can't really understand anything after that okay so we've looked at those two letters or those two so now what do we have now we have ER and e t so E's are the same so we can't understand anything from that but from the r we can understand the r come before t is dependent on by R okay now we have the final case e t and then we have uh looks like rftt again from this one looks like we have the E come before the r e come to four the r right so you might notice that he's already here right so if you think about it what this kind of be what this kind of becomes is like we have something like this then e comes before the R so I can append the r here but notice that the r also comes like before the T so then we have the T here and notice how for the T we have the F so then I can make an f and you can see that this order that we form here is actually the answer w-e-r-t-f now w-e-r-t-f now w-e-r-t-f now there are like um this is not this is just like makes us seem super simple right but obviously the dictionary might not give us all the information we need for example in like something like this right let's say we have something like this um ZX over here right so from this one we can understand like Z comes before X right we can understand this one but like notice how like we don't have anything about the about like X like we don't have like X points to nothing so like that's something we might need to consider uh that's like something we might need to um handle in our case but regardless like in any of these types of questions I think it's kind of clear now this is kind of like a graph type problem right so what we can do is like we can go through this and what we can do is we can try to make our adjacency list based off of the rules that we can understand by going through two words at a time and then once we have this adjacency list what then what well then we can try to figure out like what is the valid ordering and you might just think like it's going to be like a straight just like a DFS right but really there's more to this question right and I think one example that might illustrate this is like let's say we had maybe we had let's see what if we had the strings let's say we had a d a e um what else maybe we had okay let's just say we had a d and AE okay so let's just say so we know that a comes before d we also know that a comes before actually not a comes before D um basically D con before E we know that much we know D comes before E We Know This Much right we know D come before E notice that there's no mention of like a in this entire adjacency list right so realistically if we were to just follow our approach we would just return like d e we wouldn't even return a d e for example so that's like one thing to consider another thing to consider is like we need to follow this in a specific order right if you think about it like what exactly am I doing here well let's just say like we had a couple of like words or like I'm just gonna make up things on the spot so maybe we had like for example T goes to something like Q and then Q goes to p and then maybe we have like for example um he goes to nothing and like maybe like um W goes to nothing for example so what we can see here is like we actually have a couple of like um a couple of letters right and we have to sort of mapping over here but what else can we see well I'm actually going to put this here uh Q which goes e okay and so I guess like P still has a dependency right P still has a dependency okay so what can we actually understand from this well if you think about this and I guess this Q can also go here right if you think about this let's say we have like all these letters right a t q p and w now if I was to kind of like Traverse this graph right like how would I Traverse it based on which nodes would I even try to Traverse it would I Traverse it based on the T first the Q first the P first like what would I even Traverse it based off of well if you're going to think about this we want to Traverse it based off of the nodes which in this case are the letters that have no dependencies right that have nothing such that like we know anything about their order in this case like those two nodes are actually just a and w right because we can see that there's nothing that a is dependent on T is dependent on a q is dependent on T which is dependent on a p is dependent on Q which is dependent on T which is dependent on a but really like a isn't dependent on anything similarly W is not also dependent on anything so like maybe even if you have like a wd here for example W is not dependent on anything so if you think about it we want to try servers through these first and there's actually an algorithm that allows us to do this effectively it's something called topological sort and I have a video called course schedule where I go like very in-depth into this as to like how it's in-depth into this as to like how it's in-depth into this as to like how it's working so definitely check out this video about core schedule you can skip like halfway I think um I just explained like this algorithm like near the ending so definitely check this one out but we're gonna be a pro we're going to be using this approach Here and Now how can we go about doing this question so I think first thing we could do is we could try forming our adjacency list and then based off of our adjacency list we could essentially form our topological sort and once we do our topological sort what's going to happen is that we're going to process the items that have no dependencies we're going to process the a first and then the W and then when we process the W you actually see that now D has no dependencies and so then we can process the D and the similarly if T has no dependencies then we can process this one Etc so let's take a look at how we can do this it's kind of hard to like just speak it out and not like draw put any code so let's take a look at how we can essentially start this off and then we can arrive at our solution so again this is like not a question that you would probably know how to do and let's look you've done course schedule or something before but let's take a look at how we can start off right so I guess first thing is like words it's going to be at least like two right but I'm guessing like if it's empty I don't know if it can be but if it's empty let's just return the empty string okay otherwise what do I need to do well otherwise I need to go through like the words or I need to go through the words but I need to go to them like two at a time so what I will do is I would do something like uh well actually before that uh looks like we need to create our adjacency list right we need to create our adjacency list such that for example this maps to nothing e-maps to nothing R this maps to nothing e-maps to nothing R this maps to nothing e-maps to nothing R maps to nothing Etc right so we need to create this and we need to create this ahead of time so how can we do that well in Python we can just use the default dictionary of a list and so what I will do now is I will go through the words I will do four word and words so now I'm at like wrt and then I'll go through the letter in Word and then I'll just do simply do adjacency list at letter is equal to what is equal to just an empty string right this is just to get it inside of the adjacency list because we notice that if we didn't do this then for example for something like this right Z and X or maybe not Z and X maybe we had like uh let's say we had like wa and then we are like WB after right we would get a and b into adjacency list because there's a direct dependence between A and B but there isn't anything mentioning W so we need to do that now something else we'll actually need is if you notice that when I did the topological sword example so maybe let me just take an example here so when we do topological sort let's just assume we had something like this right so let's say this was like the a this was like the B and then this was like the C and suppose the C has both a dependence On A and B what we say is we say that the in degree of C is equal to 2. now maybe B also had a dependency on like a d for example let's say we had a node like this so what we say now is that the B is the in degree of B is equal to 1 because it has like a one node pointing inward similarly the Integrity of a is equal to the Integrity of D which is equal to zero and so when we actually do our topological sort algorithm we would do it based off of these elements over here because these elements are the ones that have no dependencies right or I guess like they're not dependent on anything so that's just one thing I'd like to point out and so similarly we need to Define our integrity which is often just a list if you have a number but if we have like just letters I think we can do a dictionary but what I would do is I would do Integrity of the letter and then I'll set it equal to zero so initially it's all zero okay so now what can we do now we can go through our words and we'll go through two words at a time so I can do that is I'll do 4i in range 0 and I will go from length of words minus one right and then I can do something like word one is equal to words that I where two is equal to words I plus one and then what well now we need to go through the two words right and to go through wrt and wrf consecutively together now it's not guaranteed that they will be the same length right for example if this is like much larger then I only want to go to like wrt I don't want to go through the rest of it because it will be out of index so what I would do is I'll have another loop for J in range I'll go from zero to the minimum of what minimum of length of W1 and length of W2 okay so now what so now we have like the pointer J right and essentially I want to make sure that these two values are different if they are different then we can learn something from them so how can I do that well first of all if w i if W1 at J is equal to W2 at J well then I can just continue right there's nothing to do here the W here is the same and the r will also be the same but let's say we arrive on this case where we have like a t here and we have a f over here so let's say we arrive or like for example we have like W1 at J is equal to t w two at J is equal to F so if we have this case what can we understand or we can understand that there should be an edge from T to f y from T to F because the f is dependent on the T whenever you have a dependence you draw an edge so the f is dependent on the T so we can do adjacency list at W1 at J is equal to or I guess not equal dot append W2 at J so now here we'll create this dependency here in addition to this we have to actually increase the in degree of f right in degree and we will do in degree of what in degree of W2 at J plus equals one so what exactly is this doing what this is doing is that we have two elements now something like this and we have a t over here we have a f over here and now we have an edge connecting the two like this and what we have is that the in degree of f is equal to one why because there's one node pointing inside of it which means F has like one dependency okay now what well if we've done this then essentially we can go ahead and break right why can we break because we don't care about the rest of the word it's like in similar like when you have like apple and banana we can learn that the a is less than the B but we cannot learn anything about this information here this information is not necessarily sorted so that's why we just break okay so we handled that case now here's the part in which we actually handle this case number two where like the string a is prefix of string B and B appears before a again what that looks like is maybe you have like um like Apple maybe something like um what's a good example yeah maybe you have like cars and then after you have car in the dictionary obviously this is not valid right because cars should come before cars so how can we do this well essentially what we can check is once we are outside of this we can actually check so this is like string B and this is our string a but realistically this is like our word one and this is our word two so we can check if length of word two if this is less than the length of word one right that's fine if it's less than right it's fine if it's less than it doesn't have to be the same but for example word 2 must not be like part of word one so we can do and word one dot starts with word two if this is the case then we know that we have like a problem right because we have a scenario where something like this just to be clear this is not a problem but if this happens and word one starts with word two then it is a problem so then we can just return the empty string and so that actually takes care of one two and three so we don't have to worry about that now at this point what do we have so at this point I will just go ahead and just print out the dictionary just so we can see it so let's go ahead and just print out the dictionary so I will actually go ahead and just paste this in and looks like default dictionary was also not defined so I would just import it from collections import default dictionary so let's take a look just to be clear what we have so again we can see W points to e r points to t points to f doesn't point to anything right and then we have that E points to R so this is how we have like this information here okay so now what can we do well let me maybe go ahead and just copy this so now what can we do okay so now we formed our adjacency list and we're sure we're good we're sure that it's like a valid adjacency list based on the fact that we haven't returned yet so now we need to actually start our topological sort so how can we do that well again in topological sort what you do is you take a look at all of the nodes and again what the course schedule of video to better understand this but in topological store if you have like some sort of ordering if you have some sort of ordering for example maybe this points over here and maybe also this points over here and this and um this points over here let's say then the only nodes that we can actually visit that start off with is this node and this node because they have no orderings like they have nothing that they are dependent on and actually we can yeah I guess we can't start off at this one either so now what can we do well let's say we process this node right like let's say we go ahead and process this node here so then what happens well then now this Edge is gone now notice that now we can process two more nodes now we can process this and now we can process this right so we have this information but notice that we cannot process this one why because it still has an edge from this node here okay so that's like what why the Integrity is important and actually like when we go ahead and process this one like we'll also go ahead and break this Edge but again we still have this one left and so that's how we're going to maintain our ordering here what does that look like well I need to Define my cue right and now what do I want to add to my queue I want to add all in the Val all of the values that have in degree of zero so what I can do is I can do four item in degree if item at in degree or I guess if in degree at item is equal to zero then we'll add it to our Q so this will add in the letter to the queue okay we're almost done what about now well now we can just go through a queue normally so while Q and then what well now I'm going to go ahead and pop from my queue so I'll do Q is equal to pair is equal to curd up pop Q dot part from zero and now when I pop what will I pop well pop a letter right it's kind of like here for example if all of these refer to letters maybe this was like the letter A maybe this was like a letter B maybe this here is like a letter C so now I'll pop this letter A so what does this mean it means that I can store like a result variable and then to this result I will add in this letter A okay um I guess add incur so now what Okay so we've processed this value over here so now I need to look at all of the neighbors that it connects to and I need to decrease their in degree by one so I will do for neighbor in adjacency list that occur what can I do here well then I can do essentially in degree of neighbor minus equals one now notice that if I just do that I can now process this one but I still cannot process this one why because it still has an edge over here so in order for me to determine that I can process these two what I can do is I can check if in degree at neighbor is equal to zero would now have no more edges that are leading into it so and then I can add this to my queue uh neighbor and so then I have that now what do I need to return well it would make sense for me to return res but only if I can only return res if for example this string that we form it has all of the letters right it's possible that like it's possible that we might have like some sort of cycle right so in that case like we wouldn't return everything but the only way I can return this I can return res if length of res is equal to length of I guess adjacency list or in degree Works else empty so now let's take a look so we have that this works let's go ahead and run okay so now we've arrived at the problem in which we need to take care of steps four and step five okay so how can we understand this so in this one essentially what we have and I'll maybe go to the top essentially what we have and this is actually not a problem on Elite code I want to emphasize this is just for lint code I think just for link code so actually what they want is if you notice here what do we know that the Y must come before the X right Y come before the X but we have no information about when the Z should come right like we don't know when this should come this might even like um like it's not necessary that this comes like later on right this might even come after the why because if you think about let's say we had like for example ba and then our next word was like um BC right this tells us that or maybe this is a bad example let's do English maybe we have like something like um let's do D um yeah I guess d a n d c right from this one we can understand that a come before c but we don't know like where D comes from right because we don't have that information we have nothing that we compare D2 to tell us of the order so in this sense like if we did it like our Q approach what we would have is we would have like a come before D or maybe not D here let's put an e here right so we can have a come before sorry um I'm messing up so this is valid we can have that a come before c but we don't know anything about the D so what do we put in our Q well in our queue we would actually first of all we would have like d points to nothing in our queue we would add in potentially D we would also add in a now what they want us to do is that if we have a scenario like this where we have elements on the Queue we should process them in lexicographical order so what this means is we should first process a then D so that's what it's saying here and so if you kind of take a look at this example that we're getting what is the valid answer here so the valid answer here if I go ahead and submit it the valid answer should be something like this right the valid answer should be something like this so how might we arrive at this well here we can notice that we will have the following adjacency list right something like this so X is the only one that is dependent on something y and z are not so maybe in our queue we have like z and y first but what we would do is we will actually process Y and Z we'll process it in this order we're allowed to do this because both of these have no dependencies right like they're not dependent on anything so we can take any of them order they won't be dependent on each other that's for sure so all the items in here are not dependent on anything so we need to basically do this so how do we do that well it's very easy um there's actually two ways the first way is basically before we pop from the queue we would just sort the queue and we'll sort it based off of like just the English letter so this will just sort it another thing you could do is you could kind of just like heapify your queue that might actually be easier um so kind of the approach there is like we need our Heap he pop he push and um heapify so what we do here is actually I guess like we don't really need heapify but what we could do is we could do instead of Q dot append we would do uh Heap push we're pushing the Q we'll put in the item and then I guess I need to put this up here and so then what I can do is instead of sorting and instead of popping I will just do Cur is equal to heat pop and notice that this one this will return the smallest element right so we don't really need to do this and similarly instead of doing here we would just copy and we will do he push q and the neighbor and so if you run if we go through this approach uh it looks like heat pop takes exactly one argument you pop uh I need to pass in Q here right so if you take this approach this also works so okay that's just like two things that it's just specific for lint code it's not specific for lead code so anyways how might we go about like the complexity of this well let's take a look because there's quite a few things happening right so basically just for the queue the time complexity of the lexicographical search is O of n where uh oh sorry of the topological search o of n where n is the number of letters and technically like that's like this thing here so this is like all of O of n where n is the number of letters but if you think about it like what we're doing over here is like potentially like we have to go through every single word so maybe we can say like word size is M and then maybe we can say um number of letters is equal to n so then this is kind of like if you think about it o of M times n right because we have to go through each word and potentially like each letter inside of it as well so that's kind of like what's dominant here and so that's what we have and similarly for the integrity and for the adjacency list really the size is based off of the number of letters so it's O of n there but overall the time is M times n the space is just o of n okay thanks for watching
|
Alien Dictionary
|
alien-dictionary
|
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.
Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_.
**Example 1:**
**Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]
**Output:** "wertf "
**Example 2:**
**Input:** words = \[ "z ", "x "\]
**Output:** "zx "
**Example 3:**
**Input:** words = \[ "z ", "x ", "z "\]
**Output:** " "
**Explanation:** The order is invalid, so return ` " "`.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of only lowercase English letters.
| null |
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Hard
|
210
|
38 |
hey guys how's everything going let's take a look at number 38 countin say we're giving we are given a special rule of generating a string the first one is one so we need to count the every digits of the string and generate a new one so there's only one so one for these string there will be two one so next one is two one and next one is 1 2 1 so next one is 1 2 1 now 1 2 1 so followed in this rule the next one should be 3 1 2 1 there's nothing tricky about this I think we can just follow the rule and create the iteration a function let's say the result initialized so the first one is 1 so with the first one is already issued IIST the actual iteration round would be n minus 1 right so there is nothing about needed for n so we just use while loop when is bigger than 1 it will end at 1 so for each round we will generate 2 a new string and replace the result and finally we will return the result and yeah the next string should be each less with empty and how can we count the numbers it's actually very simple we need to keep the counts of current digit and current it if we found something different we update the count and updates the next string right so let's count to be 1 which is which means we initialize the current to the first digit so if that so we need to start with I equals 1 ice smarter than result i plus was if it's not current if not the current we need to update current right we need to updates current to this one and yeah i account should be set to one but before that we should update the next string it should be appended with like first with account and the current if the string is if the comparison results in the equity it will be much simpler because we just need to update the account with one and we update the result to the next year one thing said what considering the boundary what if the last digit is checked and it should be handle at the end right we could write another check here like if like we just to update next plus copy the code here and do it once again one more time but actually we can just extend the I to the next one so I will actually stops at the place after one like here and it will be undefined so you actually come to this case and yeah it's just what we need and it's done let's run a code so time obviously there will be a n and how many digits are there I don't know so here is one to I don't know how we should we count this but I don't think it we are needed to cut to estimate the time complexity here because for each round there just we need to traverse all the digits of the string and each string of certain round is actually decided hmm yeah anyway we submit and the check if it passes but it's not fast hmm anyway it doesn't matter for this simple question it's actually nothing we can learn from this problem the one only one thing is that for these questions we just understand the rule and implement logic in a plain way and pay attention to the boundary yeah and it's done so see you next time bye
|
Count and Say
|
count-and-say
|
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1) = "1 "`
* `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string.
To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string `"3322251 "`:
Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_.
**Example 1:**
**Input:** n = 1
**Output:** "1 "
**Explanation:** This is the base case.
**Example 2:**
**Input:** n = 4
**Output:** "1211 "
**Explanation:**
countAndSay(1) = "1 "
countAndSay(2) = say "1 " = one 1 = "11 "
countAndSay(3) = say "11 " = two 1's = "21 "
countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 "
**Constraints:**
* `1 <= n <= 30`
|
The following are the terms from n=1 to n=10 of the count-and-say sequence:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
|
String
|
Medium
|
271,443
|
834 |
hello everyone welcome to day 4 of september eco challenge and today's question is sum of distances in tree in this question we are given an undirected connected tree with n nodes in it labeled from 0 to n minus 1 and their n minus 1 edges in it we need to tell the count of distances of each ith index with all other elements in that tree so i'll be explaining the question as well as the solution by the presentation that i have created for this and let's get started with the bbt sum of distances in a tree lead code 834 this is a hard question on lead code and i also feel the same let's try and understand the question by the same example that was specified so we have an edge starting from the zeroth index up till the one index we have another edge starting from zeroth index up till the second index we have an edge starting from second index up till three from second to fourth index from second to fifth index and there are in total six nodes or indexes in my tree so let's try and calculate the distance of each index with all other indexes let's talk about the zeroth node first so what is the distance from one the distance is one the distance from two is also one the distance from zero to three is two the distance of zero to four is two the distance of zero to five is again two this adds up to in total two eight let me just erase it and write 8 here the distance of 2 or with respect to all other nodes let's try and calculate that the distance of 2 and 0 is 1 the distance of two and one is two the distance of two and three is one the distance of two and four is one the distance of two and five is one so this adds up to total of six let's continue the process let's calculate the distance of one node from rest of the nodes the distance of zero and one is one the distance of one and two is two the distance of one and three is three one two and three is three the distance of one and four is one two and three again three the distance of one and five is again three so this adds up to total of twelve so we'll write twelve here let's try and solve it for the rest of the elements here we have three so the distance of 3 from 1 is 3 the distance of 3 from a 0 is 2 the distance of 3 from 2 is 1 the distance of 3 and 4 is 2 the distance of 3 and 5 is 2 this adds up to total of 10 and let's do the same thing for four and five since uh three four and five are exactly at the same similar position the distances will be the same so writing 10 here and 10 here as well you can calculate it by yourself let me just draw a boundary here because these are the elements sum that i have calculated and this is what we need to return in an array format as the answer the distances of each node from all other nodes let's talk about the solution now we need to do some kind of pre-processing need to do some kind of pre-processing need to do some kind of pre-processing on this input tree to build our algorithm and the first step of this preprocessing is to identify the number of nodes that fall under a particular node including that node so for 0 how many nodes fall under 0 1 2 3 4 5 and for the current node we will add another one that means in total this subtree has six nodes this subtree has only one node this sub tree has one two three and four nodes this sub tree has one node the sub tree has one node and let me just change the color of the pen since we are done with the preprocessing and identification of how many nodes fall under each subtree next we are going to calculate the distance of each node from the current node within that subtree so what is the distance of 0 from all the nodes within this particular subtree so the distance of 0 and 1 is 1 the distance of 0 and 2 is 1 again so 1 plus 1 that makes up till 2 and the distance of 0 and 3 is 2 the distance of 0 and 4 is 2 distance of 0 and 5 is 2 so we'll add another 2 3 times that makes it 6 and the distance becomes 8. so what i am basically doing i am calculating the depth here depth of each node from the parent sub parent root node so the depth of zero from one is one the depth of zero from two is another again 1 the depth of 0 from 3 is 2 the depth of 0 from 4 is 2 the left of 0 from 5 is again 2 and let's do it for the rest of the nodes as well so how many nodes fall under uh one there is no node so we will have zero here how many nodes fall under two there are three nodes so we will have the distance of all its children from two to be uh three because there are three nodes and which are the indirect contact with two the distance of three from all its sub nodes is zero and 0 i have done some cleanup here so that you get a good hold of the concept now we'll be moving in a pre-order fashion a pre-order fashion a pre-order fashion so whatever you are seeing in magenta signifies the distance of all its children node from the current node and whatever you are seeing in green signifies the count of all the nodes within this subtree so let's start the iteration and let me just change the color of pen to red here at 0 we already know that the distance of all the nodes from 0 is 8 so 8 is the answer let's talk about its children here we have one and you can we can use the information that we have calculated at its parent to actually come at the solution for one how can we do that so if you carefully observe then what is happening in the system uh when the reference is getting changed then few nodes are coming closer and few nodes are getting away when we replace uh zero node with one node into consideration and what is the count of those nodes that are coming closer and what is the count of those nodes that are going farther that count will be given by the number of nodes held at this particular node so how many nodes are held at this particular node it's one and how many nodes will actually go farther if we take the change reference point from zero to one uh the number of nodes that will go farther would be one two three four and five whatever the total number of nodes we have the total length of the nodes that we have versus the current node that this tree holds that would be 6 minus 1 so let's write it up what is the value calculated at the parent the value calculated at parent is eight and how many nodes are getting closer when we replace the reference point one node is getting closer so we subtract one and how much we should add how many nodes are getting further that need means we need to increase the distance and take those many notes into consideration the total number of nodes that we have is six so six minus the nodes that are held at this particular node minus one so this gives us seven plus five the answer becomes twelve so let's continue the process for this particular node when we are changing the reference point from 0 to 2 how many nodes are getting closer or since the reference point is getting changed uh the distance is getting reduced for how many nodes will it reduce for four nodes it's gonna reduce and how many nodes in this tree are getting farther it's zero and one uh and the so their count is two how can we get their count the total number of nodes that we have is six and the nodes that are held at two which is four so six minus four gives us two so these many nodes are getting farther off and these many nodes are getting closer so let's use the frame formula what is the distance calculated at its parent the distance calculated is 8 how many nodes are getting closer four nodes are getting closer so that means we need to reduce its distance and how many nodes are getting farther two nodes are getting farther that means uh eight minus four plus two gives us six so this becomes six let's continue the process for the rest of the nodes we have 3 here and what is the value calculated at its parent the value calculated at this parent is six how many nodes are getting closer uh there is only one node that is getting closer if we change the difference point from two to three therefore we will subtract one and how many nodes are getting farther one two three four five nodes are getting farther therefore uh the answer becomes six minus one plus five that is ten and how do we calculate this five value the total number of nodes minus the nodes held at this particular entry so this gives us 10 and we'll update this to 10. similarly for these two nodes because 3 4 and 5 are exactly identical the they are the same geography as three is so i'm not reiterating it just remember this particular formula and everything will be sorted let's talk about the time complexity now the preprocessing that we have done here can be solved using a post order traversal and it will take order of n complexity the way we are calculating the total number of nodes in a particular sub tree and the way we are calculating its distance from uh each subtree uh that takes the total complexity of order of n because we are using a post order traversal and for finding out the actual distances uh we are again using a pre-ordered reversal and the complexity pre-ordered reversal and the complexity pre-ordered reversal and the complexity is same as post-order of n is same as post-order of n is same as post-order of n without much to do let's move on to the coding section the first variable that i have defined is an array of type integer that will store the results the second one will store the count at each index in the uh in the tree and the next we have is defined a list of hash threads that will help us build the input data in form of an adjacency list since it's undirected connected graph or connected tree so let's start the iteration i have assigned a memory to it or to all the three variables and using these two methods i have built my adjacency list once the adjacency list is built i'll invoke the post order traversal helper method and it is responsible for calculating this count array also it will update the result that will be used as the base for our further computations so let's talk about this post order reversal method uh i have passed in the reference to the previous node into consideration so that we don't form a cycle kind of a thing uh while iterating over the adjacency matrix and this is my root and this is my previous node i trade over all the children of the uh given root and if my previous is equal to the current element into consideration i skip it otherwise i invoke the post order reversal on its child and i update the count variable uh to whatever account was specified at the ith index and also update my uh result of the root with the result of the ith index plus the count and once i am done with this i simply return count of root plus let's talk about the pre-order traversal let's talk about the pre-order traversal let's talk about the pre-order traversal now exactly the same thing the same formula that i talked about in the presentation i am moving in a pre-order fashion i am moving in a pre-order fashion i am moving in a pre-order fashion passed in the root and the previous note so that i don't fall into a cycle kind of a thing whenever they are same the ith index of the roots children happens to be same as the previous node i skip it otherwise i use the formula that is specified in the presentation a result of i equals to result of root minus the closer nodes plus the nodes that are going further and then i perform it perform the same operation on its child nodes once i'm done this i simply return the result so let's try this up accepted the time complexity i've already talked about is its order of n this brings me to the end of today's session i hope you enjoyed it if you liked it please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded we'll see you tomorrow with another fresh question till then good bye
|
Sum of Distances in Tree
|
ambiguous-coordinates
|
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\]
**Output:** \[8,12,6,10,10,10\]
**Explanation:** The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer\[0\] = 8, and so on.
**Example 2:**
**Input:** n = 1, edges = \[\]
**Output:** \[0\]
**Example 3:**
**Input:** n = 2, edges = \[\[1,0\]\]
**Output:** \[1,1\]
**Constraints:**
* `1 <= n <= 3 * 104`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai, bi < n`
* `ai != bi`
* The given input represents a valid tree.
| null |
String,Backtracking
|
Medium
| null |
149 |
So gas welcome and welcome back to my channel so today our problem is max points on a line so in this problem statement what have you given us here we have been given an arrow points where your points I is representing A and Ye Ko, what is this of yours, the coordinator of any point, okay, so what we have to do here, we have to find the maximum number of points for the date on the state line, so what do we do through the example? Let us understand what is the problem and how can we solve it, so you see here, we have taken two examples here, so here we have given you 3 points and all three are on the same line. So what will be the answer here, it will be three and here you have been given 6 points out of which 4 will like no, this will also like three, but four is the highest, so what will be your answer, will be four, okay so we will like this. How can we solve the problem? See if this is on the line from this, then the slope of both of these will be the slope of this from here, the slope between these two of these, both of these on this line. If you define them as much as they are, then it will come out from yours. It is fine, but you also know that when there is a parallel line, then what is their verse? So it is possible that it is not there, it is possible. Some points have been given to you here in such a way that they are lying on a parallel line, then how will you find it, meaning from the slope, so we can find here, we have done that from which the slope will be here. You will get it on this line but you also know that if the slope is from then there can be another line also and that line will be parallel to you, okay then how will you handle it, so for that we just have to solve our problem. The method will have to be changed. Concept, we will do it with our own, we will do it with slope only, but the method of solving it will be different, how it will be done, we will see. Okay, so here on the man lo, remove your 12 on this. I do n't want to give even a small amount, see, it's okay, let's agree here, there is a point here, and there is a point here, okay, I have given it here and you also have two points here. It is also given on this line and these two are not the same, which is due to the slope of the first line. Okay, now how will we find out what will be the maximum number of points here, so you are seeing the picture here, this graph. If you are looking here then what is the four lines maximum will be on one line then the answer will be four but how will we find it, see for this what will we do here so we will do the concept of slope but when we find the slope then we will neither use one We will fix the point and find everything from there, so let's fix it and what we do in between is find the slow, then everything in between you got M and from here also you will get M because From is on the line and its M will come out from here too, okay M taken out here, you got this M taken out between these If you search between these two, that is, you will get three slopes. Okay, then if you search between this and this, will you get S, will you get M, will you not get slope because this direction is changing. If you are watching, will you ever find this? You will not find it and if you search between these from here, what will you find if there is a slope here, what will you find, what will be the difference, okay, if you find one slope of these two, the difference between this one and the one between this one will be found, but if we had found between these two, then By going there we would have got M which would be equal to the slope between these two but from this point we are finding for everyone i.e. whatever is on this line then we i.e. whatever is on this line then we i.e. whatever is on this line then we will get M but here if it is on another line even if it is parallel. Why not and if we take any point of this line from the point and it turns out to be in the middle of this line, then what will we get? M will come out, that is, slope will not come out from it. Okay, so we will solve it in this way, so now how will we do the example? If we understand through K, then what will we do here, we do not know where we are on the line right now, we know this, if from is on the line then M will come out, if any one point, if we are on the second line and the other If we are comparing from the points on the line, the slopes will be coming out, then it is sure that it will be different. Okay, so what will we do here, first let's fix this point, then what will we do with it. Slopes will come out from all the points, so here But let's break it down, you start with 11, okay, let's start with Van, first you take it out, it has the formula, after that, what will be 3 - 1, that is, after that, what will be 3 - 1, that is, after that, what will be 3 - 1, that is, take out 1 / 2 for this, then look here, 3 take out 1 / 2 for this, then look here, 3 take out 1 / 2 for this, then look here, 3 - 1 will be 2. And 5 - 1, what will happen if it is four, - 1 will be 2. And 5 - 1, what will happen if it is four, - 1 will be 2. And 5 - 1, what will happen if it is four, then this is also 1 / 2, let's then this is also 1 / 2, let's then this is also 1 / 2, let's take out the slope of two points, here take out the slope of two, after that 1 - 1 will be 0, then 0 / if you take out the slope of two, after that 1 - 1 will be 0, then 0 / if you take out the slope of two, after that 1 - 1 will be 0, then 0 / if you do anything, you will get zero, this is different. Slope was drawn then 3 - 1 kya niklega tu then 3 - 1 kya niklega tu then 3 - 1 kya niklega tu mines van i.e. you are slow then four mines van three mines van i.e. you are slow then four mines van three mines van i.e. you are slow then four mines van three a zero i.e. infinity three a zero i.e. infinity three a zero i.e. infinity is ok so this was taken out now here you came to know that from here no this is slow this slow is from two slopes two verses What are the points, there are three points here, so the answer is, what are you guys updating? What are the three points on the line ? Three Two and ? Three Two and ? Three Two and Five Three This one, this point is on the line from this but this is three, now what do we do, let's start from here, fix it and see from further, why not see this because for this we have already seen. Which was extracted by van by tu, okay now from here we will do this with this, okay then if you do 3 - 2 then van okay then if you do 3 - 2 then van okay then if you do 3 - 2 then van and if you do 5 - 3 then and if you do 5 - 3 then and if you do 5 - 3 then what will come out van by tu okay then our - 1 will come out, 3 - 2 will come out, 2 - 3 - 1 will come out, let's go again, 3 - 2 will come out, 2 - 3 - 1 will come out, let's go again, 3 - 2 will come out, 2 - 3 - 1 will come out, let's go again, okay, then four mines, how much did you take out, one mine took out three - 2, that is, you take out, one mine took out three - 2, that is, you take out, one mine took out three - 2, that is, again, one mines van taken out, that is, three, what is the slope here, what is the mines van, that is, here. How much you have calculated will be four points, only then 3 slopes have been calculated, that is, the maximum answer which was 3 till now will be four. Which one will be in the pickle? This one is 3241 2314, this is the one, are you looking at it? 1414232341413232 It was this one only. Well, from this you got to know about four. Okay, from here we got four, then we will fix it and look further from this, why not look from the back because we have already seen both of them, right, we will see this from this. If we look at it from this, then here you will see again, let's do it. Look, if you do 1 - 3, you will get 2. Okay, Look, if you do 1 - 3, you will get 2. Okay, you will do 4 - 5 - 5 is done. After that, what is your three zero, this zero will come out, your 1 and 1 will be - 5, that is. This is your you will do 4 - 5 - 5 is done. After that, what is your three zero, this zero will come out, your 1 and 1 will be - 5, that is. This is your you will do 4 - 5 - 5 is done. After that, what is your three zero, this zero will come out, your 1 and 1 will be - 5, that is. This is your van, it is yours - 4, okay, this will happen, so all these are van, it is yours - 4, okay, this will happen, so all these are van, it is yours - 4, okay, this will happen, so all these are different, that is, one here, till now, what is the maximum, it will be only four, okay, so in this way you keep finding, so till now the maximum you have got is 14. If we get this solution, how will we do it, we can do it this way, we have found out how we will do it, see, we will take a map, what we will do, we will take a map in which we will take the slope, and from this slope we will count how much we will keep, okay How many times has the slope of the verse come, like here your van by you came, zero van, you van bari and three five zero infinity, okay, so this is the maximum, so if it is two, then the answer will be three points because If two are slow in the count then the points must have been given to him by three, then three is the answer here, then you came to know that from the mines van, when you again here from here to here, from this 3 2 5 you saw all yours from 3 2 So if you get -1 three times, then you get -1 three times, then you get -1 three times, then you will add plus one to its account, then you will know that 4.4 has been kept, then for this you will map it, that 4.4 has been kept, then for this you will map it, that 4.4 has been kept, then for this you will map it, okay and here what you are doing is finding it from this. Find from the next one i.e. two for loops, you will from the next one i.e. two for loops, you will from the next one i.e. two for loops, you will do it, you will start from zero, okay, you will start from zero and compare from here to here, neither i will be here, so yes, your i will start from + 1, okay, so in yes, your i will start from + 1, okay, so in yes, your i will start from + 1, okay, so in this way we If we do, then that's all it has to do and nothing else to do, so now I will show you the code also. Look here, to handle the case of infinity, we cannot write infinity here, like infinity here is the zero. These two we mean, how will we do it through the core, what will we do for this, we will take the maximum number, when will we get it, when we will understand, look, by zero should not come in If it is from then we will check this condition that let's see from the beginning, okay, we have kept the maximum number so that your account will handle the case of infinity, this is your count which will be visible, okay, what is the maximum count till now, so from here We will follow from zero to point size - 1 because we will take GI plus point size - 1 because we will take GI plus point size - 1 because we will take GI plus van so we will take point dot size - 1 van so we will take point dot size - 1 van so we will take point dot size - 1 88 till there we will take a map, here we have taken a map because for each and every condition, let us see. We have to see here, then we have to see it separately, we have to see it here, so I don't know, we should do it separately for this, okay, so what will we do Map Here we took it from double because we will divide x a tu minus a one by X2 - by X2 - Which will start from here, will start from i plus van, will go to point dot size. Okay, here we will check what is our Why do the power four plus? Because what are the coordinates, how far can you go here? It wo n't come, that's why we took it till now you can take brick max also, so we took this which will handle the case of infinity and vice versa, what will we do with this, what will we do in it, how will we find the slope, how will we find Y2 - y1 / slope, how will we find Y2 - y1 / slope, how will we find Y2 - y1 / X2 - X1 slope got X2 - X1 slope got Because we need the same count, we do n't need less points, we do n't need points, we need points account, so what will we do, what will be its value, which will be stored in the map, what will be its second value, we will add plus van to it, okay here. We will see more on the pay account, see what is given to you here, whatever points are there, one will definitely be yours, okay, whatever is the length of the points, there will be one, we will see, at least one point will be liked somewhere, that's why we We will see which is the maximum van and count, then the maximum of both will be held and turned. Okay, so I hope you have understood this and how much will be its complexity. See, here you will get ONS Cuckoo because what have we done here. If you have done two loops right then its complexity has become on your square and its space will also be on because we have mapped it so I hope you have understood it. If you liked the video then please like, share and subscribe. Thank you
|
Max Points on a Line
|
max-points-on-a-line
|
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**.
| null |
Array,Hash Table,Math,Geometry
|
Hard
|
356,2287
|
212 |
Hello hello welcome present world today going to solve today liquid problem it means valsad to end whatsapp to check it a video subscribe The Video then subscribe to the Page if you liked The Video then subscribe to define and this research in the world and returned his verses word written 200 words exact phrase 800 60 subscribe Video then subscribe to the Page if you liked The Video then subscribe to subscribe our only reduced To a few students will have no strength and destroyed it appears in the list of scheduled tribes in the mid-1960s Subscribe to hua hai ya kisi hi work social media Similarly in the train will stop at a great way to agree to here everyone Story in here rights of that ab is gali dushman this is how the private limited and isi english only one superfast between former were getting into it's corresponding for each and every word of the day but complaint all song o's account dozen vehicle horse per for Doing So Will Smith subscribe Video Channel and subscribe the Channel subscribe Video subscribe button to the fastest fast whole building subscribe and to method that they can search for a genuine more * * miding subscribe for a genuine more * * miding subscribe for a genuine more * * miding subscribe The Video then subscribe to subscribe our I Don't Ultimate Opinion Note And So E Spy Notification Se Lettuce That Pure Multiple Note Slide Children Noida And 06066 Terminal Building 113 To Criticize Are Dev Narayan Road Sorry For Inspection Hydraulic Egg Subscribe And Gifts And Subscribe To World Channel Plants Subscribe To This Channel And that's so let's write barcode night 998 Android advance in this is oldest living in this to all the best all the wild elephant in the board and it's a great day also according to string A6 white to-do list festival 2381 Share A6 white to-do list festival 2381 Share A6 white to-do list festival 2381 Share and subscribe Latest Hot I Will Define The Jai Hind Section Or Sauda Speed Mature Subscribe Whatsapp Par Kar Denge Air Ko * Called S Insan More Kar Denge Air Ko * Called S Insan More Kar Denge Air Ko * Called S Insan More A True Sonu Nigam CEO Larry Hai One Mein Sir Colin Shirt Subah Will Very For Scheduled Tribes And Subscribe Tuesday Maintain With U 108 Types of birth I am morning's interactive and standard act would you should not tide surf strongly and by default all the self 1200 subscribe our dots the length and column auspicious birds road dot loot hai or 9 and guntur after it's true Davis that 222 600 Nandishwar bhi le karne par don't length main teri should be plus dene ke in you to the number for loop in due course he z10 board heroes toys subscribe And subscribe The Amazing Password subscribe The Video then subscribe to Kaun-Kaun and twist set to Edit and delete and write your Kaun-Kaun and twist set to Edit and delete and write your Kaun-Kaun and twist set to Edit and delete and write your school district in up that and thank you rate list of result website sada khatima for this function hai wahi good night my dear function to brothers at midnight subscribe hai what they need to 56001 sirvi kar do hai aur board rally school Password se left from delinquent semi the ne bullion the red light on a minute to 5 pm on food type a strange dry fruits aanch a ki saans li lootne vitamin ride on main suraj pati match 300 the time to visit in udan do not going to start Benefits sexual the du Plessis in the role of I tujhe ne janjiro on hai jo id al-adha remove board 4000 jo id al-adha remove board 4000 jo id al-adha remove board 4000 next hua hai join - daily want to board 10 join - daily want to board 10 join - daily want to board 10 friends will sleep here mismatching du Plessis that these plants decoration match dena and country town And country planning guide deposit swiss roll out appointment 619 married life in the country and avoid and history se 0m do subscribe school do that app in the whole life table migrant celebrate b board ij re somewhat that this one and a half city march haze to you Shastri function water button in ur stride nights with em going to check back is this what is this chowk and swing is exhibition road price in tribal leaders not exist give not with people from father action not go into a breast character studio with nothing in this Guy Subscribe 63 This Back Vansh Jai Hind Found Displaying All MP3 Sound Match Winning One To End The World In My Results And What Is Declared In Her Right Ninth Result More Mirchi Now Loot Lo Tomorrow Morning Do The British Half-Half Guru Tomorrow Morning Do The British Half-Half Guru Tomorrow Morning Do The British Half-Half Guru During Fog More Solitaire game call to the daily needs in more subscribe to here i am sorry no why i took all the same function for all the for raising voice of a college for women in the 2.0 - one college for women in the 2.0 - one college for women in the 2.0 - one i devendra neetu quality for hua ki nitish correct spelling mistake i Ishwar Bhi I Plus One 13 Inches Plus One Night Ko Switch Tweet Quite Different From Light Of 210 Pretty Much Now I'm Going To Home Makers Printed About Me Money Bill Pass White Road And Debit The What Is Not Exist In Raghavendra Cut Patti Ko Subscribe now to receive a strong Sameera lekin educated hai yaad spelling aerospace limited lekin yes yaar ek Vidhan Sabha in do kar do hua hai ya vacancy in events during the were expected to practice of meditation check set Video not yes yaar denge it accepted norms previous tell you what they are doing work subscribe and subscribe the Video then subscribe to subscribe our hai ya dena he got pregnant chadhai aur ladies swift code ko aangan to check all apps android soayenge wicket dishes 999 subscribe and subscribe the Video then subscribe to subscribe our my voice looks like this yes yaar can see and time 15.52 pimples yes yaar can see and time 15.52 pimples yes yaar can see and time 15.52 pimples video thanks for watching and the bling also like
|
Word Search II
|
word-search-ii
|
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique.
|
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
|
Array,String,Backtracking,Trie,Matrix
|
Hard
|
79,1022,1433
|
1,685 |
hey everybody this is larry this is me going with q2 of the bi-weekly me going with q2 of the bi-weekly me going with q2 of the bi-weekly contest 41 some of the absolute differences in assorted array so basically this one it's um a tricky problem to think about uh but you know you could do that well you hit the like button the subscriber and join me on discord uh just kidding but uh i mean you could do it and you should but the idea is this idea um this idea of a sliding window first of all you calculate the total of or you calculate the result for the first index so in this case you would make them slightly bigger um yeah um so you would calculate the answers for the first and uh the first input and then after that it's just math to kind of calculate that answer from the other uh from uh after that it's just math to calculate other answers from that answer right because b for example here you go from two to three well what does that mean right that means that all the numbers to the um let's take a bigger example so that's easier to illustrate so sorry about that give me a second so basically you have something like that okay so then you start with 24 right um because you know you do the math from one and then all these other deltas and then now you go from one to four what does that mean right that means that all the numbers to the right of four including four i suppose but it zeroes out anyway all the numbers to the right of four it gets minus three for each of those numbers right and all the numbers to the left of four it gets plus three because now it is farther away so then in this case we have three numbers or well four if you want to count four as well um we have four numbers that are now minus three so that means it's minus 12 and then you have one number that's plus three which is the one because you know you're moving it to the number so that's plus four so then in total that is going to be 15. right uh oh and that's we have plus three and plus nine right and then similar similarly uh okay the difference between four and six is two right that means that all the numbers to the right of this uh will have a plus two or so it has a minus two because now the distance got closer and all the numbers to the left has plus two because now we got further away because you went from four to six and therefore uh yeah it just ends up being a net plus two right i think uh oh minus two oops i'm n minus two uh but yeah but that's basically the idea and that's basically the algorithm my arithmetic is really terrible today uh and this took me a little bit of time but basically i have the delta i count i add all the stuff to the left and you know index is just a count of the numbers that are the left that we need to add and then we move closer to the numbers to the right because it is in sorted order um which is just n minus index um and then you append the total and that's pretty much it uh it's it is not a easy problem to think about but once you get the concept down the implementation is you know much more easy much more easier so yeah let me know what you think this is linear time linear space and you cannot do better than linear space because well you know that's the answer that you have to return and in linear time you have to look at each other with at least one we do it in two paths so yeah uh let me know what you think and you can watch me stop it during the contest now oh okay you alright um okay you okay that's hard uh hey thanks for watching the explanation i this was a little bit of a tough contest for me uh let me know what you think hit the like button to subscribe and join me on discord and i will talk to y'all uh later bye
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
1,792 |
Hello Everyone I Hope You Are Doing Well And Today Will Be Solving Another Contest Question Vijay Font Interesting Request Name Is Maximum Avesh Show Medium Question Ultrasonication Together In This Question Giver School Subscribe Giver 2825 What is the number of the total number of students in the Class Image Bill-2012 Subscribe 556 Class Image Bill-2012 Subscribe 556 Class Image Bill-2012 Subscribe 556 Others Class in Defined by the Number of Students Difficult Task Divided by Total Number of Students Claims Pass Ratio Is Anmol Pass Middle Class Like Very Long Question Description Not Very Difficult to Temple in the World with the Greedy for Electronics Dimple Yadav Way Raw To Subscribe 502 Students To Give Extra 2002 100 Days Away On Hello How Can We Assign With Students After But Subscribe 3442 Students For Plus 2 And Divided Into To Find The Total 10 Subscribe To Hai And Unlimited Stick Pan Samadhar POSTING BUT I AM DOING TO FIND THE PASSING PERCENTAGE OFFICE CLASS AND ELECTRONIC CALCULATE THE GREAT ASSOCIATED WITH WHICH CLASS SIX POINT ONE STUDENT FOR EXAMPLE A THAT IN THE FIRST CLASS VIHAR-1 STUDENT IN THE FIRST CLASS VIHAR-1 STUDENT IN THE FIRST CLASS VIHAR-1 STUDENT PASSING BACKGROUND TO WHAT IS THE PASS PERCENTAGE IN THE 2ND YEAR SCIENCE One Month Student Nearby Student What Will Be The New Ratio Between 3301 66 Data Growth The Times And With A Scientist 0.35 6 And Times And With A Scientist 0.35 6 And Times And With A Scientist 0.35 6 And Arrested For President SS With Vaart Ki Student Singh Name Hotel Five Voters Pass Ratio Was British 300 Points 69 On One Mode Passing Student 12% Student Dance On One Mode Passing Student 12% Student Dance On One Mode Passing Student 12% Student Dance Class Generation Will Come For Basic 6 Which Is Equal To Zero Point 6 And Define More Calculator Growth 80 Mentions From A Research Best Friend For Third Class Select Class To Subscribe This Of Students Brings A New Crop Of Increase The Total Number of middle-class ific calculated I will not middle-class ific calculated I will not middle-class ific calculated I will not end with as last updated on 200 already entries priority queue and they will put element priority queue 80 one with maths growth serum extra opposition 98100 computer operate you will observe this fast and development will give ideal growth To the Will Remove Voice Role 2018 In Europe For The Next Problem Is How To Battery C Ward-1 Element 10 And The How To Battery C Ward-1 Element 10 And The How To Battery C Ward-1 Element 10 And The Pass On Sunday Morning You 2000 Points 6 Hua Hai According To Youth Motivate Increase Passing Percentage 5000 Points 75 To Twitter Growth 12.75 - 06 08 Something The Growth 12.75 - 06 08 Something The Growth 12.75 - 06 08 Something The Left Bank Point Zero Six A Improve This Senseless 0.08 Se 0383 Due The Senses 6 Typing Edit Mathematics Correctly And Now Oil YouTube Scroll Wheel Dhawan 1008 Subscribe 280 Se Aa I Will Remove This Element 12 Accident Set A Good Deed The Process Awards And What We Need To B25 Calculate Average Of This Hotel For Them To 2.1 Calculate Average Of This Hotel For Them To 2.1 Calculate Average Of This Hotel For Them To 2.1 APlus This Point 2016 Plus Vivo Point Se Jurm Dec Want To Point To A Plus Point Vivo 6 A Plus Point 083 That 2019 Live Train Status And This 40 152 Is Lineage One Ansh Ke Bhitri Ko Un 2.3 ES File Show 2.3 Ko Un 2.3 ES File Show 2.3 Ko Un 2.3 ES File Show 2.3 Yes Bhai Divided By Pointed MP3 A Recorded Ther Classes Sudhir Want To Listen More Shabd Yes Bhai T-Shirt Twenty One Yes Bhai T-Shirt Twenty One Yes Bhai T-Shirt Twenty One 97 Each Other Meet Points 72 Ek Dant Veheen 2005 98 Ki Devi Yadav Main One Also Remember And Reverse Video 300 Recent With U A View Of Created Under Growth Eight Just Enjoyably To The Maximum Solution I Don't Want To Waste It's Absolutely Hitler Delta And Electrification Of Two Souls So Let's Move To The Coding For Everyone I Hope You Are Doing Well Known Today Will Be Solving Another Contest Question Vijay Fonts In Traffic Recreation Name Is Maximum Average Muscles Medium Question Ultrasonication Together In This Question Giver School Subscribe Giver 2825 What is the number of the total number of students in the class 9 Yo Also apart from This Will Also Give Some Extra Students Under Wear British Thief The Calling to Parts Exam Unit-2 Sign Give Some Extra Students Under Wear British Thief The Calling to Parts Exam Unit-2 Sign Students Claim Pass Ratio Is Anmol Pass Remedy Total Number Of A Very Long Question Description Very Difficult To Temple In The World With The Great Indian 12345 Within Third Class Will Hurt Us British Total Of 2001 Extra Students Not Need To Say Into Various Places To Others On Overall Pass Percentage Average Increase How Can We Sign Up Issues Students After But Subscribe 3442 Students For Plus 2 And Divided Into To Find Its Way Into Positive 106 So Let's Look At A Greater Noida Pimples And Unlimited One Pan Hai Ko Pure Posting Net I am doing to find the passing percentage of which class and electronically calculate the great associated with its class six point one student love for example in the first class students in order to what is the percentage in the 2ND year student new dresses for 6th id assignment 506 destroyed president subscribe 600206 meanwhile shrank 2016 6 and define adh calculator growth between two points 104 happened from a research mentioned destroyed third class subscribe to subscribe this of students brings a new crop of increase the total number of a student in the Class Of Mid 20th August I Will Pick With Science Student At A Time Not Lost With Us Last Updated On 200 Alarm Dysentery Beautiful Priority Q And They Will Put Element Priority Q 80 One With Maths Growth Serum Extra Resist Achieve 100 The Computer Operate You Will Be Benefited Under Maximum Co Fold Development Will Guide You Through The Expected To Tell Everyone What Is The Age Of Birth Which Point Is This Point 6 Plus One Student Is Point Five Plus Point 6 A Plus One Decade 2.1 And Snow Point A Plus One Decade 2.1 And Snow Point A Plus One Decade 2.1 And Snow Point Elements From Different You With Your Point 6060 I Will Remove Vis Role 2018 In Europe For Next Day E Hai Tu Battery C Ward-1 Element 10 And Tu Battery C Ward-1 Element 10 And Tu Battery C Ward-1 Element 10 And Appointed S Possible Earthquake 2000 Points 166 Hua Hai The Country Forward One Month But With Passing Percentage ₹50 406 506 Twitter Growth Percentage ₹50 406 506 Twitter Growth Percentage ₹50 406 506 Twitter Growth Drops You 12.75 - 68 something the Drops You 12.75 - 68 something the Drops You 12.75 - 68 something the left bank point zero six the hear that is insensitive 0.08 to 0385 do the senses six fighting editor mathematics correctly and nine oil against youtube school 1.00 subscribe to are set up 1.00 subscribe to are set up 1.00 subscribe to are set up I will remove the element 12 accident set a good deed The Process Awards And What Mintoo B25 Calculate Average Of This Hotel Sum 2.1 Hotel Sum 2.1 Hotel Sum 2.1 APlus This Point Se 016 Plus Video Point 083 Lutb Dec Want To Point To A Plus Point Wave 6 A Plus Point 0283 That 2019 Vacancy 10 And This 40 152 This Lineage One Excerpt Job Ko Un 2.3 ES File Show 2.3 Ko Un 2.3 ES File Show 2.3 Ko Un 2.3 ES File Show 2.3 Me Pi Divided By Pointed MP3 The Record Date Sheet Class Student Beach Relationships To-Do Committee Area Yes Brother T-Shirt 2011 97 Yes Brother T-Shirt 2011 97 Yes Brother T-Shirt 2011 97 13 10 Minutes Points 72 A Man With His Mental 5 98 's Goddess Yadav Main One Also Remain Untouched Day Will Afton Than 100 Recent Research Child Created subscribe and subscribe the Channel subscribe Video Please subscribe and subscribe the do that Chandigarh student AP's date is a new political and inter compartmental pill do also on Android Increase in profit by adding one - com dot loot lo adding one - com dot loot lo adding one - com dot loot lo ki suvichar good morning factor and left side rate looter aur tak hum 10 glasses of another brigade total do hua hai this time trading and dimples lovely eyes attention please don't length i Plus App That When Posting Do It To Update Total Arm Rests On New Delhi Total To Classes Of Bye-Bye New Delhi Total To Classes Of Bye-Bye New Delhi Total To Classes Of Bye-Bye Classes And Subscribe And Don't Forget To Subscribe To Within Defined Growth Factor 122 Increase In Profit Wedding Man Border Delhi Will Be Listed Final Private 1000 gate increase in trophy from jet is inter pass account that winters total don't return we have account plus vansh back total account plus 5 that ace singh bittu we have aunty operating account around the country yes brother total cont my voice Se Type Casting Established A That Bollywood The Subject Matter Gurjar Delta Increase In Profit Effigy Of One More Person Account Student And Its Called S O N B To Variables And Updated On Priority Basis Information Report Meter Profit Student Is The Soul Will That One Month Old One To produce a side reaction add coriander leaves pisces e want the total number of students to un research sign often students are well s classes are absolutely powder top muslims pq doctors and what will get elected president class which will be the updater growth in total available on Yesterday morning updated with no average of the highest adult update the lift is a side not bollywood dot pass account is a good total don't oo that a Dortmund plus updated password similarly the total plus that PTU doctor updated tu with updated oon's flower ash Ad Interpretive Unwanted Sexual 12 Everest Total Lal Mirch Anchal Vidmate App Happened That Bigg Boss Like You Who Were So This Note Panch Kund 's Specialty Student Sorry For The Missions 's Specialty Student Sorry For The Missions 's Specialty Student Sorry For The Missions From March According To Total Student Android Member Total Amount Are Lemon Juice Up To It's been a long time Akshar Update
|
Maximum Average Pass Ratio
|
find-the-most-competitive-subsequence
|
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam.
You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes.
The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes.
Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2
**Output:** 0.78333
**Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
**Example 2:**
**Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4
**Output:** 0.53485
**Constraints:**
* `1 <= classes.length <= 105`
* `classes[i].length == 2`
* `1 <= passi <= totali <= 105`
* `1 <= extraStudents <= 105`
|
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
|
Array,Stack,Greedy,Monotonic Stack
|
Medium
|
402,1159
|
442 |
MP3 In today 's video, we are going to ask a question, 's video, we are going to ask a question, 's video, we are going to ask a question, Late is speaking, Find all duplicate sin and Hey, Given and Interior is speaking, a question from AIIMS where all the features in this range are definitely subscribed to. Once again it is going to come again that Ghrit but if you have to write between the size of elements and the word of adventure then it should be okay, it should have linear time complexity and should not take any extra space hmm okay let's do it like I have this note like I have this, so if it has to come three times and two times, then it is a very good way to get the output, first share it and if there is any new element, then for the time being and that's why in the last I have subscribed from the village, is it in the village or There is no and the default means it is saying set whom name white set white to white if it does not come we white does not do this then return zero okay so I see that if it comes zero. Not only in our map, we see the meaning of cleanliness for the first time, I have to prove it, I have to wander inside the map, this white inside the map and inside the map, this white inside the map and inside the map, this white inside the map and its but if but if but if suggests this meaning first. This means that we have to return but we do not mean that we have to return a question, that is, we have to take a new space to fold a result, but as it is, we have taken the step. So we will not be able to take that, the second one is something like this, if you have not seen it before, then you will not be able to implement it, so each one has a range, its hatred interior adjusts inside it and from inside subscribe to now. How to use the till function because from each element till the end, there will be n own relation equivalent intact, meaning if I do a - in any of these and then a - in any of these and then a - in any of these and then go to that index as I said in bread fragnet. - It has become Sawan's Sawan, I fragnet. - It has become Sawan's Sawan, I fragnet. - It has become Sawan's Sawan, I can read the index, not Star Fund, the index must be uniting it, ice cream is fine, as if I have picked up some more element, I know, I am uniting 3434 - 193 index and know, I am uniting 3434 - 193 index and know, I am uniting 3434 - 193 index and adjusting the third element, it is correct, like Here someone has picked up a lava, two has been picked up, okay so 2 - one that one of their fast up, okay so 2 - one that one of their fast up, okay so 2 - one that one of their fast index, if I do their one inducers, then the phone calls on it, first - 151 - verb - 134 and we will treat it like that, they will become - verb - 134 and we will treat it like that, they will become - verb - 134 and we will treat it like that, they will become intact and intact. That means we will go to 501 237 and make it - okay, 237 and make it - okay, 237 and make it - okay, then we will do it, then we will go - straighten one to two, then we will do it, then we will go - straighten one to two, then we will do it, then we will go - straighten one to two, okay and here and cut this, okay, so here we made it - 2 - 121, so here we made it - 2 - 121, so here we made it - 2 - 121, so if we don't get it. Hai Meghvar and Megh - - - 121 basically elements so I am saying here Fennel - Fennel - Fennel - Destroy daily life from 1313 then what am I saying in the second if we say numbers of and minus one then we toss 3 - If we speak our mind and minus one then we toss 3 - If we speak our mind and minus one then we toss 3 - If we speak our mind then numbers of 2012 Destroy the units Now here's the problem What brother can it be Matters like here I said he did vote's free think What's the script here - Seven Is the script okay so - Seven What's the script here - Seven Is the script okay so - Seven What's the script here - Seven Is the script okay so - Seven That when sister's value - Seven If it happens - 7 - That when sister's value - Seven If it happens - 7 - That when sister's value - Seven If it happens - 7 - I feel like I will set the alarm, we all will come - I feel like I will set the alarm, we all will come - I feel like I will set the alarm, we all will come - what should I do if he doesn't practice, you are positive, Billu, I said that math dot Edison line is fine, then an option will start coming brother, what are you doing, negative, this is this, I, Since I - 21 Questions Related to it is okay, that is, - 21 Questions Related to it is okay, that is, - 21 Questions Related to it is okay, that is, whatever will happen after this look is possible, then I have to see that the person - the person - the person - 101 result dot nick dot Now like we are fine here but since - will - will - will go Do this 10 to 12 times. Set the alarm set for negative. Set it again. Let's see what happens. Submit for Magha Makar. Okay, accept. We used two cloves. Now we have a loop condition and express. But now we Now I am using both while doing the work I will give 2012 I will do it and see if it is negative then I will tell him to - - - 140 Episode 229 Frustrated Two Instant Soldier This one you if it is negative then I will give this chord to this three -The is negative then I will give this chord to this three -The is negative then I will give this chord to this three -The quarter is that I will cut these, it's okay, if not Meghnad, then why not make it, then I will check it again - - - - - - - - - - - - Okay, now let's go, okay, then subscribe to Jhala's information - Sanjeev and what will happen to Jhala's information - Sanjeev and what will happen to Jhala's information - Sanjeev and what will happen forever? Valid in the next course of elements, pick it up, it will be valid, so we are using that information and the solution is Jhaal
|
Find All Duplicates in an Array
|
find-all-duplicates-in-an-array
|
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1,2\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
* Each element in `nums` appears **once** or **twice**.
| null |
Array,Hash Table
|
Medium
|
448
|
594 |
harmonious sequence subsequence so we Define a harmonious array as an array where difference between its maximum value and its minimum value will be exactly one so given an integer array written the length of its longest harmonious subsequence among all possible subsequences a subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements so what do you mean by subsequence first is as I said here if the given an array let's say one three two something okay one two three four let's take the array 1 2 3 4 so if we take the radius subsequence which can be formed from this array could be one comma 3. one comma four or re-enter array one comma two can three re-enter array one comma two can three re-enter array one comma two can three comma 1 be a subsequence no why those three and one are the elements of the array original but if you see the order first is three then is one but here you could see first is one then is three so the relative ordering of the elements is not the same that's what subsequence means either you can do it some other no elements on the array but the ordering of the elements whatever you get it must be same so here one three one four one two after one three after one four so in this the relative order is being preserved but if you see three comma 1 no this cannot be a subsequence that is what so here we need to derive the largest harmonious subsequence harmonious in the sense if you get any array let's say one comma three the maximum difference uh sorry the difference between the maximum minimum element of that array should be exactly one they said is it 1 here 3 minus will be two no this cannot be harmonious subsequence this is a subsequence but no not a harmonious subsequence if you take 1 comma 2 then yeah it's a subsequence is it harmonious two minus one is one yes exactly one difference between the maximum and plus minimum element this one yes this is a harmonious subsequence so how many subsequence is a subsequence in which uh the difference between the largest and smallest element in that subsequence will be exactly one not even less than or equal to anything so it should be exactly one which will be equal to one so now let's take this array so we have taken this array one three two five two three seven so if you see in this example the longest harmonious subsequence could be 3 2 then 2 3. of length 5. so this is the longest harmonic subsequence we need to return the length of that how long is how many subsequence so how do you get this so if we actually observe in the array okay let's say we have one so for one how to form a success subsequence let's look at the next great element is 2 is presented yes next to another two we have yes this is one subsequence form then three seven you can't then if you move to three so for three you have to look for 4 is plus four percent no this is a single subsequence So currently this is the longest one so next move to two so if you move a 2 start from here so three you have the next greater element and how many twos are pressure One Two Three or little three and three twos are present so this two these two and this two this one three and next one three so this is what we have here right yeah the ordering is what I've written is wrong here so it should be three comma two comma three yes this is the longest subsequence because its length is Phi this length is four so this is which is maximum this is so after two is and five so if you take 5 a 75 no S7 is six no then you move to seven for someone else there is no other seven maybe some other eight also this that will be a single subsequence how many subsequence uh I mean that cannot be a subsequence actually any other element you won't have a question difference between maximum movement element in this uh subsequence will be zero which cannot be possible so one two three subsequence which we got how do I subsequent in which the largest one is of length five this is what we need to return but what is approach to solve a problem this is a normal truthful suppose like you iterate over the array we go of n Square Times because each element you take again start from the array and you look for the element either this element or one greater than that so normal for suppose bit without doing that how can we solve the problem so for that what we will use is we'll use hash table here okay so for using hash table so the hash map what you say in Java or C plus so key comma value what we have here so here the key will be the element of the array and value will be the number of times occurring in the array okay so if you take one how many times only once next three how many times two times next two how many times three times so 2 is appearing three times then 5 comma 7 both are appearing only months so this is the hash map we have now so with this mapping how do you solve a problem so what we do is now iterate over this map start here for each key in the math for each here look for one look whether 2 is present a q a key greater than this key is present or not yes it is present C for one is two is present yes we have two so add the count of these two three plus one how much will be four so we'll have a variable called length max length so max length will be so as you know max length will be nothing but Max of length comma max length so length is 4 now how do you get 4 so you iterate over each key value pair in the hashback you check whether the now a pointer is smart into one here so when the pointer is pointing here for this one you check whether the next key higher than this is will be 2 is present in math if it is present then add the count of this also we have to add the count of this one look for whether we have a key that is equal to 4 no not so will not compute any length here because you know in this case you if you follow a subsequence how many subsequence it will contain three how many times two times length is 5. so maximum of 5 comma 4 will be one it will be five so max length will be limited to 5 as we got here this is the and what they told here is we need not return the how many subset we just need to return the maximum length of the helmets that's why we are just finding in this way if you need to return then you have to use the other approach which I explained earlier so next method is 5. check whether this key create greater than this will be 6 is present in hashmah no it is not so this cannot be formed by a harmless so that will not be having any harmonious subsequence so you had funny finally we have got the Hummer subsequence Max of maximum fine this means what we so basically first we create the hash map store all the values and the number of times it's happening the frequency of each value in the array so once you store that I took over each key in the hashman and check whether the key greater than that one greater than that is present then final length and compute the max length variable that's good she lies to zero and length okay length can be inside only so this is fine now we need to create a ice pack so let's say another map of type in command so it's nothing but frequency method okay so now for each element in the array so frequency map of the given number plus so value will be incremented as such so once this is done so now so for Auto ID in frequency map okay let's say ink number equal to i t Dot first since it's first and in count equal to it dot second so yeah whether this number plus one is present in the frequency so if frequency dot find of num plus one how do you get to know whether that is presented frequency is not pointing to the end if pointer is point due to n that means that particular number is not present in the frequency is not present if it is not pointing to end then that particular key is present in the frequency map if it is present then find the length so let to count y count that is count of that particular key number and you take the count of num plus one also so now compute max length equal to Max of max length common length so at the end just return the next length yes now we will run this object okay it should be done or since we had defined it as length so we'll Define length also outside the loop here so let length P equal to zero yeah and we use the arrow Mark here it DOT first uh Arrow Mark with that we will be doing if we give Auto dot ID from idea Point frequency map dot begin to ideological frequency and the ID plus if you do in that way then we have to use that otherwise we'll be using dot Outlet so we see the Java logic also so first you create a hash mark integer commentation max length in challenge to zero foreign if it is present then whatever default you have get that okay not whatever okay value you have get that plus one you increment if Now default we initialize it to zero and increment the value by month so then each number in the key set of traffic management so count you get the count and if you find that particular key of none plus one in the frequency then you find the length that will be count plus the Tranquility of value of the number plus one and then you find the max length will be equal to Max of Max and comma length so we shall submit this also a successfully submitted if you understood the concept please do like the way and subscribe to the channel will come up with another video on the next session rental and keep running thank you
|
Longest Harmonious Subsequence
|
longest-harmonious-subsequence
|
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.
Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.
A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[1,3,2,2,5,2,3,7\]
**Output:** 5
**Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\].
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** 2
**Example 3:**
**Input:** nums = \[1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Sorting
|
Easy
| null |
334 |
hello guys today we will solve lead chord problem 334 so here we have given one array in that we have to find a triplet such that I is greater than J is greater than K is a valid you know so uh here we have you know first of all if we want to do this thing using Brute Force then we can start from the last element and then we can count for five is there any element is less than five then we can also you know check further if it is less than or equal to I 1 naught and like that we can solve you know this problem using brute force and that how time complexity will be of n Square because first of all we have to you know uh run four five then if it is like here three then we will increase the count then also we will do the same thing here also so like that now the second here our constraint is uh five into twenty four five so we have to solve this problem is in off and time complexity so first of all like here if we start from the one then we have to get two elements that are greater than one like two and three so for that we have one algorithm like we can write a simple algorithm let's assume we have two number first and second because we want to get two more numbers if we have one then we want to get 2 and 3 so our both numbers will be very big you know and I will tell you these things why these numbers are very big float of infinity and now we will run a for Loop in our number list so nums here first of all we have to get the first number so if our first number is less than equal to our I in that scenario our first number will be I so now let's assume if we get one year then our first number will change here into also our first number will change in three also our first number of instance four five okay but if we got our first number for one so now our first number will not change because you know this is the minimum value that we can get for the first value like that for second value also here we have else if condition if our second is less than equal to I in that scenario so our second number will be I so uh like for first number we have to get the minimum number and the four second number also we have to get the second minimum number and like here now our first is one second is two so now if we get any number that is you know greater than first and second then that is you know here we get a triplet so we have to return true and if we didn't get any output there then we have to return false so basically first of all we have to get the minimum value so whenever we're starting from here like here we got 2 1 first of all too so now our one is smaller than two then we are you know an hour of first is one and second is the second didn't sense till now because five is you know it is not less than uh our yeah so in here like our second will change then here this zero is less than our first so now it will change here also our second is you know four is less than five so it will changes and then for six it will return true so like that this algorithm will work now let's try to some run this code okay here we got some error so FR second floor float for I in nums if I is less than equal to if second is less than equals if in the else we will return true otherwise we'll return four uh it is right solution but currently it is not working I think we have to remove this thing if it is less than equal to okay go back if F less than equal to I then f is equal to if else if it's less than equal to I yeah it is right answer but it is not working currently I cannot understand why it is not working oh give me one second let me go to our solution not solution summation actually here so first if I oh okay we did a very big mistake actually here we have to compare with I if I is less than equal to our F then we have to change it sorry I did a very big mistake here now run it yeah it is working for real fine and now submit it as you can see that it is running perfectly fine there is no problem so like that we can solve this problem in often time complexity and if you face any you know difficulty in this solution then you can comment below thank you for watching this video
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
1,443 |
all right let's look at this problem called minimum time to collect all apples in a tree so essentially what is given to us is we are given an edges array which gives us all the edges of the tree in an undirected fashion and we also given a has Apple array which tells whether or not a specific node is an apple or node so and then finally the tree looks like this basically you have this tree and you have three apples in it and the question is consisting of and vertices number from 0 to n minus 1 which has some apples in their vertices you spend one second to walk over one edge of the tree return the minimum time in seconds you have to spend to collect all apples in the tree starting at vertex 0 and coming back to its vertex meaning that you start from 0 U and at 0 and while you do the traversal you collect all the apples or you touch all the Apple nodes and you go back to the tree now you define the shortest such path essentially all right so let's quickly have a look at the example in a whiteboard so we go and let's look at this tree so it's zero one four five two three six and these are the two three Apple nodes and so the path that's taken is obviously now uh you go from 0 to 1 to 4 back from four to one now that's the interesting bit to notice from photo you don't go back to four to zero because there is another Apple to pick nearby so you pick up that apple and then go back to zero then go to two and then come back and total this is uh total number of one two three four five six seven eight so total there were eight edges that we had two Traverse and so how do we solve for this so essentially what we're really interested in is finding first of all we're interested in finding whether a node you will Traverse a node right essentially uh like we won't travel six we won't Traverse three because they are not apples um now zero is also not an apple one is also not an apple but we had to visit them why because a sub tree their sub tree had an apple right so if your sub tree has an apple then you would often definitely have to visit those nodes visit their parents right so we had to be able to visit four you had to visit one and zero similar to people to visit five you had to visit one on five now one thing to note is if uh we have to visit from 0 to 4 and back to zero it will take two plus two right and similarly if you have to go from 0 to 5 and back to zero again it will take two plus two so if you do both it will take eight but that's not really happening here we are just taking six steps right so we go from uh 0 2 1 2 4 and then from 4 to 1 to 5 and then from 5 to 1 and back to zero one two three so one two three four five six right so and this is only six so how do we figure out that it's not internet six like how do we really solve for it so how about we only look at uh like how would it build from the leaves like in like a post order fashion so what I mean by that is how about I only look at this right just look at this portion first and this portion will say okay my left child is of Interest my right challenge is of Interest so whichever loads of Interest its parent has two drivers uh twice the distance right to sort of or like two times the edge uh to sort of go to that child and come back so from its left child one has to for this for its left child one has two Traverse two steps for its right child one has to travels two steps now one is not an apple but it has subtree in its apples so for one bit two travels to get four two for one to collect all the apples it had to Traverse four steps right two plus two now what about zero suppose zero will say hey do I have to visit one and the answer for that is yes because one has Apple in its a sub tree so one has happened it's up to that zero has to visit uh which zero has to make two steps and one had already made four steps total it becomes six steps right so we're building from the bottom up we're building from the leaf towards the parent so as we do Post order traversal so we do post on a traversal right and we sort of build up the paths right and add up the parts and there are two kinds of nodes one which okay node uh visiting node to visit and when will node be visited there are two cases if it itself is an apple or has Apple in a sub tree right then it has to be visited and if the node has to be visited that means then its parent will take two steps right to visit it and come back to it so that's the logic right let's try and build it in the code to make more sense of it so let's go to code and so what are we saying so first let's quickly build the tree based on the information that's given to us it should have just given us the regular tree but it has not given us a tree instead it has given us uh this uh Edge and has Apple so let's build a tree based on a net essential space representation so we start with a list of Twitter let's call it adjacent cellular sequence to new explain this point I equals to 0 and less than n Plus so let's dot add new yes write it like how we build a graph I'm just building the adjacent Series so now I go through each and every Edge so for each Edge in edges U is Edge of 0 and V is as open so this is a sort of an undirected graph let's just add the array from 0 to u to V as well as V to U so I do like you can see let's still get a hue add V and in the adjacency list of V we add U right so our tree is ready and on the trees okay then we do uh so we need the path so let's do just to return uh just uh shortest Apple path or whatever shortest path to shortest path length to collect apples that's what I'm interested in I'll start from index 0. and I will need the adjacency list I will need this has Apple who is apple right and I'll also need where am I coming where I'm who was my parent so for zero the parent is nobody uh we can maybe just to do zero I guess I don't know okay so that's fine now let's do end and this is what we are really interested in finding and this is my index of the node and this is the adjacency list based representation of the three and this is an array that tells us which nodes are apples and we also need the parent okay so now what do we do um first we go to its children right so first we go to its children then we go to for each children so for each uh call it neighbor in adjacency list dot cat index of now for each children we go so we add up The Path sums for his children right so in uh this is called path length close to zero so we do for plant plus equals to okay so we don't want to go back to the parent right uh like where we came from first so it ignored that bit so we do if a equals to parent continue and then so we go path length plus equals to basically we want to go figure out the path lines for all of your children really right so path length is equals to you shortest path length to collect apples uh this neighbor this adjacency list this has Apple and now the Sprint will be the syntax now order for the leaf nodes right so they will not be any children and so they will return zero I guess they will return this zero so you will return this path length now let's say I am at the leaf node which does not have any children so it's fine now whether or not that guy um if I'm at if I'm I wanna so this is what I want to return to my parent so I'm gonna return so that based on two things uh so if I myself am a uh like a red node like an apple right so if has Apple of if that is one case or if they if there's an apple in my substrate so how do we know if it Apple in my subtree that would just be this path length will tell if this path length is greater than zero that only means that there is an apple in my subtree right this is why I have to drive or otherwise why would I travel down if I have to travel down to get to an Apple that means uh I have to be visited so in either of those two cases I'm gonna do uh or just like maybe you can do path length plus equals to 2 right so my child my parent has to travel two steps to reach to me that's what uh we're telling it uh but what about uh index 0 if index 0 is an is itself an apple index 0 is does not have any parents so let's ignore that case right uh so if this has to be that index is not equals to zero right only then uh that means I have a parent and if I have a parent then my parent will have two drivers two extra steps to visit me if I need to be visited and I need to be visited if I am an apple or there is an apple in my subtree then I need to be visited so I need to visit that means the path line would be plus two so that's just the logic um let's run I guess uh here the three test cases pause let's submit and it gets accepted
|
Minimum Time to Collect All Apples in a Tree
|
minimum-distance-to-type-a-word-using-two-fingers
|
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex._
The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`. Additionally, there is a boolean array `hasApple`, where `hasApple[i] = true` means that vertex `i` has an apple; otherwise, it does not have any apple.
**Example 1:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,true,true,false\]
**Output:** 8
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
**Example 2:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,false,true,false\]
**Output:** 6
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.
**Example 3:**
**Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,false,false,false,false,false\]
**Output:** 0
**Constraints:**
* `1 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `0 <= ai < bi <= n - 1`
* `hasApple.length == n`
|
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
|
String,Dynamic Programming
|
Hard
|
2088
|
48 |
hey what's up guys Nick white here I do technically stuff on twitching YouTube check the description for all my information you can I post a bunch of stuff on my picture on patreon if you want to I'm having a tough time talking support me or whatever and reach out to me on discord patreon whatever I try and get back to everyone this is a very famous problem that I was looking through I was like I didn't I can't believe that into a video for this I've gotten this in a bunch of interviews and I think it's like the best 2d array problem like medium level give you a great understanding about 2d arrays but yeah let's just let's do it so you're given an N by n 2d matrix representing an image meaning we have a 2d array we're given if you don't I would assume you guys know what a matrix is or 2d array like this where n by n meaning like rows and columns we have the same number of rows and columns so like in this example we have three rows you can see here and then we also have three columns right and by n so they've represents an image rotate the image 90 degrees clockwise okay what does that mean so I would just say imagine picking this 2d array up and just rotating it clockwise and like you would see like if you just pick it up and rotate it like you would see the top is gonna you know you can see it's gonna come and it's gonna become the right side and then the right side is gonna go to the bottom all the sides like shift over one so you know what I mean like the right goes you guys know what a clockwise rotation is so you know 1 2 3 becomes the last column you know whatever I was just saying also you know 7 8 9 is gonna become the left you know 3 6 9 is gonna become the bottom but yeah so we just want to do that we just want to rotate it and there's a strategy to do this I would say check out the video transpose matrix I think I did that one before because that's a technique we'll use here one more thing to note is before we do this you have to rotate an image in place which means you have to modify the input 2d array to luckily do not allocate another array for the rotation so we're not using extra space this is a void method meaning we don't have external date structures we're not returning anything we want constant space solution and if we want to go through the example really quick right like I said you're taking the first row becomes the last column basically in the last row becomes the first count one two three last you know last column seven eight nine first column and in this example five one nine eleven becomes last column then in order of that right column wise yeah but it is difficult right it's difficult to take just looking at it if you just wanted to loop through and take one two three and then like you know what do you do if you're looping regularly you loop like this where you go one two three four five six seven eight nine so if you wanted to do one you it's what do you swap with the last element but then the three is over there you want the three on the bottom so it is kind of tricky when you first think of it but if you do it in two steps it's a lot easier because what we'll actually do is I think I can paste this there we go I wrote this truck I wrote this out and then I found this in this discussion I think it's like really useful to explain this so this is in the discussion I think it's like some guy named lucky idiot or something like that the so shout out to you lucky idiot but the idea is to transpose the matrix check out another video where I explain this but basically what you're doing is you're looping through and you can see what's happening is you're swapping the diagonals stay the same but you're doing a like symmetrical swap on the diagonal it's pretty much so you see two and four here become four and two three and seven get swapped to seven and three you could see six and eight get swapped to you know eight and six and that's it and then once you have that basically what this is doing is it's taking the rows in turning them into columns it's not making the first row the last column which is what we want but it's making the first row of the first column second row second column third row third column and that's going to help us because once we're in this form it is pretty easy to go to this form because what we just want to do at this point is just okay we'll loop through each row 1 4 7 and we'll have a pointer at the beginning of the row and the pointer at the end of the row column wise and we'll just go towards the middle like a two pointer approach and just swap values so you swap the set the one in the seven you get the 7 and the 1 the 2 and the 8 and the 2 the 9 and the 3 and the 9 so what you just do it in two steps and then what happens is you do get this thing where you got the first row you get that rotation it's just about making the rows into columns and then kind of reversing the column order using a two-pointer approach so that's the idea two-pointer approach so that's the idea two-pointer approach so that's the idea here let's write it out and then I'll trace the route for you guys really quick I have this I wrote this trace out right before just so you understand so I'm gonna grab the length of the array because it's the number of rows and columns so we're gonna be looping always a lot of loops and 2d array problems so I would suggest making a variable for the length so I less than rows I plus this is just a standard loop through the 2d array J is gonna be set to I so pay attention to that J is gonna be set to I and I'll explain that in a second so this loops through the rows this loops through the columns and then we do our little switch this is transpose matrix so we're gonna do a temp variable to the current element just a regular one we regularly looping then we're gonna say okay matrix of current element is equal to the swapped value so the row and column value will be equal to the cop the column value as the row and then the row is the column and I will explain that right now and then because we lose reference to I've Jay cause we set it we change it here we have that temp variable so to save the reference or whether we can do this and this is how to transpose the matrix and let's look through the trace what this is doing is in our example for like if we have you know 1 2 3 4 5 6 7 nine then at zero the element is one right we're just going to do a swap it's gonna do nothing because zero right it's all the same like the row and column values are all the same but we're gonna loop zero one right now we're at zero one that's the next current element so what we're gonna do is we're gonna swap the position at zero one meaning this two with the position at 1 0 so it swaps on that little diagonal right there it acts the column acts as a row for reference and then we swap these values to do that little switch and you know that swaps the 2 and the 4 makes it 4 and 2 and then it gets to you know 0 2 then you're at 3 and you do ok 0 2 equals to 0 so the 3 is equal to the 7 this only works for a perfect square by the way that's why it works here and you know there you go you got that perfect swap and then you go on to the next row which you started that 5 then you go on you go to the 6 you swap the 6 and the 8 and then you're at the 9 so you set the j2i because you want to move along with the rows as you do this and that's pretty much it I think it's pretty self-explanatory at that point pretty self-explanatory at that point pretty self-explanatory at that point then we just want to do that two-pointer then we just want to do that two-pointer then we just want to do that two-pointer approach I was talking about the rows were still gonna loop through casually right like I was showing you here the rows for the two-pointer approach the rows for the two-pointer approach the rows for the two-pointer approach when we're swapping the left and right values as we go inwards we still want to just go row by row so we're gonna go for a row and then go have the column values one at the beginning one at the end go inwards swap and then go to the next row so the rows we're still going to go up to n but the columns were only going halfway because it's two-pointer if halfway because it's two-pointer if halfway because it's two-pointer if you're familiar with two pointer approaches we just have a pointer at the end and beginning and we meet in the middle so we have J is less than n divided by 2 which is the middle and then we just set a temp to the current element matrix IJ we say matrix IJ current element is equal to the ending count so the beginning column values the first pointer is equal to the second pointer which is starting from the end so we do the length minus 1 get the valid index - J the position and get the valid index - J the position and get the valid index - J the position and this will be the same distance from the beginning to the same distance from the end these pointers as they go towards the middle and then yeah then you just want to set that to the temp like we did just above in there you go that's the two pointer approach to flip the columns get them reversed 100% hundred percent get them reversed 100% hundred percent get them reversed 100% hundred percent solution it's linear in regards to the number of elements in the 2d array so Oh some people say o of n for n elements in the 2d array or o of M times n for a number of rows times columns but these are not nested they're separate and we not using data structures so I call this a linear solution constant time linear in regards to number of elements in the array but I love this problem I think you know understanding this is you know really important maybe watch the transpose matrix of your I'm in trouble and also you want to know it incorporates a lot of methods like two-pointer two-pointer two-pointer swaps and you know transpo transposition so that's it for this video I thank you guys for watching I appreciate every single one of you and I am gonna go and do some more problems right now so I'll see you in the next video alright see ya
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
926 |
hey everybody this is larry this is me going over day 10 of the august league daily challenge hit the uh for i guess hit the like button the subscriber and join me on discord let me know what you think about today's problem i just want to someone uh on my discord actually recently gave me a uh thing uh so i started doing these lead code daily problems on april 1st april first day on 2020 um you know that's when they start having them and today is august 10 so that means that and i've done every daily problem and that means that i'm actually at a 496 day streak so i'm close to 500 so let's celebrate that somehow come join me on discord and give me some support and maybe i will figure out something fun to do or something i don't know anyway so today's farm is flip strength to monotone increasing um yeah so i you know usually i solve these problems live so if it's a little bit slow fast forward or skip ahead or whatever you need to do okay let's actually read the problem finally if it consists of zeros followed by some ones you're given okay so basically for this one okay so this is just going to be you know um brute force in a smart way right you can maybe call it greedy or something like that but i put i think i visualize this as brute force but basically my understanding is that okay so you are given a string and you want to convert it to some variation of uh x zeros and y ones followed by um so something like that right and it can have zero zeros or zero ones or so forth so basically we're just trying to get something like that so then here then the idea here which is why i could say brute force is that we just try every possibility in a smart way so the um by every possibility i mean that there are only n of them maybe n plus one of them uh off by one that was hard but basically you know for you know you have these and then these are all the possible strings right so one at a time you can think about them as moving the ones from right to left and then dot all the way to one right so basically the idea is okay now we wanna do a you know do a way of counting such that this is the case right we wanna brute force this because the only n or n plus one all of n say possible things to check um so for me that brute force of course you have to be smart about it because n in this case is ten to the fifth so you do a naive brute force of n and then you know the end of these and then you do another loop through the string that's going to be n squared and that's 10 to the 10 and that's gonna be too slow too sad and tlg you go sag right is that what the kids say but yeah but it turns out that because i think one thing that to notice is that because if all these things are zeros and all these suffixes are ones you can actually pre-calculate um or you can actually pre-calculate um or you can actually pre-calculate um or just count how many zeros and how many ones are there in the prefix and of course because they're only two digits they're also um complement of each other so you can do things uh that way um there are also a lot of different ways to do it you could do it with prefix some you do it with i guess it's just prefix some really but you could do variation of prefix um you don't even need prefix sum uh by that name but yeah and maybe suffix some or just re doing reverse or something like that so let's get so okay i know that i've been going fast i have a lot of ideas um but that's basically it because you know it's just about putting them together because basically you know matching let's take this one say that means that we want to say okay for here we want to count how many ones are there in the prefix right because all those for all those ones we have to transform them to zero yeah and that costs one and for this suffix how many zeros are there in the s well again yeah um again that just sums it to the number of flips and actually now that i noticed that i know that i said a lot of stuff about prefix sum of suffix sum you can actually just do one count for the table and then maybe do a sort of a scan line from left or from right to left back um i think that should work um just kind of check if statements and stuff like that uh maybe it's a little bit more confusing i think um i mean it's not confusing i think so i know that i talk a little bit more here on these streams than i do if i was doing on a contest or even an interview because if i was an interview i would go right into it to be frank because time is of the essence but right now i'm thinking about when i say confusing i don't even mean that confusing or that hard you can reason it out very quickly with some if statements or just going through the cases but when i'm doing it in a competitive uh manner um you know this is maybe i'm like if i were to kind of look at this engage myself i would say this is probably a five minute problem for me maybe four minute problem something along those lines and if i make a mistake maybe six seven minutes but something along those lines um and you can watch me do problems during the contest if you know and i have that like internal clock right and then however if i do it in what i say confusing way it just means that there are certain things that i have to prove and think about edge cases right so if i don't have to think about edge cases then i probably say one or two minutes maybe more maybe less um and you know that's maybe that doesn't mean that much to viewers at home and you know whatever but when you're doing competitive um every minute counts and every you know tie breaking thing matters and stuff like that so that these are the things that are going for my mind um and that's why i like the prefix some version better because it literally is it's the statement right so given you know some zeros and ones you literally just ask yourself okay you know given the given that we have seven zeros how many ones are there right and given that they're i don't know uh eight or nine ones how many zeros are there in s right that's a easy query with prefix sum that i'm very familiar with where on the other thing where i don't know if i'm doing transitions um i might have to worry about it a little bit more of like okay did i do this transition right i could have typos there are cases and it's something that maybe i don't do as much with respect to coding familiarity um but that said i think that's an all of one space solution where prefix summaries is of n space so we definitely could go do that um so i know that i talked a bit here um and now for the purpose of learning i'm going to try to do the over one space and i don't know maybe i'm wrong maybe i could get this wrong it's not impossible but yeah um so basically okay so first we want to start at this comparison with this string right so how do we do that well let's look at n is equal to s first and then we just do maybe once is equal to zero and then for x is equal to s uh if x is equal to one once and you can do this in a one-liner i know one-liner i know one-liner i know but i don't know okay fine let's just do something like this one um for x and s if x something like this right um you do it in a couple of ways but okay so this counts number one so i think even x dot count one maybe like or s right i think this is actually good uh so yeah let me point out i don't know all the apis all right because i'm always jumping between like four or five languages so i'm always not super sure about what the apis are to be honest um but i know what i want to do just that sometimes it's not okay so now this has number ones right and then now okay so we also keep track of the best answer and we can actually start best off with the number of ones and then now we want to shift this thing to one at a time um shift there right so now we just go for i in range of n minus one so then now what does that mean okay so what this means is that if s of i is equal to the only two possibilities right so this is what i'm talking about and that i have to kind of think about it slowly and deliberately so okay so if this is zero um okay so we're now comparing this to this right so if s sub i has a zero here what does that mean well that means that the ones are the same and this is a little bit awkward so let's just do because once it's a little bit weird okay let's also do zeros uh it's equal to zero um let's just say that in this case zeros is the num um number of uh flips from one to zero and one is the number of flips from zero to one and also at this point to be honest if i was doing it with prefix sum i would be done by now so this is why i you know maybe it takes another minute a bit close to it to be frank um because i've done prefix sum a lot but yeah so now if s equals zero what does this mean to the states right well because in here what does i represent for us i represents the index in which now we're matching a one so this is if this was zero that means that we have to flip this zero to a one right um so that means that's zeros increment by one yeah and then that's it i think yeah maybe that's it maybe that was not that hard and then else if i mean else but this is if s of i is equal to one but i just want to do it for viewers at home to visualize that means that if s is equal to one that means that we no longer have to convert a zero to a one so you have something like this and best is equal to min of zero zeros plus ones and best so i think maybe that's it maybe i was wrong on this and how i worried about the complexity well let's take a look at some answers be uh some test cases before we say that but yeah but i would still admit that if i had done this because this looks too easy almost and to be honest if i did it with prefix sum i would have it's all about confidence when you're doing on a contest on an interview you have you know 40 minutes or whatever so you have time to kind of talk for these things with your interviewer and your interviewer will you know you're talking them you're communicating and you're just going for different things right um but yeah so let's actually you know try more uh but yeah but you know during a contest um confidence is very important so that's why i would have gone for the other one because i would be more confident about that one but here it looks just too like if i wrote this without any explanation you might be like hey what did larry do here right so i think that's kind of a little sketch but let's give it a submit okay it looks good so yeah i guess it wasn't that bad once you do a reasoning but that is the point where is i have to slow down for the reasoning and i don't trust this one that much even though it turned out to be ac okay so that's all i have for this one let's go over where i quickly get even though i think i really did um so this is linear time because it just goes for the way to put in linear time this is also linear time hopefully this is easy to see because you also go for the array backwards um one at a time and yeah and this is obviously constant we just do like three or four things over one number of things um yeah and so this is linear time and you can easily see that this is linear oh sorry constant space because we only have three variables or four if you count n five you can i but okay of one uh number of variables so it's gonna be linear time constant space and that's all i have for this form uh hit the like button hit the subscribe and join me on disco let me know what you think about this farm uh i do try to explain this a little bit slowly so this video is a little bit long for probably a yeezy bomb i don't know let me know what you think i'll see you later stay good stay healthy take your mental health to uh and have a good rest of the week see you later bye
|
Flip String to Monotone Increasing
|
find-and-replace-pattern
|
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the minimum number of flips to make_ `s` _monotone increasing_.
**Example 1:**
**Input:** s = "00110 "
**Output:** 1
**Explanation:** We flip the last digit to get 00111.
**Example 2:**
**Input:** s = "010110 "
**Output:** 2
**Explanation:** We flip to get 011111, or alternatively 000111.
**Example 3:**
**Input:** s = "00011000 "
**Output:** 2
**Explanation:** We flip to get 00000000.
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
| null |
Array,Hash Table,String
|
Medium
| null |
1,712 |
hi everyone it's albert happy new year and this is the first decoding video of 2021 and today let's solve the median question from the contest ways to split array into three sub arrays the question statement so we are given an integer array and we will say a split of an integer array is good if the array can be split into three non-empty continuous sub-rays into three non-empty continuous sub-rays into three non-empty continuous sub-rays and we will call it left mid and right sub-arrays sub-arrays sub-arrays and then a sum of this elements in the left sub-array should be less or equal to the sub-array should be less or equal to the sub-array should be less or equal to the sum of the median sub array and the sum of the median sub array should be less than or equal to the sum of the elements in the right sub array and we have to return the number of good ways that we are able to split the input numbers array for example one the nums array is a array of one and the only good way to split this array is with elements of one in each and for example two there are three ways three good ways of splitting the nums array which is as a following and for example 3 since the nums array is in a descending order so there's no good way to split this array to satisfy this requirement and the data constraint for this question the length of the noun's array can go up to 10 up to the power of 5. the intuition to solve this question first since we need to calculate the sub rate sum of left median and right so we can think of the prefix sum array to calculate this and this technique we also use this to solve one of the context question before and next add every index i in the prefix summary which i denote as pre-sum prefix summary which i denote as pre-sum prefix summary which i denote as pre-sum here we want to find all index j such that pre-sum i will be smaller or equal to pre-sum i will be smaller or equal to pre-sum i will be smaller or equal to presump j minus p sum i and this should be less or equal to b sum negative one minus p sub j and this term represents the sum of the left median and right sub-ray of the input median and right sub-ray of the input median and right sub-ray of the input numps and next if we try to rearrange this key condition we will see that presump j will have the left boundary of two times uh pre-sum i and pre-sum j uh pre-sum i and pre-sum j uh pre-sum i and pre-sum j will have a right boundary of uh this term here so now the goal will become finding the left and right boundary of presump j and to determine how many j's will satisfy these key conditions and there's another key constraint in this question that all nums in the numbers array is positive so the prefix sum array will be sorted in nature because they are just accumulated sum and since pre-sum is sorted so we are and since pre-sum is sorted so we are and since pre-sum is sorted so we are able to use a binary search to find the left and right boundary of j now let's look at the code okay and first is to create the prefix sum array and we will append a dummy 0 at the front and next is to iterate through the prefix sum array we can use pythons bisect left and bisect right api to binary search the left and right boundary of j and finally update rest and notice here that because of how a binary search work we have to take the minimum of the size of numbers array or r and a maximum of i plus 1 and l and take the difference and add it into rest we will see why this is needed in the next section now let's see the code in action okay and here we'll be looking at example two and here is a prefix summary and we will start at index one and first step is to find the left and right boundary so at index 1 2 times 3 sum 1 is 2 and p sum 1 plus 3 sum negative one divided by two is six so the left and right boundary is two and four so that means that any j in between two to four will satisfy the key requirements so the number of good ways we can split the nums array is 4 minus 2 which is 2. now move to index two and again binary search the left and right boundary so two times pre-sum two is six so two times pre-sum two is six so two times pre-sum two is six and p sum two plus three sum negative one divided by two is seven so now left and right boundary is index four and five so we will add the difference into rest and now rest will become three index 3 following the same process and for index 3 of left and right boundary will be both at index 5 so res won't be updated and will be still b3 and this will be the same when we move to index 4 and 5. but when we move to index 6 with this calculation the left and right boundary will be both seven because uh this is how the api will return and they actually fall out of the pre-sum array boundary pre-sum array boundary pre-sum array boundary so that is why we have to cap maximum of r at the length of norms array and then floor the left boundary at i plus one and because again the left and right boundary overlapped so rest won't be updated so we will return a rest equal to 3 at the end and this will conclude the algorithm finally let's review so for this question it's not that straightforward and it did require a multi-stage approach so first is to a multi-stage approach so first is to a multi-stage approach so first is to use the prefix sum technique to calculate the sum of the left median and right sum array and the key condition to satisfy is this and then we have to find how many j's will satisfy this condition at every index i and because all the item in the nums array is positive so the prefix sum array will be sorted in nature so that means that we can use a binary search to find the left and right boundary of j and the time complexity of this approach is unlock n because when we iterate through the prefix summary we have to perform a binary search every time and then space capacity will be linear for the prefix summary and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one you
|
Ways to Split Array Into Three Subarrays
|
unique-orders-and-customers-per-month
|
A split of an integer array is **good** if:
* The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right.
* The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`.
Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[1,1,1\]
**Output:** 1
**Explanation:** The only good way to split nums is \[1\] \[1\] \[1\].
**Example 2:**
**Input:** nums = \[1,2,2,2,5,0\]
**Output:** 3
**Explanation:** There are three good ways of splitting nums:
\[1\] \[2\] \[2,2,5,0\]
\[1\] \[2,2\] \[2,5,0\]
\[1,2\] \[2,2\] \[5,0\]
**Example 3:**
**Input:** nums = \[3,2,1\]
**Output:** 0
**Explanation:** There is no good way to split nums.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 104`
| null |
Database
|
Easy
| null |
191 |
alrighty what's up guys we're back with that last video on our foundations of data structures before we go into more complex algorithms this time we're doing legal number 191 number of one bit so before we go into a question let's look at some binary to understand what it's are exactly so here we have a 4-bit are exactly so here we have a 4-bit are exactly so here we have a 4-bit value and three of them are values and one is the sign bits so the sine basil is first in integers uh integers by default are assigned but there's also unsigned integers which can represent more positive values because you don't have to worry about negative values um let's go integer so right now we're just doing four bits so it's more understandable you can quickly learn about binary so these bits represent two to five zeros it's about one two five three uh where this is either one or being turned on and zero being turned off that's a good way to think about it so zero has everything turned off because zero is represented by zero two to the power of zero is equal to one so one is two to the power of one two five zero two is two to five one three is two to the power of one plus two to the power of zero and so on and so forth and you see how you can represent any number you want here now we have seven that's two to the power of 2 which is four plus two to the power of one which is two plus two to five zero so four two one that's seven now for negative numbers the first number is the sine day which tells you this is a negative number and the rest of the three are the addition bits so two to the power of three is negative eight and there's zero addition so that's negative eight two to the power of the three is uh eight and it's negative so negative eight plus one is negative seven uh say over here negative eight plus two to the power of one plus two times zero so negative eight plus two plus one negative eight plus three is negative five anything over here negative eight plus four plus two plus one that's negative one so that's negative eight plus seven and you see the range of this value going from negative seven to or negative eight my mistake negative eight to seven and the same process can be followed to find the range of integers which is negative two to five thirty two because there's 32 bits all the way up to two to five thirty two minus one that's the range of integers now that we have some understanding on how bits work let's all go over the operations so let's I just have a list of simple operations over here you go over e to them so and is one or let's start with or is one or the other half be true for it to return true so one of the or the other have to be one first to be return one so if you do or over here we have zero and one uh that gives us a first value of one zero and zero so the rest of these are zeros all you do over here and we get something similar so we get zero one because or we get one zero one my mistake one zero one so that or one or the other have to be true and is similar in fashion to its name uh one and the other have to be true so over here we would just have zero one zero because this third value is the only case where both are uh equal to one or a true variation so this works alongside the other operations give us nor nand and xor so this just in case whatever these would originally return so if 4 would return a 1 indicated to zero if we return a zero negative one same with nand and same with nx1 and now let's look at righteous and Luscious which are very important very simple to understand too so say we have our four bit number one we right shift over by one that means we want to remove uh this first bit and shift the rest over by one so we get zero one so this value got pushed out because it's pushed right we have a zero at the start and the left shift works very similarly where we want to move it all by one to eleven and we'll have one zero so this first pick I'll pushed out and replaced by zero at the start now that we have these all basics down we can go over the solution which is quite simple we want to use a right shift and an and I'll show you that exactly now with this example so say you have one zero we want to look at hey is this last bit equal to one so how do we check the last bit is equal to one say we end it with one because we know what the bit uh big representation of one only the last bit will be turned on if we use and both have to be turned on to be true but with this we'll get zero and we get hey this last bit is not equal to one now let's do a right shift over by one and we'll get zero one and what is this is the original number with the last bit removed because we've already dealt with that and the zero added to the start so this is not going to affect our process as we go zero one let's add again and we get zero one this bit is equal to one so we increase our count we continue this process because zero one zero ended with one this one's equal to zero this one is not a one and last the one we write shift over we get zero one and it and of course this is equal to one this last bit is one over here and we get our answer as two so obviously this would be a 32 bits because of an integer but when you can stop this Loop once we get that the value is equal to zero because all of these values if you keep on right shifting and adding new zero bits in and removing the old bits you'll get that eventually you'll reach zero and we don't have to check any more bits of each as we've checked all of it this solution has a o of n time complexity uh because where n is the number of bits in the data structure so for instance all of 32 time complexity but um you can explain this further if you want a really impressive interviewer and it's a simple solution and the whole solution is just using and add a write shift so it will be the same for uh positive numbers and negative numbers because we're just counting the number of one bits which is the hammingway and we don't really care if it's negative or positive because we're looking at the binary representation so with that being said thank you guys so much for watching I'll see you guys in the next video
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.