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 |
---|---|---|---|---|---|---|---|---|
328 | hi guys hope you are doing great uh today's question is odd-even link list today's question is odd-even link list today's question is odd-even link list given a singly linked list group all odd nodes together followed by the even notes please note here we are talking about the node number not the values in the nodes you should try to do it in place the program should run in O of one space complexity and row of nodes time complexity for example the input is one two three four five null so we have to first group together the elements at the odd positions in the linked list which is one three and five because they are at the first third and the fifth position and then it should be followed by a group of the elements at the even positions which is two and four because they are at the position two and four okay similarly in this example as you can see two three six and seven they are at the odd position so they come first and then one five and four they are at even positions and they come after note the relative order inside both the even and all groups should remain as it was in the input the first node is considered odd the second node even and so on okay so this is a problem on linked list and before going any further we'll just think about whatever other ways that we can solve this question so yeah these are the approaches that we have understood till now so please pause the video take a moment and then come back alright so here clearly we can use the two pointers approach because we have to rearrange the links right inside the linked list and to be able to do that we will need two pointers one that will point to the odd list and the other one that will into the even list okay so as we sauce the question it will get clearer so since we don't want to use two different lists to store just the odd elements and just the even elements and then merge them together we just want them to do we just rearranged in a manner that they give us the output straight away right so what we will do is that we will as you can see here for example this list right so we take three pointers in the beginning one pointing to the odd head which is one in this case and the other two pointing to two which are the even heads right now there's another question that we had solved on linked list where we had to do a similar operation and we had to take two pointers pointing to the start because what happens is that your even head here it will travel right to the end of the list that will be formed by the even nodes and then if you want to come back to this type the head you will have no way if you don't keep another pointer right so for example here initially odd had points to one and once we extract the odd elements sorry this should be three yeah so once we extract the odd elements odd head would reach five okay or no rather and when we talk about even it will initially be at two and when we extract the even elements it will reach four right so obviously after this we want to join them right and in that case we would want five to be pointing to the start of the list that contains the even elements even position elements right so to able to be able to do that we are capturing that in even which does not move right so that at the end we can say odd head dot next equals even so that five then points to two and we have our final answer okay so let's see that in our code and I hope that should help okay so let's get started with this so okay right so base case should be if head equals none right that is there are no elements then just return okay after that as we discussed we need to have list node odd head that will be equal to the head because first element is the head of the odd list back and we'll have even head and even right both of them so we can just say even head equals two head dot next that is the next element and just even equal to even had the same element right so now we have initialized our pointers now we want to ITER it till right so we want to follow even right so till the point that even head becomes null or its next becomes null right so because what we'll be doing is that we will be first initializing odd head moving or head then based on odd head will be moving even head so at any point when even head becomes null or its next becomes null is the point where we want to stop right so our condition will be well this is not equal to null okay or this even head dot next is not equal to null I think it should be an end because in both cases we don't want to proceed so yeah let's see yeah let me see when it runs okay so now what we want to do is that we want to break this link from 1 to 2 and make this one once next point to three okay which is the next of the even head right so what we do is that open sorry odd head dot next right equals to even head dot next right because two's next is 3 and we want to make sure that the next of one becomes three okay and then we also want to move odd head right so we just say that odd head equals to odd head dot next so basically we have moved or head from one to three right okay now for the even so we do a similar operation so we say even hand dot next equals two odd head dot next which is odd head is three currently so dot next is four so two should point to four correct so we say that odd head dot next and then similarly just even head equals two even head dot next because you want to move it to for now okay and after all if this is done with user even so odd head dot next equals to e right and then we return head from this because we have changed everything head is still pointing to one and that's what the rearranged linked list looks like and that's what is our answer okay let's try and run this okay that's taking a lot of time I'm extremely sorry about that price I don't know what's wrong with my internet these days in the meanwhile the time complexity for this would be O of n because we have reversed each node of the linked list only once right and the space complexity would be off one because we are not using any extra variable or any other linked list to store the elements so we just rearranging the links that's why it would be O of one okay it's connected let's just today it's a minute great okay so hope you liked this video and find this helpful if you do please like share and subscribe keep pouring in thank you guys | Odd Even Linked List | odd-even-linked-list | Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second** node is **even**, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,3,5,2,4\]
**Example 2:**
**Input:** head = \[2,1,3,5,6,4,7\]
**Output:** \[2,3,6,7,1,5,4\]
**Constraints:**
* The number of nodes in the linked list is in the range `[0, 104]`.
* `-106 <= Node.val <= 106` | null | Linked List | Medium | 725 |
200 | Hello Hi Everyone Welcome To My Channel Today In This Video Bihar Solving A Very Famous Problem Number Oil This Problem According To Google Microsoft Amazon Interview Selection Problem Statement And Give An Example For Giving A Gross And Degraded Map Of 108 Number Of Land And Water For Connecting Edison Electronic Cigarette Water No Veer Is Loop Connected To Wheeler Seervi Hai Ko Hang De Villiers Pensi Delhi Zone Lever Not Island In This Example Service Centers Only E Can See This Is Jeevan Ireland Then Security Note Connected To The Subscribe The Channel and subscribe Will solve this problem with due subscribe and defensive will start from this like subscribe and em from greed will start hero index like high for high 20 will start to go number of total votes 226 a request 202 n will check the effigy grade of Mid of greed will find difficult directional connected rate parts of violence and mischief will run from this directional first The Video then subscribe to the Video then subscribe to and you boil Greater Noida Record Number of provision for age SID number Roll number and we need to Solve visiting for not giving subscribe Video to 100 will return from all directions from The state and implemented a Gautam will solve and subscribe my channel subscribe know when you CEO that data structure and will give off inter basically to coordinator for chronic coordinator bill-2010 from chronic coordinator bill-2010 from chronic coordinator bill-2010 from this 2009 into effect from loot-loot 990 will again this 2009 into effect from loot-loot 990 will again this 2009 into effect from loot-loot 990 will again Here subscribe my channel thank you hua tha a for direct nal singh life all four directions of different continents and 0f 50 coordinator is like this condition is like that of warriors and withdrawal it is not loose will continue with other wise coordinator to our video Subscribe Egg Subscribe Button Thursday Subscribe My Channel Subscribe Definition Language Queensland 09 Ki Angry A Foreign Tire i20 Electronic Cigarette Don't Like This Ki I Plus App Kar Do Jo Points Equal To Zero Balance Jain Grade 90 Number Of Roses This Plus Meanwhile Sexual gautam jain easy land witch character one in that case will update ail nn ki and quality bf in it third wife cigarette da hike for j&k cigarette da hike for j&k cigarette da hike for j&k to 100MB ranvijay se thandi number of ireland let's implement deficit private point subscription will give oo will help To reduce intake why not for processing in different directions and creative director on Thursday that's why like is our direction more na will create a few of inter-related inter-related inter-related tuning have thank you don't 8b current coordinator new in top player of access oil and mark director current coordinator value grade of access oil meanwhile sex 2004 no veer 1000 is MP3 the bank will First festival current coordinate which will be vtube.ball noida depot coordinate which will be vtube.ball noida depot coordinate which will be vtube.ball noida depot direction in building direction are software will get the date of birth current of sure android see the volume decrease subscribe direction will be 90 and C0 C R0 C R D0 and half of the Vid U Aadhaar Main Aarti This Character 0 Will Just Keep Continuing Handover Hai Otherwise Revolver Smart Kid Grad Of RC His 2051 Scheduled For True And The New And Commerce Pay Coordinator Interview Anil Ki Tange Subscribe To 202 President Naveen Thukral Center Jewelry Hair On Karo Loot 10 Hindi Typer is because and why Loot 10 Hindi Typer is because and why Loot 10 Hindi Typer is because and why coordinator too much coordinator hindi current twitter share to facebook submit and hips tracking sometime mobile handset accepted norms for the time complexity of this difficulty ringtone for all elements of obscurism subscribe channel | Number of Islands | number-of-islands | Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_.
An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
**Example 1:**
**Input:** grid = \[
\[ "1 ", "1 ", "1 ", "1 ", "0 "\],
\[ "1 ", "1 ", "0 ", "1 ", "0 "\],
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "0 ", "0 ", "0 ", "0 ", "0 "\]
\]
**Output:** 1
**Example 2:**
**Input:** grid = \[
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "0 ", "0 ", "1 ", "0 ", "0 "\],
\[ "0 ", "0 ", "0 ", "1 ", "1 "\]
\]
**Output:** 3
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 300`
* `grid[i][j]` is `'0'` or `'1'`. | null | Array,Depth-First Search,Breadth-First Search,Union Find,Matrix | Medium | 130,286,305,323,694,695,2035,2103 |
1,909 | in this question we are given an array return true if it can be made strictly increasing after removing exactly one element or false otherwise my initial self to approach this question is to go through this array using a loop and also set a counter up front if they see a current element is smaller than the previous element we will increment the counter and after going through the loop we will check if the counter is larger than that these are my initial steps let's take a look at the solution to remove exactly one element there are two scenarios the first scenario for example if the array is one two six three four here three is the current element and the six sixth element needs to be removed so we will just remove previous element which is six the first scenario is easy the second scenario is a little difficult it's also very tricky for example if the array is 6 7 2 8 9 and 2 is the current element here 2 is smaller than 7 but 2 is also smaller than 6 so 2 is the element that needs to be removed to make this array strictly increasing we are going to remove current element which is two um so when we see the current element is smaller than the previous element we also need to compare if current element is also smaller than the i minus 2 element if that's the case then we will return current element instead okay let's take a look at the code initially we set the counter equals to zero and then we set a loop to go through the array the loop starts from one is because we want to compare uh we want to compare nums i with nums i minus 1 and we want to make sure mn span is larger than 0. so the index starts from 1. also since the ray will be strictly increasing we will use less than an equals two because even numbs i equals to times i minus 1 is still this qualifies and after that we'll check the counter if counter equals to 1 which means we have exhausted the only one opportunity to remove one element in previous iteration so we return false otherwise we increment the count then we compare numbers i uh with nums i minus 2 which is the second scenario we are comparing 2 and 6 in that in this case and if nums i is less than or equal to nums i minus 2 we will remove current element how to remove current element here we are assigning the previous element to the current element in the example is the equivalent of assigning seven to two and uh it's the same idea as uh bridging the gap between seven and eight and nine so we can compare the previous element which is 7 with the rest of the array which is 8 9 in this way is the equivalent of removing current element 2. so after the loop uh we can just return true that's pretty much it thank you for watching my video if you like the content please subscribe to my channel | Remove One Element to Make the Array Strictly Increasing | buildings-with-an-ocean-view | Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`.
The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= i < nums.length).`
**Example 1:**
**Input:** nums = \[1,2,10,5,7\]
**Output:** true
**Explanation:** By removing 10 at index 2 from nums, it becomes \[1,2,5,7\].
\[1,2,5,7\] is strictly increasing, so return true.
**Example 2:**
**Input:** nums = \[2,3,1,2\]
**Output:** false
**Explanation:**
\[3,1,2\] is the result of removing the element at index 0.
\[2,1,2\] is the result of removing the element at index 1.
\[2,3,2\] is the result of removing the element at index 2.
\[2,3,1\] is the result of removing the element at index 3.
No resulting array is strictly increasing, so return false.
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** false
**Explanation:** The result of removing any element is \[1,1\].
\[1,1\] is not strictly increasing, so return false.
**Constraints:**
* `2 <= nums.length <= 1000`
* `1 <= nums[i] <= 1000` | You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not. | Array,Stack,Monotonic Stack | Medium | 1305 |
1,844 | lead code 1844 replace all digits with characters so the question in brief is that you'll be given a string something like a b d e f XY z x u c Pi a b something like this and there could be some digits in between right something like um this and this right there could be digit so what you need to do is you need to return back the string which replaces the digits with a character with a letter and what would that letter be that letter will be the previous letter and adding two to that and finding the moving that letter by that many spaces places in the alphabet so this would essentially be a b and since we get two here so it would be after b c and d so D would come here then they will be T again e f x u at this point I find one right so I'll add one to you V would come here then z y a then there's five years so I'll move five places in the alphabet from a so that would be b c d e f so I'll put F here then B so this will be my resulting string which I need to return how am I going to do that simple I'll just go by character for so for I in range length of s okay I'll check if current character if that is numeric right before this what I need to do is I need to convert s from a string to an array so I'll pass s to a list function and that will give me a list of s so every character would be one uh element in that list and then because I need to update the string I cannot update a string so I'll convert it into a array update the AR and then join it back to a string so at the end it would look something like this so I'll join it back with passing the string right so this is what I'll be returning at the end and going back to the logic if the current index is numeric which means that I'll set the value at current index to B I'll take the value at the previous index IUS one convert that into an as value then add the current value that I have at current index so I'll take the value at current index it will be in string format I'll convert that into an integer this integer I'll add to the ask value of the previous letter okay and then convert this sum to back to character so CHR and this function in Python helps me do that convert ask to character and that I'll store at my current index that's it this will run for the entire uh entire list and finally I'll join it back to a string and return let's run and see and that worked for both the test cases let's submit it and that worked | Replace All Digits with Characters | maximum-number-of-balls-in-a-box | You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.
There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.
* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.
For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.
Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.
**Example 1:**
**Input:** s = "a1c1e1 "
**Output:** "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'
**Example 2:**
**Input:** s = "a1b2c3d4e "
**Output:** "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists only of lowercase English letters and digits.
* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`. | Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number | Hash Table,Math,Counting | Easy | null |
1,557 | hey so welcome back and this is another daily code problem so today it's called minimum number of vertices to reach all nodes and it's yet again a medium level question but it's a graph problem here and so I actually read this wrong initially so I'm going to try to make sure I explained it to you right so make sure to you know read the description and read the example you know sometimes it's very easy to race right into the implementation but I encourage you don't do what I did today and uh yeah just take your time it's a simple um not simple well it's a simple algorithm but um it's a simple question to understand what they're trying to ask you so I just I didn't read it I thought I initially just exactly look at the question do what they wanted but I ended up just wasting like 10 minutes on a on the right and the wrong algorithm it was a different problem I was thinking of but anyways so basically all that you want to do is find the minimum number of vertices or I like to call them nodes that will reach all the other nodes in the graph and so in this case um what that really means is okay this node zero it can reach not just one and two it can reach those but you also want to consider that it can also reach five through this relationship through the second node so it's not just what it's directly attached to but effectively what it's able to touch through these um relationships here so it's not just like it's direct children but also their children's Trilogy and so forth and so in this case I'm just using node 0 node three you can reach all the other nodes and that's because well you can reach 0 and 1 here 3 can reach four fourth can also reach two and then they can actually also reach five and that's all the nodes I think this is a really good example of showing you um what they're trying to hint you towards how to implement the algorithm and we'll see that here so if we start off with two it can reach four and it can reach one here and then three here although you already reached one you have to use three because well nothing else can reach three except for itself and so use node 3 here and same thing with zero here you have to use zero because nothing else can reach zero and so although other nodes have reached one already and that's the only use for zero you still have to use zero in order to make use of it and so what the pattern you might start seeing here is basically any of these nodes that I think of them as roots when they have no Edge pointing into them um you need to include in your output and so that's exactly what the algorithm is actually any node without an incoming Edge you have to include and I think it wasn't until I really kind of looked at this example here that it clicked where okay there's a pattern here where whenever um we don't have an incoming Edge we need to include it and then as you begin thinking you realize okay that's all I need actually I don't need anything else except for nodes without an incoming Edge so yeah fairly intuitive question but you know looking at a question like or an example like this is really helpful so yeah let's go ahead and implement it so what we're given is kind of an adjacency list here through a two-dimensional list here through a two-dimensional list here through a two-dimensional array so we're going to make use of that to find out okay which of these has an incoming Edge pointing into it and so we just say okay let's go through every source and destination so this is the source node and this is the destination node this is the one that has like the incoming edge here in our edges array and we're going to create an array called like has like incoming Edge maybe or um has an edge we'll call it and initially this is going to be all set to false and N is given to us and that's the number of nodes in our graph it's false because well at the beginning we're seeing that none of them have an incoming Edge but all these destinations and these edges has an incoming Edge and so you can easily just say okay let's update this at this particular node for this destination to true as we iterate through here and that's how we get which ones have and do not have an incoming Edge and then after that it's just as simple as okay let's go through all these nodes has an edge in our um array here but we want to enumerate it and that's because we want to make sure we know which particular node that we're talking about so this is just keep track of okay does node 0 have an incoming Edge does node one have an incoming Edge and so forth because this is just the true or false Park Housing coming Edge the value that's stored there so we need the index too so we enumerate it and then we just say okay if um it does not have an incoming Edge so we just not the operation then we want to include in our output so I would call it response so let's add to our response array this particular node I and so let's create our array here and then all that we want to do is just return at the end looks good let's try submitting and success so that's uh today's daily Eco problem so for time and space complexity well it's O of n time complexity and that's because well we just iterate through all these nodes in our edges and same thing here this edges array has the same number of notes so it's an O of n time complexity and then for space complexity it's same thing it's O of n um where um we're using this has in edges array to Mark whether or not each particular node has an incoming Edge so yeah hope it helped with the rest your algorithms thanks for watching | Minimum Number of Vertices to Reach All Nodes | check-if-a-string-contains-all-binary-codes-of-size-k | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct. | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. | Hash Table,String,Bit Manipulation,Rolling Hash,Hash Function | Medium | null |
1,697 | Hello everyone welcome, PAN card problem is a hard level problem, okay so let's quickly understand what is my problem statement, what details are given and what we have to do, okay so more is given in the problem statement. Ok and what is given is my number of nodes, how many notes I have in the question, ok, apart from that, what else do I have, a further list is given, ok, what is the next list or the number of 2d vector, ok Further in the list, the value given is that my U is I am I and distance is I. Okay, so there are two notes, I am U and I, there is some text present between the two, the distance of which is my decision. Okay, so what is this one, 2d, what is this one of mine, what is 2d vector, okay, apart from this, what have I got, some queries have been given, Maa Lo Ques, I have got the queries, Maa Lo, what is this also 2- Dector is maa Lo, what is this also 2- Dector is maa Lo, what is this also 2- Dector is maa lo jeth query so what is the ka in jet query that I have, what is there in that too, two notes are given maa lo ki is J and yours is K and there is a limit J. Okay so you have to tell me what. There exists such a thing between P and J, the true date is the distance of all the edges that are happening in it is like a limit, it should be less, right, what does it mean, take a small example, zero, one and you, and we had given it like this. People have repaired their graph so that the text zero is one, I am 01, which is my no, and the distance in between is four, it is okay and the distance between it is one, so mother, someone has gone to me, okay mother. What zero do I have, okay, and mine is zero, and you and mother, what is he asking me, what do you mean by zero and you, is there any text in between the notes in which all the edges are, what is their value, they are strictly If you are smaller than this limit, let's check. From zero, you are fine. One exits the text whose value is smaller than mine. One thing exists. But what if we come from this point, does it mean that we are true? Why can't we find it because it is going from zero to one, four is going from 2 to 12, so we return it on time, but here because I have one thing on the list, one thing adjusts like this. If the weight of the true date or the distance between the destination and my source is less than this particular limit, then how can I return it? If you return, then many such queries have been given. For queries, we have to check whether the distance between the particular nodes and all the agencies is less in this lens. Okay, one more thing, pay attention to what is given in the statement that between one or two notes. There is a power to have multiple ages too, Maa Lo that this is 10 is okay and this Maa Lo that is five is okay, now let's check this again whether such a part exists in me from zero to you, the truth is that its S is from you. It is okay, mother, that if we had taken the five distance lesson, we would not have been able to reach it, or if we had taken the 10 distance lesson, we would not have been able to reach even if we had gone beyond 10. Apart from this, what if I had been given one again? That means from zero to you, the one with five distance, the one with 10 distance and the one with one distance is fine, then we could have reached the path with one distance. Okay, I hope this thing is clear, so this is what is given to us, so what should we do? Hey, we have to return one or we have to return a vector, okay, what will be its size, it will be equal to the size of the square, in every case, we have to return its true or jal, okay let's go DFS BFS or any. In the order from time algorithm, this condition is being satisfied or not, but here the value of N is in terms of 10^5, the here the value of N is in terms of 10^5, the here the value of N is in terms of 10^5, the queries in this way are not the same, why are the queries so low, okay? The number of queries which is mine is fine, that too in terms of 10^5, so if we that too in terms of 10^5, so if we that too in terms of 10^5, so if we go once to drive the entire graph, then it takes order of more time. Okay, so it is jQuery, mother, so total, we have all the answers. In giving n * k g will go na all the answers. In giving n * k g will go na all the answers. In giving n * k g will go na 10 tu di power 5 * 10 tu di power five 10 tu di power 5 * 10 tu di power five 10 tu di power 5 * 10 tu di power five I will be written total, my game ends right there, so we will not have to remember anything like this, okay so that we can answer my question. Can give right, one thing has to be kept in mind, so here it means we cannot put DFS BFS, right graft driver cell, note this in this way, okay, this note in option, sorry, okay, this thing must have been clear to you, okay now. Before solving the problem statement, let's break it down into what we have to tell about the problem. First of all, we will break down the problem statement. If the problem is correct, what do we have to tell? First of all, we have to tell that it is possible that Lo, zero is mine, you are there and three is there, maybe brother's, we had to tell between 02, but these people are not connected, it is okay that they are in their own group, you are separate, okay, so first we have to see that. Notes Maa Lo's query ones which are my notes, Query Notes R and Connect are fine, connect is what is meant by saying one, do they exist in a graph or not? Maa Lo, this may have been a different graph, that's why this Have to check, ok secondarily, then tell me, give us dental, check the distance, will fix my condition, Maximum Problems are connected or not, but let's see through the joint sets, okay in the big of the joints, sorry in the big of sets, if you don't It is known that we have done a lot of work in the previous video, so you can watch the last video also from here, whatever is your link, we will give it in the comment area, it is okay with your advice, we will do it here also. Let's look at the sets once again, okay, what are their properties, then we will come to the problem and solve it immediately, okay, joint property, so joint sets is a way of representing a graph, okay. Which tells us whether the two notes are ultimately connected or not, or is it part of a particular set or not? What is its name? Brother, its name itself is your country. Joint set may mean. Your graph is also disconnected, isn't it? Mother, these two are test joints, but this will be its own set, okay, this is its own setup, even though it is alone, but the set is okay, let's not leave it alone, this is the only exit, it is its own. Some are different sets but although they are disjoint, well then the brother of the design set is less so that we can tell that one and you are part of one set of one design set, 4 and 2 both are different sets. Okay, so this is the lesser part of the design set, it is better to explain it, so what do people do in the Jaswant set, how do people do these imitations, to implement it, do it in a factory, do it, you are okay, whose size is It happens that it is my number of notes, what is my number of notes, mother, how come I have five notes, sorry, okay, then make it of that size, one, three, four, five, okay, let's initialize it, this is mother's, now mother. Take it that there are no connections in these, it is okay, everyone must be alone, connections will happen later when we will get further limit, okay when the list will be given, for now let's assume that everyone is alone, no one is connected to anyone, so everything will happen automatically. Okay, 1 2 3 4 Okay, now as we will be given the connection, we will connect to it and we will give its name generally, then this representative What does it mean to know who is whose parent? Okay, and every group has a representative, one has a parent who will be everyone's guardian. Okay, mother, this was the zero of this group, this is the three of this group or set, this is the representative or this. There is a five in the group because he is alone brother, so it will remain a five, okay let's make one by one and see how the connection is done, okay now mother, I had to make a connection between three and four. Okay, so we will see which is the end of three, there is a balance in it. Okay, now what do we do in this, we have to add these two, so in this we do the term in the set, we do the union operation. Okay, union, so the union function is reduced by two notes. Okay, so we will do the union operation tomorrow, we will make the function our own, okay and connect these two in it. Okay, what will we do before connecting, we will find out the parent of both are their own parent and If we make the parent of one the parent of the other, then whoever is the parent of the four, right now there is only four, so do we make him or what do we make of him or do we make him the child of 3? Let's make three of us, okay then who is the parent of three and four, brother, three, this is the representative of these two, okay, now a note must have come, mother, that if you want to make a connection between my 0 and 1, then exactly 0 and 1. The balance of zero is zero, okay, if one is one, then what do we do to establish a connection with the parent of one, that is, if we make it zero, then the parent of one becomes zero, okay, very good, now zero and 2 are mine, okay? If there is a connection between these two, Zero and Tu, then what do we do, we make Tu's parent Zero, okay, so when we are searching the parent, we implement another function for that, my find which is Mine tells me who is the layer of the parent note, mother, it can be multi-level also, okay, make mine, okay, so let's take its size a little bigger, 67 and 8, okay, till now, this six is okay to consume itself. Hey Maa, now we have to find out that you and Maa Lo of Six, I have to make a connection between 68. Let's keep it simple. The example will be good. The connection has to be made between 6 and 8. Maa Lo, what is the initial? Education, parents, what is the meaning of coming ? Okay, ? Okay, ? Okay, so now we have to make a connection, so take the parent of 8, whatever was the smallest value, we will make it six. Okay, the layer of Aate has become six. We have to do similar union operation. Okay, so brother, who is your parent? Mine is zero. Okay, who is the parent of six? Mine is 6. If we have to make a connection between these two, then what do we do with the parent of six? We give 2 to the parent of six, so 6 is finished. You, there is a connection between these two, I am fine, this thing is mine, what else do you do, seven children, this is the end of seven, my six is fine, the cross of 7 has become my six is fine, the cross of 7 has become my six is fine, the cross of 7 has become my six, this thing is clear for me, so Through this find operation, we find out who is whose parent and in the union operation, we make the parent of one person the parent of the other. Okay, I hope this is clear to you. There is also an option in this that whenever Whenever we go to find, then mother, we had to find out who is the parent of Six, okay, so you are showing Six to us, then you will return, okay then we will you sometime. We will see who is the ultimate representative of this group, then my representative is yours, then who will be the print of yours, then who will be the zero, then it will do it tomorrow. Similarly, if you want to know 8, in which group does 8 exist, then mine will be the parent. If 22 is zero then this number of calls will be very high. Okay, so what we do in this is that many times we optimize this, whenever we are removing someone 's parent, we directly If we 's parent, we directly If we 's parent, we directly If we connect it to the representative, then mother lo, we could have written it like this also, mother lo, we are taking it out for weight, okay, so we connect 8 directly, then it is okay from zero, similarly six must have come on the way, so six. How to do this, we will see in the code once we return in the find operation, what will we do by directly changing the parent of at and making it zero. Directly change the current value of six and make it zero so that next time whenever you do mine, it will directly give you the answer in one hydration. Okay, so this is an option, you can implement it if you want, or you can't do it. It won't make much difference but your code will become a little faster. I hope this thing is clear. Ok, let's check once with the find operation. Maa Lo, I have to check for 3. Maa Lo, I have to check for four, okay, what is four and one? If it is in a group then what is the representative of my one? What is the representative of zero four? Three is left, meaning if it is in different groups then it is not disjoint, it is ok, it is just joint, actually it is ok from different sets, I hope this thing is clear. So I set it, I hope it would be clear to you that how you will implement it in the functions, it will become clear to you, today you should pay attention to one thing that today we will do an optimized version of union, the last problem is that we had done union, if you want then we will do it again. They are saying, you can go and watch the video, okay, today we will make an optimized version of it, is it okay without union, generally there are two options, one is normal union, one is my union, one is buyers, one is what is my union, bank size, union today. Bye run will be called it means that if Maa Lo is my 012, three is four, then its rank Maa Lo must be my connection twice, then you are ok on two levels, in this way I must have had one more. Take any mother that my 56 is fine, his rank must have been one because once the connections have been made here, whoever has a higher rank than me, higher rank, whoever has a higher rank than me, what to do is add the person with a lower rank in it, that means if we If we had made it its parent, then it was adjacent to it, so what would have happened to me if its height gets flooded, that's why what we do is connect the smaller one to the bigger one so that mine remains at 5 and mine remains at six, okay? Union Bank can do it if you want, you can't do it but it is beneficial, it is quite ok, so what do we do that whoever has a higher rank, we make the parent of the higher rank the parent of the lower rank, okay? This thing must have been clear, then I have understood the joint sets. Okay, now come to the problem statement. Okay, so in the problem statement, first let us check whatever my query notes are, whether these two are connected to each other. Not yet, there is a good connection, so now we have to find out whether the distance they have is within this limit or not, how will we know this, what do we do to know whether the given queries are ok or not? Let's sort the list, okay, what do you do in the smallest, you do in the largest, on what basis do you sort it in the largest, brother, then go on the basis of this distance, my lesson with smaller distance came first, the one with bigger distance came later, okay. Okay, so what to do in step one, shorten the list further, okay, on the basis of what to do on distance, what to do in the next way, now we have to give the answer to the quiz, okay, so reduce this query by one, so that you can shorten it, okay. On what basis will you sort, then your message of this limit is ok, that is, whatever small limit of mine is ok, I will answer it for the smaller one that if it was my limit, you are ok, then whatever we can, whatever is mine. Next, take all the notes which are smaller than you, what will we do by adding them to the set, okay, we will add all the notes which are close to mine, after that we will apply this condition and see that whatever note is given to me. Is it possible to connect so many notes together or not, in which I have a maximum limit, it is okay, so shorten it, I have to sort it, brother, is the query okay on the basis of whether the limit is okay, but what will be my problem? After sorting, the order will be gone, Maa Lo Meerut, who will be at Jeth position. After sorting, Maa Lo, you will have reached K+Tu point, After sorting, Maa Lo, you will have reached K+Tu point, After sorting, Maa Lo, you will have reached K+Tu point, anyone has reached the index, so what will you add in this. Add your parameters separately. Let's tell what was its actual position which was given in the problem so that when we are returning the answer then attend your GG position, okay then add a parameter, okay after that. Shorten it, okay, now what will we do next, what will we do, will we hydrate each query from zero to zero, whatever limit it will have for each query, from the limit, whatever number of edges we will reduce, for the limit j, we will reduce it. Those who will be less than the limit, we will add them to our disjoint set, then finally we will check whether P and J are connected or not, when my limit is clear then the pro statement is a very long video, but I hope that's all. You must have understood something clearly, ok, now quickly let us move on to the code and implement it, otherwise we can do one less thing, after that we will code so that there is clarity for you too, ok So Ageless is mine, I had to sort it. Okay, take Ageless, let us sort it, see its weight, you are it, its is four, it is 8, it is 16, so the next list is my shortcut, we had to shorten it too, we have to do this. Right on the basis of limit, so this is also my short raid, we have added an extra parameter in it, is this its index, okay, what is this index of mine, okay, so Now what will we do that every query It is okay for every query, if it is definitely a query, then we will add all the small agencies within this limit to our deny set. Okay, so you are okay, zero and one are okay, what is the weight ahead of it? You but you are not smaller than you, otherwise we will not be able to add it. Right, we will not add it. Whoever my answer will be is zero and whose size will be one, this one is zero. What is my position of the query, then it is zero. What will we write after going to the zero index? Why water, because first of all, we are not connecting zero one because its edge weight is not small, so we will not be able to connect these two. Okay, so that's why we. Let's reach here and then come to the next step, here we have five for the square, so going to this list, we will add notes and connect the union until mine is less than 5. Okay, now zero can be connected, because now tu is smaller than 5, so zero will be connected to one, okay, this is similar, then let's come to this, okay, four is also small, so one and tu. If we connect then we will connect one and tu. Okay, then if we do union operation on these two, then its parent must have been zero. Okay, and let's make one the parent of tu and ultimately if one's parent was zero, then this should also be connected to it. So it became only 2, its bread is also fine, now let's go to my eight, okay, we will not be able to connect eight, right, so we stop here, okay now what was my query, my zero and you are connected. No, what is zero and the pattern of you must have been one's pattern has become zero, okay, if all this is clear, then now let us do coding, okay, let's go, the function is given in the name, okay. The answer is to return one, so what is the first step, what do we do, we create some of our variables which will come less like me, why do we create them, okay, then the dot size, sorry, apart from that, we create a max limit which is We will do that to see what are the limits, okay, apart from that, let's create a K, initialize it from zero, okay, now what do we do, to store an answer, we create a boolean vector with the name of our answer. Ok, after speaking the answer, what will be its size, it will remain the same, as many queries as there are, we have to return that much answer, ok, this is done, it's mine, now what do we do about who will be my parent, ok, who will be my parent, for whom let's go ] Come, we will implement our joint set, prepare it, right after that, the parent stores it, what will be its size, the number of numbers of mine now, what are the notes of my notes, okay, it will be as much as 10, if you are the power five, then take the mother. What we do is that we take zero and one extra. Similarly, to store the rank, we name it rank one and we keep its size the same, we do zero and one power band, one, two, three, five, okay. This is clear, now what do we do, we create a find function which tells us who is the parent of the two notes, after that we will compare them, then to find out the parent, we create a find function by calling our find parent as mother. Take the pass, okay, whatever I was parenting, pass it, what are we doing in this way, what we had discussed was that we were going up the level and checking who was the final pilot. It's okay, if we had to optimize this, we had discussed that why not connect everyone to zero, right, we will connect everyone to zero, then whenever my zero is returned, then whoever's parent was in the way, that's it. Brother, please update your parent to zero. When you were mine, please update the parent of six. Connect it here at the connection cat so that next time we can give the answer in one go. Okay, that is why whatever answer has been returned to us. Here's what we do with it so that next time we don't have to do so much searching for the address above, we can connect directly. Okay, apart from that, this is my one more function, let's do it. Which brother is Union? Ka to union is giving its separate let's pass in it Okay parent ka what happened to me Come on this is mine okay Mine let him know Ki Parents of who was my parent to him Update the rank, whose post will go to me, who is clear and this is my union operation completed, brother, whatever my union was, it is completed, okay, apart from this, we also have to shorten it, how do we sort it as per our own, okay? Create a static function on the condition that if you keep it inside the class then you keep it outside the class as well, then there will be no difference from the static. You will create a function by saying compare cmp, ok and let's create another vector. For this, what is my distance to the second element of A? Is the second element of A right, is it smaller than the second element of B? If so, then return true. Okay, so these are my extra functions ready, then this find function is ready. Union by Rank is done and this is our Comparator function which is the radius to compare. Okay, so now let's come back to my original code. Okay, so what were you doing now brother? So now what were we doing? You update it, but the one with high quality zero parent, which was there in the beginning of every kind, update it in the beginning that everyone is their own parent initially, that is why the parent came in and what do you do with the rank, make it initially one for everyone. If no one is connected to anyone, then rank one, friend, zero, whatever you want to do, okay, this thing is done, I am good, what is my next, reduce one of all the queries that we have done, what have we done in all the queries. Did you add a parameter with an index or did you add a value, which they do, but In the queries of I, okay, let's push back, this thing is done for me, what will we do now brother, we will both do the sorting. Let's sort the queries and we will also sort the queries. Okay, so shorten it. It's okay for me. It's okay to do. The current one, my query, reduce it by one, the max limit that we had created in the beginning, do that. So max limit is equal, what will happen to my queries, which value of i, third value is correct and now where will be my store, which would be its actual index, now what could be at i position or not at the original i8 position? Whatever the story may be, we have stored it here, this operation is stored on the third index in the queries of I of third, so let's keep that also, okay and let's create an idea for the index here. Come on, say, this thing is mine, it is fine, as long as it is exiting, that means the size of the list which was mine, should be mine, now what will it reduce or add all the edges which are less than the maximum limit, okay? You should remember, okay and further list, whatever is mine, whatever is my distance, it is mine, do n't break on j2, it is less than the max limit, okay, it is less than my max limit, okay as long as my distance is maximum. If we have to do with the limit, then what are we getting done by getting the union done, what are we getting done, sorry for both the ages, we will get both the parents added, so union is fine, parents, what will we pass in this, brother, if I am ageless then I am ageless. What do you do to add both of them, ageless zero and next to me in the list, go right on one, whatever is my value for the query, if you pass it, then whatever is right of mine in the queries, it will be there. in the queries, it will be there. in the queries, it will be there. Whatever my U is, means first value and whatever my V is, we will pass both of them and see what is the parent of both, okay then what will be the parent of both, okay one is messed up, okay equal tu will be then find. Call the parents of both of them and make them equal, what should you do? Compare, if it is equal then it will be true. If it is not equal, then it will be false. Right, then band on this and get it returned, what is my answer? Abhi Ki No, if it is from then I must have been cleared, we must have done all the approaches, the salary of the test one set is very basic, okay, if you did not understand the video, then watch it again and again, see you in tomorrow's video, bye. | Checking Existence of Edge Length Limited Paths | strings-differ-by-one-character | An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .
Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
**Example 2:**
**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.
**Constraints:**
* `2 <= n <= 105`
* `1 <= edgeList.length, queries.length <= 105`
* `edgeList[i].length == 3`
* `queries[j].length == 3`
* `0 <= ui, vi, pj, qj <= n - 1`
* `ui != vi`
* `pj != qj`
* `1 <= disi, limitj <= 109`
* There may be **multiple** edges between two nodes. | BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*"). | Hash Table,String,Rolling Hash,Hash Function | Medium | 2256 |
1,816 | hi guys welcome back today let's look at this problem truncate sentence it says a sentence is a list of words that are separated by a single space with no leading or trailing spaces okay that's a very general statement next it says each of the words consist of only uppercase and lowercase english letters no punctuation so that makes her life much more simpler so it has given an example hello world is a sentence hello world are some example of those sentences so we are given a sentence s and integer k we need to truncate s such that it contains only the first k words and then we have to return s after truncating it okay that's the problem statement let's look at some examples so here the example is hello how are you contestant and we have to return the first four words so the output is very we can easily guess that's hello how are you let's look one more example what is the solution to this problem so if we are asked to return first four words of the sentence it would be what is the solution similarly for the third example as well so now before jumping into the solution i would highly recommend you to try out this problem and come up with a brute force solution this will really help you to train your brain for in the future to solve such problems so pause this video and think of a brute force solution now i hope you have given it a shot so let's think of a very brutal solution so for example if we are given so forget of forget about this in a string so if we are given an array and we are asked to extract the first k elements of that array what would our approach be yeah quite simple will i trade through the first k elements of that array and copy that into a separate array and return that resultant array now can you think of this string and can you think of a way to convert this string into an array yes you guessed it right it's the split function that is used to extract each and every word of a sentence into a separate based on a delimiter for in our case it's a space into a separate array so if we extract each word in a separate array and we can then return the first keywords by joining that into a string and then finally return it so the time complexity would be order of n and space complexity would be also an order of n since we are storing each and every word into a separate array now before moving forward i would like to ask you can we optimize this solution from a space complexity point of view yes we can definitely the catch is do we really need all the words to store in an array or just the first k elements or the k words in this case or do we even need to store that into an array give it a thought if you want you can pause the video actually we don't need to store all the words into an array a better approach would be i'll store i'll have a variable which is my word count which is initially 0 and i'll traverse my resultant string or the input string character by character and once i encounter a space that means the word has ended and i'll increment my word count and then i'll check if my word count equal equals to k that is my inputs input value then i'll break out of that while loop which i use to traverse each and every character if it is not equal to k then i'll increment or i'll go to the next character and then finally if it is equal equals to k i'll return the resultant string from 0 to that particular index so this is my optimized solution so let's code it and then we'll talk about its time and space complexity so let's have a word count variable let word count equals to 0 and then we have a resultant string which is which would be used to return my result it's initial empty initially and then we have a variable to traverse my characters while i is less than s dot length so here i'll check if my s i character at ith index equal equals to a space then that means the word has ended and i'll increment my word count now i'll check if my word count equal equals to zero i'm sorry equal equals to k then i'll break so that this is quite understandable now if it is not the case that is if my word count is not equal equals to k then i'll move on to my next character and this would come inside a complete block now let's extract the result into my result variable so result equals to s dot splice 0 to i so splice generally returns does not changes the s string but it returns a new string with characters from 0 to y excluding i so and then we will finally return my result let's run this code s dots slice it should be slice not splice yeah now let's submit this yeah a solution passed all the test cases now if we talk about the space and time complexity the time complexity is order of 1 since in the worst case we would be traversing each and every character of the string and space complexity is order of one because we are not using any extra space to in our solution yeah so that's it guys this is the optimal solution that i could think of uh if you find any optimal solution then this then do share in the comments and do let me know thank you and always keep smiling | Truncate Sentence | lowest-common-ancestor-of-a-binary-tree-iv | A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation).
* For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences.
You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._
**Example 1:**
**Input:** s = "Hello how are you Contestant ", k = 4
**Output:** "Hello how are you "
**Explanation:**
The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\].
The first 4 words are \[ "Hello ", "how ", "are ", "you "\].
Hence, you should return "Hello how are you ".
**Example 2:**
**Input:** s = "What is the solution to this problem ", k = 4
**Output:** "What is the solution "
**Explanation:**
The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\].
The first 4 words are \[ "What ", "is ", "the ", "solution "\].
Hence, you should return "What is the solution ".
**Example 3:**
**Input:** s = "chopper is not a tanuki ", k = 5
**Output:** "chopper is not a tanuki "
**Constraints:**
* `1 <= s.length <= 500`
* `k` is in the range `[1, the number of words in s]`.
* `s` consist of only lowercase and uppercase English letters and spaces.
* The words in `s` are separated by a single space.
* There are no leading or trailing spaces. | Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node. | Tree,Depth-First Search,Binary Tree | Medium | 235,236,1218,1780,1790,1816 |
36 | hi everyone welcome to my YouTube channel and for this video we will talk about given a grid like 9x9 grid we have to determine whether this is a valid Sudoku or not so I just want to emphasize that this is not so for this problem we are not trying to come up with a Sudoku server we just want to know whether a given input is valid stoku or not so this problem is not too difficult so let's look at the problem statement so here is the problem statement and as you can see it looks a little bit confusing like what do you mean by the belly Sudoku board it means that so if you look at this one um this one is actually true because notice that five six eight four seven now those numbers are the same so they are all unique numbers five three seven so on and we don't care about this you know empty blocks so just forget about them and same thing for the second row six one nine five well you don't see any repetition for the second column 396 you don't see any repetition and we also look at this block five three six nine eight so no repetition so this one is fine but this one is actually false because you look at this we see eight here and we also see eight here so this is false so just want to emphasize that for this problem we are not required to find come up with our own stoko server that's for the next problem and I will talk about it in the next video the way I did it is I basically had three like nine by nine grid so Matrix and for each one so the first and then the first one is for the rows second one is for the columns and the third one is for the blocks and it may not make sense but just pair with me so notice that I mentioned this before so we know this step for this row so the fourth row we have eight and eight so we have a repetition and that makes this Sudoku invalid and notice that here for this column we see the same eight here eight and eight so that makes this Sudoku invalid so we somehow have to keep a record if the same number exists and so I chose nine by nine Matrix and three of them actually so for rows columns and blocks means like this inner you know three by three Matrix grid so this one I call that like zero block for a one block like second block third block fourth block I'm using the zero index so that's for this and let's see let's look at the next slide so we need let's say we check the column first it the order doesn't matter whether you check the column first the road second or the you know the inner block the third the order doesn't matter which one you check first so let's see if we check so let's look at the case where we check the column now we notice that five six eight four seven five this guy well so the first entry which we encounter is this five and this is our you know all these numbers are in our first column so zero column and there will be mapped to this guy here we have five well five is so and then we look at our the first row here and we see the five is not there so we set that equal to you know one so for instance if we have say Port of zero comma four that would be this guy four and we check if this is if we have already seen it if not we set it equal to one so that 4 corresponds to this guy and then we set that equal to one if this is say 4 then we check if Board of zero comma four is one or not in this case it is one so we return false and we exit the while we exit the you know the for Loop so that's basic idea for this problem here same for the row we you know we will be looking at this and we noticed that so in this case we look at board oh we look at the Port of zero comma one and which is three and we look at this guy the first we look at the first row and we see if it is one over zero right if it is one that means we already have seen it so we return Force otherwise we set it equal to one and then we keep iterating to the right and so that's what's going on here so this file represents is for this guy this one the second and three is for this guy right and then the last part is tricky this board like this inner uh three by three Matrix so I just said I just call this guy the you know zero Matrix I mean zero square one square two square three four five six seven eight okay now we look at this one so all the entries here will be mapped to the first row so that's there's going to be zero row and three is for this guy five is for this guy six this guy nine this guy eight is this guy so we see the idea and the key the tricky part is how do you come up with this um you know the mapping like buyable mapping from like this guy to this guy say for instance we'll be given a coordinate so in this case for this one six that will be what 0 uh one comma zero right so one comma zero and then how do how should we you know translate into this guy there will be zero comma five right so that's the key for this problem and how do how should we do this so my Approach for this was come up with this and you can try this you can try say this number and see where it lands so this one will be what there will be six comma six right and we notice that six and we have this one so that will be two times three that will be six plus um six divided by three that will be two so we get eight so we will be right here so that works so notice that for this one uh for this problem I mean for this guy we had one comma zero and you plug one into row zero into column we get what we get zero right so we get zero so that's good and then the six this one is you know we are using the zero index for like this guy so you'll be six minus one that's that is going to be five so we will be at zero comma five that's basically the whole idea behind this problem and let's look at the code for this problem so here is my code for this problem and the only thing that you have to pay attention is like this part and I think the other part is pretty much um self-explanatory because we are given a self-explanatory because we are given a self-explanatory because we are given a string make sure you don't forget that we have to turn it into integer and then we have to subtract it from one because you know we have to consider that so all these numbers are you know starting from one and then our index is our array The Matrix is you know zero index so we have to subtract that from one and yeah if it is so we are given this one for empty block if it is this guy then we just you know continue we have this continue here so we move on to the next iteration and let's run this all right so that's for this problem and the next problem will be where we have to actually solve a Sudoku and that one is a little bit complicated than this one I will have a separate video on it and so if my video helps you guys understanding this problem please give me Thumbs Up And subscribe to my YouTube channel and I will see you next time bye | Valid Sudoku | valid-sudoku | Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition.
**Note:**
* A Sudoku board (partially filled) could be valid but is not necessarily solvable.
* Only the filled cells need to be validated according to the mentioned rules.
**Example 1:**
**Input:** board =
\[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** true
**Example 2:**
**Input:** board =
\[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** false
**Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit `1-9` or `'.'`. | null | Array,Hash Table,Matrix | Medium | 37,2254 |
201 | hey everyone today we'll be solving lead problem number 2011 bitwise and of number range in this problem we are given a number range from left to right inclusively and what we have to do is we have to take the end of all of these number in this range let's say if in an example we are given range from left to right as 5 to 7 so we have to take and of all the numbers in this range and we have to return the result so how we are going to do that if we go with the Brute Force approach so we are going to take end of five to six with s when the range from left to right so what will be the answer here what is the binary form of five 4 and 1 this is the binary form of five what about 6 4 + 2 five what about 6 4 + 2 five what about 6 4 + 2 6 what about 7 4 5 6 and seven and now if I take end of all of these values so what is end operator if two values are one only in that case it is one if any one of the value is zero let's say if it one and zero and one it is zero all should be on to make the final output as on so if I take the add operator here manually what will be the answer this is one this is zero so on the rightmost side it is zero this is 0 this is 1 one so ultimately it is zero and here we have 1 so it will be 1 0 so this is our answer which is 4 this we have to return like in the example uh for the value as a input 5 to 7 we have four our answer but here if we follow this approach and if we have a look at the constraints so constraints are from 0 to 2^ 32 or you can say 32 31 minus 1 so 2^ 32 or you can say 32 31 minus 1 so 2^ 32 or you can say 32 31 minus 1 so it's a very high range so if we are going to do this way so we will be going from 0 1 2 3 4 5 6 till 2^ 31 - going from 0 1 2 3 4 5 6 till 2^ 31 - going from 0 1 2 3 4 5 6 till 2^ 31 - 1 so it's a huge time and the time complexity is order of n the N is the range and the N value is too large so over the small cases like range from 5 to 7 it is going to submit the answer but on the larger values we are going to get tle if we are following this approach that is going from left to right so now how do we improve it further now let's have a look on our optimized approach here the left value is five and the right value of range is seven if I do the binary representation it is 4 + 1 5 4 + 2 6 and 7 4 5 6 7 so this is 4 + 1 5 4 + 2 6 and 7 4 5 6 7 so this is 4 + 1 5 4 + 2 6 and 7 4 5 6 7 so this is 5 this is 6 this is 7 and this is our left value this is our right value here we can see that in these values we have a difference of one so on the rightmost side we are going to get at least one zero if we are not able to get any zero it means that this is not a series so on the right side we are going to get at least 1 Z if there is at least 1 Z it means in the resultant we are definitely going to get zero similar for the last left second last column if we are having at least 1 Z we will get zero in our answer so what is the trick here is that uh we have to figure out the common prefix we have to get the common prefix of all of these binary representations so for this common prefix how do we have to some way get rid of these Val values and our left is five in the starting right is seven in the starting so if uh if I do the right shift will I be able to achieve this common prefix yeah right if I'm doing one right shift it means I'm discarding one col First Column if I'm doing the one right shift again I'm discarding one column after right shifting two times for this example we our left and the right value are becoming equal so what if I do the right shift two right shift on all the values it will be 1 these two will be gone so all of these values are 1 one it means that left value and the right value is now equal so what we are going to do is while left is less than R we are keep we will keep on doing the right shift Left Right shift by one right shift by one okay now we are able to achieve the prefix so now but this is the prefix not the answer it means the end of all of these values so what is the end of all of these value all of the right rightmost value where the column is having at least one zero is going to be zero and the first First Column which is making this prefix value will be one if there is no prefix it is going to be zero all of these value are one so for the first prefix we have this is our prefix after making two right shifts so to get our answer or get our and value we will make these left shift again so over the one which is a prefix I will make left shift two times because two times we were making right shift to get the prefix so we will keep track of the shifts Plus+ so once we are doing this is Plus+ so once we are doing this is Plus+ so once we are doing this is our step one is done it means we are able to like uh achieve this prefix value and what is our prefix value this L value and R value all of these value are our prefix so on our on any one of these value let's say I'm taking left if I make the left shift by shift number of time this is going to be my and value and I can return this from this function so this was our optimized approach I hope you got the steps what I'm doing the main trick is that we have to find the common prefix if you are not able to understand this or finding it difficult to understand you can just try it on a couple of examples let's also discuss the time and space complexity here so what is the time complexity in the previous approach in The Brute Force we were iterating from left to right so it was going order of n so here we are not iterating over our uh whole range we are just evaluating left and right and making the left making the right shift in the starting and in the end we are do doing the left shift so in the integer it is already fixed that we have 32 bits so in the worst case it can be order of 32 it means that it is a constant time solution so the time complexity is order of one and what is the space complexity is also order of one so it's a constant time solution always whatever the value of range now let's quickly code this problem | Bitwise AND of Numbers Range | bitwise-and-of-numbers-range | Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1` | null | Bit Manipulation | Medium | null |
428 | hey guys welcome back in the last session we learnt how to serialize and deserialize bst and binary tree today we are going to learn how to serialize and this realize an error tree okay in the binary tree approach we used dfs period traversal and we serialized and also we used the same technique pre-order traversal same technique pre-order traversal same technique pre-order traversal to this realize there in binary tree each node can have max 2 node 2 children but in the nra tree case any node can have n number of children okay i have written the same code what we used last time to serialize and deserialize binary tree let's fix this code to solve the nre problem you can see that the tree node has left and right child because it was a binary tree let's now change it to a energy so in that case i will write list of tree node children right yeah so in that case i will write list of tree node and let's call it children let's initialize the children with an empty area list okay now let's modify the serialized method in the case of an error tree what we can do we don't have left and right instead we have a children of sides n right so in that case what we can do we can just you know write a for loop and in that for loop we will call the serialized method for all the children so let's do that okay yeah so for i equal to 0 i less than children.size and remove the right and instead of left i can write children dot get of i being the index right while this realizing we knew that we had to read two uh string to digitalize right one for the left node and other for the right node but here in the n eritrea we have to find a way to know how many children will i read for this particular node so to be able to know that the easiest way is to save the size of the children right okay so the next line that i will be writing is result plus equal to comma plus root dot children size okay good in the base case we will return a empty string instead of star now okay now let's go and fix the d serialize method okay this realized method we don't need this star case anymore because we are not saving star now that we have saved the size of the children so we need to you know read that size of the children immediately after reading the value of the node right so immediately after the after reading the value i will read another string which will give me the number of children and now once i get the number of children i can start a for loop and in the for loop i can read and add those nodes as child to our children right finally i can get rid of this another two line okay good now we are done with the deceleration method now let's go and change the stub so in this tub in this test method you can say or in the main method what i am doing i am actually serializing the tree first okay printing that string and after that i am deserializing it to get the tree back and from the tree again i am serializing it okay and if i'm just checking in the first serialization method and the last simulation method they both return the same string okay then we can say that we have successfully serialized and decentralize the anarchy now let's run this code and see the result okay we got the result if you see this string the first value is 0 which is the first root node and the second value is two which means it has two children okay and after that the dfs starts both of the string contents are same which means we have successfully serialized and digitalized the n error okay that's it for today guys thanks for watching see you next time this is another version in this version we don't have to save the children size for each node we can just save a marker or maybe we can say the end of the children's node right so that's why what i have done here after the for loop is over i'm just saving a star saying that okay for this particular node this is the end of all the children right so in this way also we can serialize and we can deserialize like this | Serialize and Deserialize N-ary Tree | serialize-and-deserialize-n-ary-tree | Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following `3-ary` tree
as `[1 [3[5 6] 2 4]]`. Note that this is just an example, you do not necessarily need to follow this format.
Or you can follow LeetCode's level order traversal serialization format, where each group of children is separated by the null value.
For example, the above tree may be serialized as `[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]`.
You do not necessarily need to follow the above-suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself.
**Example 1:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Example 2:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[1,null,3,2,4,null,5,6\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The height of the n-ary tree is less than or equal to `1000`
* Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless. | null | null | Hard | null |
394 | Luti 19th Family Trick and Test Questions Quick Questions Verification Horoscope and Giving and Electronic Monitoring Should Give in and Your Destiny After Retired Sperm Decoding Andar Tuition Proves That You Need to Apply for Indian Wedding Night Inco Tracks Her Depot School Se Tube White Vinegar Kalu's and in the profits in the square brackets de routine to distic near to multiply the inco distic 's number of sciences 's number of sciences 's number of sciences friends this is primary what like share and subscribe 382 bc to 232 three times in the times subscribe and get notification to three Thank you alarms to the serpent come see and clothing blankets and another project direct suggestion result in the leaders pe luta anadhisasi subscribe now to three layer directly subscribe to main unse mili dushman suhaag iodine 100 gm ground master team while visiting sacrificed their life in do you Do subscribe now a beta testing that challenged the cat 1950 acne pimples award specified in question flashlight tweet hard and jo hai woh register to explain the better 210 1431 to take care of cheese victory or defeat in to-do list of units defeat in to-do list of units defeat in to-do list of units Opening subscribe The Video then subscribe to the Page That Exam Point Use To Stocks Bane Par Decode Wing Strike Enters The Frequency Strike Name Suggestions Obscure Doob Sk Egg Subscribe Channel Subscribe Must Use Pe Subscribe Button Video Ke Laddu Ap Ke Inside Baliyo Between To Do Not Use Pain Opening Meeting Pushed Into A Stagnant One Gets Into There Differing Subscribe Newspaper You Are You Later This Tours Subscribe Now To Receive New Updates Subscribe Bill Up And During The Times After Were U How To Times C How To In To C What You Will Get A APlus C I D C Is Vansh Garden With This Logic What Do You Will Need To Attend To Update Your Current Do Meanwhile Do That Pranav You Again Witness According Squash Racket Bath News Paper Ko Indian Do Something You All Subscribe Suggestion Times A B C D 210 Spring Boot Be Hands Free Times Aisi Printing Spring Dubai Jo Aisi Ko Again Aisi Ki Ajna Aisi Vishwavidyalaya Who Made The Logic Clear And Uses Code Of Middle East A Limit Findest Do Stocks Date of the Best Ones Centers Will Numerous Frequency Stock New Stock Picks Inside One Word Also Race Decode Spring Strike Evening Reduce Dark Pink World Tour Website Positive Typing Master End Uses StringBuilder To Make Current Track Volume Handsfree Mode On The Current STR Request What do you want to build? - Dilon Lighting This Parts What do you want to build? - Dilon Lighting This Parts What do you want to build? - Dilon Lighting This Parts Pretty Clear Why Am I Doing A Secure Zone To Build K Operator E Vetted For Multiple Editors Terrific Venus Actor Dot Is Later Now Pass Siddha Again And Difficulties In The Developed And Directory Top Three Do Subscribe Push Most Thursday Subscribe To solve the problem often a task dot posts ki kuch u updated with k on tasty ask tak dots on hua tha kar in string and disadvantages vikas from nou aur nonveg and you will have to recall the medical treatment subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page I soft frequency equal to flex talk to vote for you and also your willpower other value from the thing builder stock ashwatik interest in the current trend is top of the stock and now started building pending reason string with Temple run is the value of this great in0 for current a string daughter and a temporary string and you will reduce frequency nine on call 100 units make sure that you update key minister button is superstition pretty much at family tree logic will return current string daughter in law The students should depend on the train years of the test post which Ravindra commented on and accepted so let's talk over time and space complexity of this logic show you are hydrated Rudra character Aryavansh time complexity tree to draw lots of fun and species complexity veer the number of Frequency is the President in the frequency straight maximum reference country and similarly for President two drops in terms of complexity and time complexity both of them thanks for watching the video. | Decode String | decode-string | Given an encoded string, return its decoded string.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
The test cases are generated so that the length of the output will never exceed `105`.
**Example 1:**
**Input:** s = "3\[a\]2\[bc\] "
**Output:** "aaabcbc "
**Example 2:**
**Input:** s = "3\[a2\[c\]\] "
**Output:** "accaccacc "
**Example 3:**
**Input:** s = "2\[abc\]3\[cd\]ef "
**Output:** "abcabccdcdcdef "
**Constraints:**
* `1 <= s.length <= 30`
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
* `s` is guaranteed to be **a valid** input.
* All the integers in `s` are in the range `[1, 300]`. | null | String,Stack,Recursion | Medium | 471,726,1076 |
799 | Jhaal Hello Hi Guys Welcome To Code Ishwar Today's Question Champagne To Hour In This Question By Step Zinc Pyramid Form Swift Raghavan Classes Tubeless Tension Champion Is Food Hindi First Class Edit Top I Top Model School Any Access Liquid Form Will Fall Equal To 10 Glasses Immediately To The left and right profit in two slices Begumpul Nx Champion will fall equal to the left and right of two glasses and on fennel Example as this country needs pyramid of classes not let consider and example Shop back to after one cup champion Sports Stars School Intermediate Vihar Distance From It's Bachchan I Got One Glass Of Champions Top Most Top 10 Glass Album Full Nine Toe Cup Champion Supposed Toe Practice All This Se Control And Housefull It Mil Gaye 12th Board Only One Last Topless Pose Fool No Before Another Class Will Happen In The Morning In The Temple In Disgust Vikram Access And Will Get Transport Vidhi Glass Is Just All Its Right Side Just Want Right Side And Doesn't Left Side And Middle Distemper Will Be Transferred Equally 1 Minute One Plus One Point In This Again Hafte Sample Govind Is Classification Will Blow Your doing this class 8th three cup champion is code friends now we are full per graces total nine see how to customers in which intelligence top most powerful and history power second class one to 10 glass anti hotspot of the second class one to 10 glass dominant after Two classes of mode of champions b2b two classification but when one other classified add will happen to be divided into two parts subscribe The Channel Please subscribe and subscribe our already subscribe to the fourth class will get accommodated in the bottom layer dat is layer swine flu Se Lift The Middle Class Fifth House Full Scene In The Middle Of Difficulties Receiving The Exception From Distinct Classes Were This Side In Decide License And This Method Champagne Only From This Only From One Side Related To Parts Of Coming In This Life And Only One Part and Coming in Disgust Sudesh Class Fifth Sudesh Classification and District President Quarter Field Sunidhi Chauhan's Question Number to Do Hindi Question No Isi Giver Stock Giver Pyramid subscribe to the Page if you liked The Video then subscribe to subscribe Are in this classification par to This Point Question No Let's Look At You Approach Now This Question Know Nothing But Will Come Into Your Mind Will Find Jobs In Your City Click On Subscribe Button 65 Particular Glass Particular Can Find The Total Amount Has Been Passed Through Class 9th And Daksheshwar MP Now But they have planned they Office of CS B.Ed Course for Class 9 Office of CS B.Ed Course for Class 9 Office of CS B.Ed Course for Class 9 Sample A Photographic Samsung Airport So What Will Be The Amount But With The Amount Will Pass Swift 10th Amount Will Be Passed Through The First Class Amount Vijaypal Singh Swift Classification Ka Amount With three amount by 3 wickets e vent for VoLTE support in this glass tithi famous bangla soni sudhir from plus one class will get activated hair and waist thin classes discant pathrila se sweep e will be transferred to day one level election the total amount has been transferred To this level no the mountain man transfer to this level be distributed equally among brothers class 8th class at 3am when 520 class will contain 1.5 to 1.5 to 1.5 to hang 1.5 to hang 1.5 to hang 1.5 to 1.5 1.5 amount on 1.5 1.5 amount on 1.5 1.5 amount on which 141 spot near once upon him and president and given to The next level best to this river given to the next level north the total classes to the amount of champion batsman receive will be divided equally among Jain Sudhir with three drivers 2 and will be 151 589 not sat back subscribe to subscribe 1.51 12.51 अधि 0 अभी को Expressed Diwali In To-Do List को Expressed Diwali In To-Do List को Expressed Diwali In To-Do List Classification Distraction Sub Business Co In To-Do List Graces So That Will Happen In To-Do List Graces So That Will Happen In To-Do List Graces So That Will Happen 1.5 - Month Divide To It Means That 1.5 - Month Divide To It Means That 1.5 - Month Divide To It Means That Subscribe Point To 0.75 To 30.75 To 06 Subscribe Point To 0.75 To 30.75 To 06 Subscribe Point To 0.75 To 30.75 To 06 2010 Select Point To That Is Equal To Point Software Points 258 156 252 Silsila Wedding Point 25 Anti Silsila Se Batting Point To File From This Point To Face And Points 258 That Boat Give Access Of Sample In 20 Lakh To 0.5 Inch Of Akshay Champagne Because Point 508 Will Also Be Passing A Champagne B2 B1 B2 Glass Sudheesh Embroidery Superintendent of Police Grade Point 5.25 to 0.25 Song Again Grade Point 5.25 to 0.25 Song Again Grade Point 5.25 to 0.25 Song Again is 1.5 to - 122 is equal to two points is 1.5 to - 122 is equal to two points is 1.5 to - 122 is equal to two points 258 Amount of 10 Glass is Trot Point 2525 From this and want to hear from this point Total amount in here in this Light is point five and amount in this tool of this point to 500 hair point to 5.5 0.2 500 oy it is difficult even before field in hair point to 5.5 0.2 500 oy it is difficult even before field in certificate Sudeshwar center for this question with best app to find any amount visit to find the amount of champagne which have Been transferred to the next level Sogdu with former DPT Are and vacancy in first form of today there will contain Rooh Ko A from now also and will initiate myth 102 opposition party maximum number of every morning Android so and even text 2025 values where Android so and even text 2025 values where Android so and even text 2025 values where making are better Than 108 102 And Ka 102 Commerce And Ka Name C Initially What Will Happen In Bihar At This Level 3000 Civilized 0404 Increase Amount Increase Incoming Amount Will Be In Coming Out In Coming Amount Will Be Food Difficult Tourist Spot S4 Value 16200 Support Now C Point Na Using this new search tool that dentist in under query to fix exit policy total amount subsidize food in this check pink anti hero in which will find class and world-class isi ghee add class which one to find someone told that will there e will make world-class isi ghee add class which one to find someone told that will there e will make world-class isi ghee add class which one to find someone told that will there e will make to Listen Live Today Rose and Other Law Bills Industry Column Sweaters Drowned Crops Endangered People Sukhi Raho Ho's Earnings Plus Not Another Ludhi and Jaideep 120 Jewelers Dainik 2i to Z plus A to 89 to Nursing given 100 Already Know That 2010 Administrative Support Because total amount of village pond in this glass is only a and tell brother to find the total amount that has been passed by 20 lakhs to the next level change snake house will be found in its logical 21 that in physical To be that i d j n shri vijay 100 dj - 151 i d j n shri vijay 100 dj - 151 i d j n shri vijay 100 dj - 151 - one vikas bani k twenty-20 current class - one vikas bani k twenty-20 current class - one vikas bani k twenty-20 current class and divide by 2.0 solid will not be the will be double e which and divide by 2.0 solid will not be the will be double e which slow represents how much champion this particular glass will move Bill passed in next 15x levels will be equal to only tablecloth values for - 1381 2.3 to only tablecloth values for - 1381 2.3 to only tablecloth values for - 1381 2.3 divide so ash 1.5 to 1.5 indigenous left divide so ash 1.5 to 1.5 indigenous left divide so ash 1.5 to 1.5 indigenous left side 1.5 inches right side suno side 1.5 inches right side suno side 1.5 inches right side suno ko satiated and slow so 10051 only need to find ko turned on I took to find a This sample is given in Next Hum of Champaign Hindi Next Glass Otherwise Do Not Need to Find This Campaign in its Classification Zero No But They Don't See the Slice 1.5 9989 Elephant and 1.5 Se Slice 1.5 9989 Elephant and 1.5 Se Slice 1.5 9989 Elephant and 1.5 Se To Update The Value of This of These Classes Bilaspur Vanavrit 1.5 Additional Chief Classes Bilaspur Vanavrit 1.5 Additional Chief Classes Bilaspur Vanavrit 1.5 Additional Chief updated value of first class with divine father for no update please subscribe * father for no update please subscribe * father for no update please subscribe * strs subscribe in chief plus one is equal to the slow content 1.5 display content if slow content 1.5 display content if slow content 1.5 display content if selina gomez 1.5 logged in the five plus selina gomez 1.5 logged in the five plus selina gomez 1.5 logged in the five plus one check plus vansh hair oil political two plus Equal to slow is not 09:37 floor and spiritual not 09:37 floor and spiritual not 09:37 floor and spiritual benefits folk display 17vi plus one zandt is glass and representative vip lounge a plus 122 equal to plus two equal to slow sudesh and tire code to right and what do you do it andhi minimum officer -1 minimum officer -1 minimum officer -1 Comedy A View Of Queries On The Courier Roy And Query That Glass Ka Nash Better Return India And Growth Minimum One And 12th Class By Bond303 119 Degrees In Soul Valley View All 9 Class Will Be Free K Channel Aa Ki Suraj Kaun Si Reddy Co Disgusting Running and Love Later Time Decoded is the British and Its Getting Support Biogas Like This Video Thank You a | Champagne Tower | minimum-distance-between-bst-nodes | We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.)
**Example 1:**
**Input:** poured = 1, query\_row = 1, query\_glass = 1
**Output:** 0.00000
**Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.
**Example 2:**
**Input:** poured = 2, query\_row = 1, query\_glass = 1
**Output:** 0.50000
**Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.
**Example 3:**
**Input:** poured = 100000009, query\_row = 33, query\_glass = 17
**Output:** 1.00000
**Constraints:**
* `0 <= poured <= 109`
* `0 <= query_glass <= query_row < 100` | null | Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree | Easy | 94 |
1,437 | Hello Hi Guys Welcome To Our Jab Mitti In Speedometer Questions Related To All One For At Least Length Of Pleasure They Give 90K Through All The Buttons Are Not Kept Away From A Distance Between To That Similarly For Example 34 Hindi Conference Vacancy In The Land Forms Are Being In The History Of Each And Will Be In Between 0 And The Land Of Blood And E Will Give Notice For Next 9 News - Just Give Notice For Next 9 News - Just Give Notice For Next 9 News - Just Seervi - 148 Seervi - 148 Seervi - 148 More Increase Current Tax Otherwise Will Need To Find The Distance Between Two And Weather Or Not This Great To The Giver subscribe The 2012 - - - 1202 Liquid To The Giver Is In This Can Us Pahad Vriddhi Updates Reviews Current 10 - - - - 121 Subscribe Updates Reviews Current 10 - - - - 121 Subscribe Updates Reviews Current 10 - - - - 121 Subscribe My Channel Subscribe - K - The Position Of My Channel Subscribe - K - The Position Of My Channel Subscribe - K - The Position Of Way Away From This App Torch Light O Krishna O D Know Everything About Special Guests Who Held Hold To Take Web School Minus Points Away From 0 To Avoid A That In Her With Numbers Note Numbers Aaye Is One To Subscribe - Previous - To Subscribe - Previous - To Subscribe - Previous - Increase in 121 Good also come out of the for look and return Appearance and taste results Subscribe And The City of Victory over all elements in terms of that | Check If All 1's Are at Least Length K Places Away | minimum-insertion-steps-to-make-a-string-palindrome | Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example 2:**
**Input:** nums = \[1,0,0,1,0,1\], k = 2
**Output:** false
**Explanation:** The second 1 and third 1 are only one apart from each other.
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= k <= nums.length`
* `nums[i]` is `0` or `1` | Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome. | String,Dynamic Programming | Hard | 1356 |
520 | hello everyone in this video we will be solving problem number 520 detect capitals the problem statement is we have been given a string word and we need to return true if the usage of the capital Senate is correct there are three valid patterns in which we need to return true if the string matches that particular pattern the first is if all of the characters in The Strain are uppercase the second is all the characters are Locus and the third is only the first character is upper the rest all of them are lowercase we have been given the constraints that the world length will be greater than or equal to 1 and less than or equal to 100. now let's switch to whiteboard and talk about how we can solve this problem efficiently let's start by comparing the examples so if we look at the first one USA and Google it starts with the first character being upper word the character as index 0 is upper and the second character is what is defining the flow so it could be either uppercase or it could be lowercase so if I add one more condition to this J saying that what at index 1 if it is upper as well it means all of the character needs to be upper so I can then run a for Loop and then compare to make sure all of the characters are upper let's say if this condition is not met there are two possibilities this condition will not meet in this case the lead code example or the text Google the next for Loop will be to check if all of the characters are lower we don't care how the word started with but the remaining characters starting from the index 1 should be lower and the one more constraint that we need to think about is the word length greater than or equal to 1 and it is less than or equal to 100 and because of this constraint the word could be just one character so it could be a b smaller C smaller D Etc which is also a valid word in itself this solution gives us the time complexities of O of n as we are only iterating through the text or the word once and our space complexities of one I hope you were able to follow this explanation let me show you how we can implement the very same solution using C sharp here is the solution in C sharp I'll start by checking if the length of the word is greater than 1 if this condition is not met it will not go inside the if Loop and then simply return true the next check is where I am confirming if the first character and the second character are uppercase if the two conditions are met if these two conditions are met all of the remaining characters in The String should be uppercase so I am running and for Loop and then checking if the character is lower if yes then I am returning false and not continuing further if the first two characters are not uppercase then I am going into the else condition where I am iterating from the second character and then checking if any of the character is upper then I am stopping the flow and returning false thank you for watching this video I hope you were able to follow my explanation and the solution this solution is available on my GitHub repository the link is there in the description below feel free to check that out if you have any comments or suggestions feel free to reach out to me and I will see you in the next one | Detect Capital | detect-capital | We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like `"USA "`.
* All letters in this word are not capitals, like `"leetcode "`.
* Only the first letter in this word is capital, like `"Google "`.
Given a string `word`, return `true` if the usage of capitals in it is right.
**Example 1:**
**Input:** word = "USA"
**Output:** true
**Example 2:**
**Input:** word = "FlaG"
**Output:** false
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase and uppercase English letters. | null | String | Easy | 2235 |
806 | what's going on everybody today I wanted to go through and walk you through how I solved this number 806 number of lines to right string a problem on leak code this is by no means like the way to do it this is just how I figured it out it has a lot of downvotes I guess it's because I didn't really find it too bad the description but a lot of people are complaining are the people that are talking about this are complaining that it's um pretty poorly written but essentially this problem it gives you uh two arguments one widths another uh the string and widths is as long as the alphabet the English alphabet and so index 0 would be a in this case it's worth 10 B is 10 Etc and in the second example widths is the same thing a 26 character long or 26 length array and a in this case would be four so in this string which is BBB CCC DDD a all the A's are worth 4 pixels in this case so you're supposed to return an array where the first index is the total number of lines and the second index is the width of the last line in pixels so I've already completed this I've got my solution on another screen I just wanted to walk you through kind of what I did first thing I did was I made an array for the alphabet and then I'm going to make a object called alphabet with widths and for now this is going to be an empty object we're going to set the values of that in a moment so the first step that we're going to do is we're going to Loop through the alphabet and we're going to set each of these we're going to add keys to this object with corresponding numbers of pixels that each of these letters are valued at and if you remember widths is always going to be an array with the exact same amount of indexes as or the same amount of items as the English alphabet so what we're going to do is we're going to make a for Loop set it equal to or as many items as the alphabet Ray and for each of these alphabet items we're going to set the corresponding so like in the first Loop here we're gonna the value of alphabet at index I is going to be a we're going to set a new key in the alphabet with widths object we're going to set a new key with bracket notation and we're going to say alphabet with width at the Key of alphabet I which currently doesn't exist yet we're going to set it to widths since these are corresponding and they're the same length widths at index I and alphabet and at index I there will always be a value for each so that's all we're going to do in this Loop now if we console log alphabet with widths we should get an object with all the keys of the alphabet well we would if I spelled it right let's see alphabet with widths so now if we run that so we get a object with like a is 10 because the first index here is 10 which is which would correspond with a these are all 10 here but like in the second test case the first one is four so um a would be 4 in this case so all of these A's in this string would be valued at 4 in the future not currently but what we'll do next we'll so we're going to set a couple of variables here uh one is number of lines and this is going to be the um this is going to be the first value that we return in this array we're going to set this to zero for now and second we're going to write last line in pixels and this is going to be basically the leftovers each line is up to 100 and the last line in pixels is whatever not whatever overflows but like if these add up to 98 pixels and then you have another letter let's say Z if you have another letter Z that's four that's valued at 4 these first x amount of pixels would be 98 this would be four so this would count as the first line and then this one since it pushes it over a hundred this would add another line and this would be the value that last line in pixels would be set at hopefully that made sense it probably didn't if it didn't feel free to roast me all right so we're going to Loop through the string that we get in our second argument our parameter whatever this is called and we want to before I do anything in here we're just going to go ahead and return generally the structure that we will end up with at the end we're going to return an array we're with num lines being the first value and last line in pixels being the second value so in this first array we're going to go ahead and jump the gun we're going to add whatever value of alphabet with widths so this object with all the keys in it with the corresponding widths and letters we're going to go ahead and add that to our last line in pixels oh I didn't set this to zero set last time in pixels to zero and in this first Loop here we're going to write last line in pixels Plus or equals two or plus and equals to alphabet with widths at the Key of whatever letter we're at on string so like if we're at in this case alphabet with width at s at index I this would be basically at if s is a string that says BBB whatever CZ and if alphabet with widths at the Key of B has a pixel count of or a pixel value of like four then we're adding four to last line in pixels again hopefully that made sense so if we go ahead and console log last line and pixels here we should get a pretty big number so 260 we haven't done the line counts or anything but you can basically think of this in this case since 260 um you can divide that by 100 twice and there's 60 left over what it's expecting is going to be three because there's two full lines with a hundred pixels plus one because of 60 is like the leftover it's the last line of pixels so 3 and 60 is left over so we want to start adding two number of lines and what we're going to do is we're going to check if last line of pixels is over a hundred then we want to add a new line Plus or equals one I spelled something wrong last line of pixels oh last line in pixels so we want to add to num lines and we also want to we want to reset last line in pixels to the current value that we're at with alphabet with widths so instead of adding it we're just going to set it to whatever current letter we're at in this Loop so now we're very close if you see we'll run it we get two in this case since we have this was the one that valued up to 260. we get two lot two full lines and 60 but we need to account for this 60 at the end so that's going to be our last line even though it's not a full line it still counts as a line because it's a new line how many times can I say the line in one sentence that's a good question so we're just going to say if last line in pixels is over zero so if there's any left over we're going to add another line I can delete that run it again we passed both test cases now let's go ahead and submit it if you want to look at the code again here it is all right go ahead and submit it let's see how we did it beats 93 of users with JavaScript I don't know how true that is I feel like most of that is based on their servers because it's always a different number 42 megabytes that seems like a lot but again it's it seems like the number is always different so yeah I hope you liked it if you like more videos like this please let me know this is the first of what might become a series I don't know if you guys like it then you know that's awesome kind of like doing it anywho subscribe if you like the video like if you love like the video as well I appreciate you watching and I will see you next time peace | Number of Lines To Write String | domino-and-tromino-tiling | You are given a string `s` of lowercase English letters and an array `widths` denoting **how many pixels wide** each lowercase English letter is. Specifically, `widths[0]` is the width of `'a'`, `widths[1]` is the width of `'b'`, and so on.
You are trying to write `s` across several lines, where **each line is no longer than** `100` **pixels**. Starting at the beginning of `s`, write as many letters on the first line such that the total width does not exceed `100` pixels. Then, from where you stopped in `s`, continue writing as many letters as you can on the second line. Continue this process until you have written all of `s`.
Return _an array_ `result` _of length 2 where:_
* `result[0]` _is the total number of lines._
* `result[1]` _is the width of the last line in pixels._
**Example 1:**
**Input:** widths = \[10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "abcdefghijklmnopqrstuvwxyz "
**Output:** \[3,60\]
**Explanation:** You can write s as follows:
abcdefghij // 100 pixels wide
klmnopqrst // 100 pixels wide
uvwxyz // 60 pixels wide
There are a total of 3 lines, and the last line is 60 pixels wide.
**Example 2:**
**Input:** widths = \[4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10\], s = "bbbcccdddaaa "
**Output:** \[2,4\]
**Explanation:** You can write s as follows:
bbbcccdddaa // 98 pixels wide
a // 4 pixels wide
There are a total of 2 lines, and the last line is 4 pixels wide.
**Constraints:**
* `widths.length == 26`
* `2 <= widths[i] <= 10`
* `1 <= s.length <= 1000`
* `s` contains only lowercase English letters. | null | Dynamic Programming | Medium | null |
228 | okay let's talk about summary range so you are given a sort of unique integer array nums so you have to return the smaller sort this of the range they cover all of the number in the array exactly so i mean you don't have to release a description the idea is if you continuous increasingly you just have to sort into a format so from zero to one two right you sort into zero two and since there is no three right so four will be another minimum range to five and seven so um the idea is that you have to traverse the in array right and while you traverse you have the starting position and any position and for example the starting position is zero so you keep increasing by one and if you break out the loop since 2 plus 1 is not equal to 3 i mean this index value is not equal to 3 so your n value is right here the starting and n value will be 0 and 2 right so you would uh you will have to add into the list of string yes string and you have to re initialize the starting and end value so let's just go over uh it will be easier to type it so install equal 0 and equal to 0 and i do have a string so i'm going to call this and using arraylist so i'm going to traverse the integer right so if i want to traverse right and i already know my starting position which is actually zero ending position is d4 by zero first so i'm going to say it well i less than num sum length minus one and number i plus one is equal to numps i plus one and this in this idea is i the follow stuff from here and the values will uh take the i will take the job for the increasing right so it will increases by 1 plus 1 equal to numps 8 plus 1 right so 0 plus 1 equal to 1 right so at least at this point n will plus and i will plus so you will knock over the same index again so when you break out the loop which means you validate these stuff right so it's either star equal to n or not right so for example this zero one two right you are not uh you are not star is not equal to n right so that is this. and then we just have to say um sorry num star plus error plus nums n that would be your initials uh initial string for zero one two which is zero two and again four five right four five will be this as well output seven started start is equal to the end right so in this case you just have to do at least num is either star or either end doesn't matter but and you just have to know it's new string right and you're adding so the tricky way is using this empty string and then plus the integer which is return stream so when you add everything else right uh n will plus and star wars become n so we break out a loop and this uh i mean the end will be here right when you break out a while loop so you add a string into the base so you need to increment your end and start will be right here again so you'll re-initialize your n so you'll re-initialize your n so you'll re-initialize your n and in this while loop so there is an idea so you just have to return to this okay it's not hard but a little bit complicated okay i made a typo for sure right yes semicolon i just run again okay some middle toe all right it's good so let's talk about timing space okay for the full space you are storing every single line into the i mean possible right possible you possible store every single one into a list of string so that will be all fun and for the time simple it's all fun right you have to traverse every single element in the initial array so all of them for the time all the run for the space for the worst case and that will be a solution and this question is considered easy but i would say it's a bit hard because you might know you might frustrate in like inserting another loop inside for loop so that will be the tricky way and i hope you get it and peace out | Summary Ranges | summary-ranges | You are given a **sorted unique** integer array `nums`.
A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive).
Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,2,4,5,7\]
**Output:** \[ "0->2 ", "4->5 ", "7 "\]
**Explanation:** The ranges are:
\[0,2\] --> "0->2 "
\[4,5\] --> "4->5 "
\[7,7\] --> "7 "
**Example 2:**
**Input:** nums = \[0,2,3,4,6,8,9\]
**Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\]
**Explanation:** The ranges are:
\[0,0\] --> "0 "
\[2,4\] --> "2->4 "
\[6,6\] --> "6 "
\[8,9\] --> "8->9 "
**Constraints:**
* `0 <= nums.length <= 20`
* `-231 <= nums[i] <= 231 - 1`
* All the values of `nums` are **unique**.
* `nums` is sorted in ascending order. | null | Array | Easy | 163,352 |
392 | welcome to choice dynamic programming tutorial this is joey lately i have been focusing on some hot dynamic programming problems from lead code and in this video i will continue the trend by focusing on another lead good problem that goes by the title is subsequence without any delay let's check out its problem statement the problem statement is quite simple you are given two strings string one and string two and you need to find out if a string one is a subsequence of string two so string one is abc and a string two is ah bg dc you can see that abc does exist as a subsequence in ahb gdc in this case our dynamic programming algorithm should return true which we will begin designing in a few moments but before that if you haven't subscribed to my channel then do hit the subscribe button and hit the bell icon because that impacts my ability to create videos like these in a direct manner the plan is to find the length of the characters matching between the string 1 and string 2 in the same order as they appear in string 1. if the length matches the length of a string 1 that means the length of the matching characters matches the length of a string 1 then we can say that a string 1 is a subsequence of a string 2. let's first do some brainstorming before we begin creating and learning the algorithm i pick the first character from the smaller string and place it here and then i put the first character of the bigger string and place it here you can see that they both match so i would say that this a is present in this a and the length of the matching characters between these two strings is one right now i add the second character from the bigger string over here is it going to make any difference i mean the length of the matching characters will still be one right now consider that i pick the first character from the bigger string which is a and place it here and i pick the first two characters of the smaller string and place them here obviously in this case a b won't be a subsequence of a but we have got a match here so i put down the length of characters matched again as one this is just a vice versa case if we put h in this case the length of the matching string will be the same as the length of the matching string when the sub problem was the one selected now you see that both the cases give rise to the same sub problem if you add b to this sub problem you get this sub problem if you add h to the sub problem you get this sub problem in order to solve this sub problem or in order to find the number of matching characters for this sub problem when the last characters don't match the length of the matching characters will be the maximum value of the length obtained from this sub problem and the length obtained from this sub problem why maximum value for that pay attention to this problem we'll find out the length of the matching characters in the same style for this sub problem as well which contains ahb from string2 and eb from string 1 clearly the number of matching characters is 2 in this case now let's take a look at the second sub problem which contains ah from string2 and abc from string1 here the number of matching characters is only one you think now when i am interested in knowing how many characters match in order like a b and a b here what would i choose between 1 and 2 obviously because it's the right answer thus we choose the maximum one more case after which we can begin solving the problem straight away is this one we have a hp from a string two and a b from string1 in this case we won't follow the same approach because if you observe the last characters of the two strings match so they give one more match in addition to the length of the characters already matching excluding them so if i exclude them if i exclude the last characters then the remaining sub problem will be a h and a the matching character's length is one now we got another match in the form of p so the total length will become one plus one two i believe we have worked a lot on the intuition part and i have told the scenarios to you in the bottom of fashion there are two strings in this problem hence i have created a table the bigger string represents its columns and the smaller string represents its rows i have added a zeroth column and a zeroth row to this matrix i have also filled up the zeroth row and the zeroth column with zeros the reason of which you will know in some time we'll start from the second cell of the second row in fact the index of this cell is one comma one so conceptually it happens to be the first cell of the matrix here we have a from string1 and a from string2 they match so the length of the matching string becomes 1 which i populate in this cell we move to the next cell in the row we have h here by common sense when string one is a and string two is a h then what will be the matching length one only right by common sense i populate one in each of these subsequent cells we move to the next row now the sub problem is a from string 2 and a b from string 1 we just discussed this case so i populate 1 in this cell moving on to the next cell check here the sub problem shows up which we discussed moments ago so in this case we take the maximum value of the sub problem a and a h and a b since both are 1 hence the maximum value will be 1 which i populate over here moving to the next cell the sub problem becomes a p and a h b here b and b match so in this case what we do we add 1 to the value of the cell diagonally opposite to this cell because it holds the value of the sub problem a h and a we also discussed this sub problem hence we populate 2 in this cell moving on to the next is a problem let's see first if the last characters of the strings match so we have b over here and g over here clearly they don't match so in this case what we are going to do we are going to take the maximum of this value and this value what will be the maximum between 2 and 1 it will be 2 so i am going to populate 2 in this set so 2 here is the value of the sub problem a b and ahp and one over here is the value of the sub problem a and a h b g so we are playing by the rules that we discussed moments ago moving to this cell over here we have d as the last character of the string 2 and b as the last character of string 1 till this sub problem so p and d don't match so in this case we are going to take the maximum between this two and this one again we are going to do 2 which we will populate here moving to the next cell here b and c don't match so in this case again it will be the maximum of 2 and 1 so that is going to give me 2 so we have finished filling up this row now we move to the last row here the sub problem is abc and a so clearly we know that we are going to populate one in the cell but how the algorithm is going to know it is going to find the maximum between the value of this cell and this cell so between 1 and 0 what is the maximum one so the algorithm is going to populate one in the cell let's move to this cell here c doesn't match h so in this case the maximum of 1 and 1 will be calculated the maximum is going to come out as 1 because both the values are same moving to this cell c doesn't match with b so what is going to happen again the maximum between this value and this value will be taken out between 2 and 1 which is maximum 2 again now moving to this cell we have c and g as the last characters they don't match so it will be the maximum of two and this two what is the maximum between two and two they both are same so i will populate 2 in this set moving to the cell we have c and d as the last characters which again don't match so let me straight away populate 2 in this cell now we have come to the last set here we have c as the last character from string one and c indeed is the last character of a string two this is the final sub problem they both match so in this case what we are going to do we are going to go one cell back diagonally and add one to the value stored over here so 2 plus 1 is going to give us 3 and hence we are going to place 3 in this cell now we have calculated the value of our last cell what we are seeking whether the final value which is 3 is equal to the length of the smaller string that is string 1 for which we are finding whether it is a subsequence of the bigger string or not so 3 over here matches the length of string 1 hence the algorithm is going to tell abc over here is a subsequence of ahb gdc with this we have come to the end of this video you will find the github link to the java solution of this problem is subsequence in the description box below i hope you enjoyed watching this video i hope you learned from this video like it share it tell people about it i look so much forward to help you with programming and algorithms thank you and take very good care of yourself | Is Subsequence | is-subsequence | Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code? | null | Two Pointers,String,Dynamic Programming | Easy | 808,1051 |
384 | Hello how are you I am always doing good welcome to the boys is lips today will do safal and there and when July list challenge is question and answers in this question sholay 3d printed safal android ja re designer algorithm to randomly safal are all the best all The Best Be Like Ali As A Result They Are Hidden Succeed-Unsuccessful Fuel Adhoi Result They Are Hidden Succeed-Unsuccessful Fuel Adhoi Result They Are Hidden Succeed-Unsuccessful Fuel Adhoi Noida Me To Reset Me To The Great Job Was Originally 123 Again Succeed That Whatever Obnoxious Games Plate And Written By The Primitive 132 So This Is The Meaning Of A Question and this very easy because in python on the language switch off successful so I will cause successful and returned fail every time his first visit to cholera in random remix with the help of this module you can call must function so let's improvements 200 bean instrumental in To variable that some original research ka nature maintain deposit find out the final tourists can read what successful a dot hmm is it possible dot org divine channel na subscribe hua hai ab so ja yaar random a dot successful the sales bottom success delay na what is Written by Providence simply Om Namah Shivay this fruitful a habit and married women need to get the reservoirs maintained the original value in original are we India in the original are white sign in all the value of the rebel to our number are so let's the return It 200 random module has no attribute successful as hua hai so let's get whatsapp problem here that her so i think successful a 5 you alone it's nine read on 128 been finished in the summit to switch i speed have smell ₹100 switch i speed have smell ₹100 switch i speed have smell ₹100 interested Fasane To App Importer Random For Improvement In Failed Function And Is Har Is Video Dhari Search For Pyun Do The Change Now Nam * Original In Time And Space Change Now Nam * Original In Time And Space Change Now Nam * Original In Time And Space Ya Meet In Next Video Subscribe And Comment It Sirvi Ki Shubh Is Fruit Force Approach Ek Pan Is Afsar Years intercepted 200 hai ki a k is sabko friend ho gaya ki ripe solitaire safal saudi se zameen function hai ab hum and shudras hai so let's see the time complexity s well s kar do main aapke show a gaon and supple they are using this ultimate Safal that you can note Safal list inquitive random functions in the implementation of the same Safal use officer this feature also thing into being after and the 123 given date Safal vaccine soak of n time complexity of deposit users pet Safal algorithm which has been given ₹ 100 One algorithm which has been given ₹ 100 One algorithm which has been given ₹ 100 One Arrested For This Is Completely Bhigo Of Baroda Mistaken Belief And Us Of Taking Off And Exit Alternatively You Can Not Succeed List Random Function In Large Number Of And Limitations Of Friends You Succeeded Users Pet Succeed Algorithm Things Easily Into Being Offered Sweets Completed Of And THIS TIME AND AFTER EXTRA SPACE CONSISTENT ADMIT NEXT VIDEO BYE-BYE TAKE CARE NEXT VIDEO BYE-BYE TAKE CARE NEXT VIDEO BYE-BYE TAKE CARE AND DON'T FOR KIDS | Shuffle an Array | shuffle-an-array | Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling.
Implement the `Solution` class:
* `Solution(int[] nums)` Initializes the object with the integer array `nums`.
* `int[] reset()` Resets the array to its original configuration and returns it.
* `int[] shuffle()` Returns a random shuffling of the array.
**Example 1:**
**Input**
\[ "Solution ", "shuffle ", "reset ", "shuffle "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\]\]
**Output**
\[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result.
// Any permutation of \[1,2,3\] must be equally likely to be returned.
// Example: return \[3, 1, 2\]
solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\]
solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\]
**Constraints:**
* `1 <= nums.length <= 50`
* `-106 <= nums[i] <= 106`
* All the elements of `nums` are **unique**.
* At most `104` calls **in total** will be made to `reset` and `shuffle`. | The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31) | Array,Math,Randomized | Medium | null |
1,466 | hey everybody this is Larry this is day 24 of the legal day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's plan will you order routes to make all paths lead to the city zero yeah hit the like button in the Subscribe button join my Discord I hope you are having a great uh week so far um I'm gonna lie I'm very tired today I know I say that a lot but maybe I do I don't know hmm just gonna be a quick update but uh but if I'm a little bit slow please forgive me I did um I finally did deadlifts today and even though I didn't do all out I've been doing I did more reps and uh when I was doing it felt good but now uh and now I've been very drained especially since I did like uh three sets of uh heavy squads for Reps for like 10 reps each so that's uh I don't know my body's tired anyway okay let's see let's actually look at this problem my apologies for but I just want to give y'all some context and some people always ask for it anyway um okay so you have entities number from zero to one to end there's only one way to travel between two different cities last year the One Direction okay so then now travel to the city your task consists of beyonding some worlds such that each City can visit zero return a minimum number of ads changed okay um it should be okay I mean I think this is a regular um I mean I think the hard part about this problem is just about thinking about the implementation I think in terms of algorithm you know it's going to be either breakfast search at that first search you know one of the traversos um and then just figuring a way to kind of you know check uh which you know which way it is um the way that I'm gonna think about it actually is with um with uh what is this thing called so I'm gonna do this by first search for sure but the one thing that I actually want to use is that necessary so let me just think whether it's necessary maybe it's not even necessary maybe it's fine uh yeah breakfast which is fine I was going to actually talk about zero one BFS um but actually that doesn't even make I mean you could do it but it doesn't change anything it doesn't make sense so yeah so let's do it let's um they're still with my first search right so first of all we have to kind of set up the adjacency list and then now for UV in connections and in this case the direction actually matters right so this is let me double check from A to B oh I see and we want to go the other way okay Yeah so basically what we want to do is right now to use as an outgoing Edge to read uh maybe with a weight of zero say because if that's going in the right direction is zero and then for me the way that I want to do is just return um create a reverse Edge where the um the cost of that edge is one which means that we have to be you know the cost of it is one because that's the uh that's the cost of that's the coconut cost of changing one Edge right it's just one Edge oh unexpected yeah the course of that is just causing it as one okay and then now we can just do a breakfast search from zero so let's say we have a deck uh we want to put in zero and then now you don't even need a it's not the shortest path thing so you can just put the cause in zero and then just sum it up as you kind of go through it right so uh yeah so while length of Q is equal or greater than zero uh now as you go to Q top left and then for v in adjacency list of now uh we can just do I have to check to see whether they were done so done is you go to force times n so now if not done a v then we set it to done and then oh this is V and cost oops set of course if it's not done then costs added to C and then we put it in uh in the queue right and that's pretty much it and then we cost and I think that should be good hopefully I didn't have a silly mistake which I do why do I put zero did I make it oh I think I just kind of will just run the wrong way then because I forgot that you have to go yeah the direction here is a little bit awkward because basically our breakfast search is such that we're going outwards but we won but the ones that are going outwards caused something most the one that are going outwards you have to switch to go inwards okay that's this is why we test though um now it is more well uh more often well maybe did I get the wrong weight uh oh I didn't set ton of zero is equal to True is probably why got a little bit lazy on this one okay so let's give it a quick Summit yep uh 1088 day streak nice um this is gonna be linear time linear space and my linear time linear space I'm in V plus e which is the number of nodes and the number plus the number of edges this is going to be all of ends of the space uh this is going to be a re-space and this is going to be all of re-space and this is going to be all of re-space and this is going to be all of V plus G in total because each note gets popped once and all the edge each Edge also gets popped once right or twice if you want to count both directions or whatever but yeah um yeah that's why I have a display one let me know what you think uh yeah what did I do last time I'm just curious if I did it well I guess last time I did it the same way pretty much except I did it with uh that first search but I set it up the same way which is huh okay well yeah um oh well that's what I have for this one hope y'all have a great weekend coming up stay good stay healthy take good mental health I'll see y'all later and take care bye | Reorder Routes to Make All Paths Lead to the City Zero | jump-game-v | There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`.
This year, there will be a big event in the capital (city `0`), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed.
It's **guaranteed** that each city can reach city `0` after reorder.
**Example 1:**
**Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\]
**Output:** 3
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 2:**
**Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\]
**Output:** 2
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 3:**
**Input:** n = 3, connections = \[\[1,0\],\[2,0\]\]
**Output:** 0
**Constraints:**
* `2 <= n <= 5 * 104`
* `connections.length == n - 1`
* `connections[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i. | Array,Dynamic Programming,Sorting | Hard | 2001 |
328 | hello guys welcome back to Drake dose and in this video we will see the odd-even linked list problem which is odd-even linked list problem which is odd-even linked list problem which is from lead code day 16 of the May challenge so let us now look at the problem statement given a singly linked list group all the nodes together followed by the even nodes please note here we are talking about the node number and not the value in the nodes so you should try to do it in place and the program should run in a one space complexity as well as order of nodes time complexity so this is the entire problem we have a few constraints as well so as you can look here the first note is the relative order inside both the even and the odd groups should remain as it was in the input and the second thing is the first node is considered odd so indexing basically starts from 1 and goes on so let us now look at an example in order to get a better understanding so let us assume that we are given a linked list having 5 nodes so in this linked list our index will start from 1 and will go till n till 5 ok now the head is always pointing to the first node and we are given the head now we want to rearrange this entire linked list such that all the odd index node should occur first followed by the even index nodes and their relative ordering should be same that is in the resultant linked list as you can see all the Audion text elements are occurring first all the even indexed elements are occurring after the odd indexed elements and you can see that the relative water in this resultant linked list is the same as it was in the original linked list like 1 was occurring before 4 and 4 was occurring before 5 so you can see that in the original linked list as well the order was one four five in the resultant linked list as well you can see 1 4 5 followed by all the even indexed elements and they are also maintaining their order so 6 is occurring before two in this linked list as well 6 is occurring before 2 so this you should always keep in mind now I hope you got the problem statement so let us now look at how do we solve this problem before solving the problem we should look at some boundary cases so the first boundary case says that if we have no nodes then we will simply return null otherwise if we have only one node that the next of this head is equals to null then we will simply return head otherwise if we have two nodes then also we do not need to rearrange because the elements will already be arranged because the first element is odd second element is even and you want to put all the order indexed elements to the left and all the even indexed elements to the right and this is already in order so if you have two nodes then you don't need to do any operation only if you have more than two nodes you will do operations so let us now look at the first method in order to solve it I will be showing you two methods so in this first method we will solve this problem by using two iterations of this entire linked list therefore the time complexity will still be order of number of nodes so what we will do is we will place an end pointer at the end of the linked list okay and then I will also take a counter counting the number of jumps from the head till the end so in this case you can see that from 1 if you start jumping one node at a time then it will take you 4 jumps in order to reach the end node which is 2 so this count value will actually be important for solving our problem using this first approach because this will be having different values for even number of nodes and odd number of nodes so once we have fixed the end at the end of the linked list then what we need to do is we can just segregate the odd nodes on the left hand side and segregate the even nodes on the right hand side so whenever we encounter an even node we will just append it to the right of this end and whenever we find an odd node we will simply skip it so this is the entire idea for this first approach how this aggregation works ok let me show you I will take our temp variable so this will initially be pointing to this head now how do we process it so the end next will now be made to point to this for now this temp next will be made to point to temp next and now end next will be made as equals to null so these are the 3 steps which are required in order to swap the numbers that is make the even index element come to the last so this will just segregate it now after applying this operation always our linkless looking so one is now pointing to five and five is now pointing to three is now pointing to two and two is pointing to four and four is pointing to null and where is our end so our end was pointing to two and our temp was pointing to this one now since we have segregated one node to the end so I will increment temp to temp next and I will also increment end to end next now we will again do the same operation so what operation did we apply we will make and next equals to temp next okay after that temp next will be made equals to temp next okay so this link is also gone now and next will be made equals to null so this will make this node three come to the end so after applying this operation as well our linked list will look like one five then two four and three okay and this is pointing to null now where is our end our temp cause at five and our end was basically at four now our second operation is also complete so when do we actually stop this all depends on this count value whenever we have odd number of nodes like in this case we have five nodes then how many jumps to be required to reach the end node from the first node we will require n minus one number of jumps that is in this case it will be four jumps now for segregating all the even nodes on the left hand side and odd nodes on the right hand side we want to do see by two number of operations so C by 2 in this case is equals to 2 therefore we have already performed a 2 number of operations and you can see that 1 5 2 are basically the odd indexed elements this is index 1 3 & 5 this is index 1 3 & 5 this is index 1 3 & 5 they all have come together and all the even index elements are to the right hand side so this is the entire concept now if you have even number of elements then we will perform C by 2 plus 1 number of operations and you might be thinking how did I come with this formula actually I did some dry runs on these examples using even number of elements and odd number of these are the only two cases which are possible and therefore I came up with this formula so this works for this first method so let us now look at the code for this method and then we will see the second approach so this is the entire code for method one here we will check for the boundary case after that I will traverse the entire linked list and place my end pointer to the last node of the linked list and while traversing I will also keep counting the number of jumps to reach the last node from the first node after that I will check how many jumps did we require if we require odd number of jumps that means we have even number of nodes in total and for even number of nodes I told you that we will have to do C by 2 plus 1 number of operations and if we have odd number of nodes then we will basically do C by 2 number of operations now after finding out the number of operations I will take the temp variable which will be pointing to head and then I will perform these operations as I already told you it is a 3 step operation and these two lines are basically updating the temp and the end value to the next values so after performing these operations I will simply return head that is we are doing all these operations in place so let us now look at approach 2 I will take the same example and solve it using approach 2 so this approach 2 says that we will divide this entire linked list into two linked list 1 linked list will be having all the elements which are at the even indices and the other linked list will be having all the elements which are at the odd indices and then we will simply join them that is the tail of the ordinates element will be pointing to the head of the even indexed element so this is also a very simple approach now how do we apply the operation so for that we need to remember the head of the even and odd indexed elements so this will be odd head and this will be even head so I will take it as OS and eh now after that I will take two pointers odd and even now since we have placed the heads of these two linked lists we will separate the entire linked list into two parts so how do we do it so look at the steps very carefully so I will make odd next equals to or next now I will make even next equals to even next okay and after that I will simply update or with this or next and even with even next so this is gone here simply this process will keep repeating or next equals to or next and even next equals to even next so when do we stop actually we stop when even is equals to null or even next is equals to null so in this case you can see that this is even and this is pointing to null therefore we stop here now you can see that we have successfully divided the linked list so basically one is pointing to five is pointing to two and two is pointing to null now we have another linked list which is four is pointing to three is pointing to null so these are the two linked lists and we had already saved the heads this is odd head and this is even head now since we have these two heads and we want all the odd indexed elements to the left hand side of the even indexed elements so the next operation is to make the tail of this odd head point to even head so how do you do it after performing all these operations wherever your odd is pointing to is actually the tail of your odd list so you will just make odd next is equals to even head so this is the entire process and you will form this linked list and this is also an in place operation and you are doing this operation in just a single traversal so this is also order of N and order of one time complexity algorithm so let us now look at the code for this algorithm this was also a simple algorithm first we will do the boundary check after that I will take four variables even had odd head pointing to the first and the second nodes and then odd and even variable which will be traversing in order to separate the linked list into two parts after fixing the heads and assigning the variables we will do these operations so at each operation we will check if even is null or even next is null if this is true then we will stop otherwise we will keep running this algorithm so as I already showed you first two lines are basically updating the links and the second two lines are basically updating the odd and even values to their next values so that we can again do this operation iteratively after doing all the operations we will successfully divide the linked list into two parts and after dividing it we will make odd next is equals to even head because we want the tail of the odd linked list to point to the head of the even linked list since the even nodes should be present on the right hand side of the odd nodes after performing all these operations we will simply return head so this will be our entire algorithm I hope you are able to understand it if you have any other approach or solution in different languages then please post below so that everyone can take benefit from it like and share our video and subscribe to our channel in order to watch more of this programming video see you on our next show thank you | Odd Even Linked List | odd-even-linked-list | Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_.
The **first** node is considered **odd**, and the **second** node is **even**, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,3,5,2,4\]
**Example 2:**
**Input:** head = \[2,1,3,5,6,4,7\]
**Output:** \[2,3,6,7,1,5,4\]
**Constraints:**
* The number of nodes in the linked list is in the range `[0, 104]`.
* `-106 <= Node.val <= 106` | null | Linked List | Medium | 725 |
937 | video we're gonna take a look at a legal problem called reorder data in log files so this question doesn't really have a lot of up votes but this question is very helpful to do in my opinion because one this question is really it's frequently asked by amazon and the other point is that this question i think really tests your knowledge in writing comparators i want you to sort the strain array based on some kind of rules we might have to write some kind of comparators to do that right so this question really tests your knowledge do you understand the comparator function and do you know how to compare strings right so basically the question is asking is that you are given an array of logs or basically array of string each log or each string is a space delimited string of words where the first word is the id or the identifiers so there are two types of logs right so one is letter log so in this case you can see we're given a string we want to return a string array after we sort it right after we reorder the data and basically what is letter logs so letter logs basically means that all the words except the identifier right consists of lowercase english letters so let me give you an example right so this is a letter log right so you can see here the first word right is the identifier and the identifier we don't you can see that all the words except identifier consists of lowercase english letters right so these words right here these are the content and uh they consist of english letters right or lowercase english letters and then what and then we also have digit logs so digit logs basically means that um all the basically the content of this log right so it's like this one right here this is another example of this is an example of digit logs so you can see that except the identifier all the content in the uh in this log right eight one five one they're basically digits right so these are digits so they're digit logs so the goal or the rules is that reorder these logs so that letter logs right the letter locks right here comes before all the digit logs okay so basically we want letter locks first and then digit locks the second right or after right and then we also have another condition is that let's say we have a situation right where there is another letter log right letter locks are sorted lexical order by their content so let's say we have uh maybe another um letter log for example let's say we have a z here right so you can see that by looking at this we know that this is should be smaller or should we go before than this string right here because you can see the content there's extra z there right so the value therefore if we want to sort this lexicographically this content goes before this content right so in this case we want to sort the letter logs right if we were to compare letter logs letter log with letter log right then in this case we want to make sure we sorted lexicographically and let's say if their content is the same let's say they all have the same content so let's say they all have the same content but we notice that the id for both letter log are different right let's say we have put a two here in this case i want this to go before this right rather than you know rather than the opposite order right so in this case the end result will look something like this where so basically like this right because you can see um the i well their content are the same but the ids right this id is bigger than this id right character one is less than character two so in this case we are sorting sort of them lexicographically by their ids if their content is the same now if we were to have digit orders right sorry digilogs if we have two digit logs we basically maintain so the digital locks maintain their relative order right let's say we have another situation where we have this is another digital log right and you can see this digital log right here comes before right you can see this digital lock right here um comes before this one because the order this string right here comes before this string right here right so therefore you can see they're all digit logs right they're all digit logs and we're basically uh maintaining the relative order right in the output array so in this case you can see how can we be able to solve this problem well to solve this problem uh we have to basically follow the rules right so the rules is that we first have to make sure the letter log comes before the digit log that's one thing the other thing is that we once we basically uh done that we also have to compare to c if the letter locks are if we're comparing two letter locks right if there are two letter locks then we have to either sort them less go graphically by their content or if the content is saying that we basically sort by their id right so basically what we're doing is that we're taking these strings right these are given our strings so in this case what we're going to do is that for each and every single string or for each and every single log we basically split by this right we basically take okay this is our first substring and this is our second substring and then what we can do is that we can maybe like convert this into some kind of like a strain array right for example i can split it to let one and then the second element is art can right so you can see we basically uh take the first substring and then the second substring right by the space and then what we can do is that we can take this and then we say this is the id and this is the content and then we can basically compare right so this is what i did okay so before i jump through the code i want to talk about something i make a cheat sheet here so basically we have to know two things here so one thing that we have to review is how can we build a compare string right and the other thing is how can we write a comparator so let's say we have a comparator right unless we do our sort function in this case you can see arrays.sort we in this case you can see arrays.sort we in this case you can see arrays.sort we sort this string right here and then in this case you can see this is our lambda function right this is our uh comparator so this comparator um basically takes two elements right a and b okay let's say if i want to sort something right so let's say um in this case you can see we have a and b in this case we are going to return 1 if b should be before a right it doesn't matter if it's a string or a number character it doesn't really matter right if i want to let if i want to sort in a way where b comes before right a then we want to return one if we want to stay the exact same order where if a should be before b then we just return negative one if the order stays the same which is basically just going to return zero right and then in this case how can we be able to compare strings in this case you can see let's say we have two strings right a we're comparing with a we are returning one uh and then you can see one because in this case you can see if it's a one then we're just going to say b should be before a right so in this case you can see this is b comes should be come before a right or come before the first string right here so in this case if i want to compare two strings a dot compare to a in this case i should it would this function will return one okay and this function it would return negative one right um and then this because they are the same so it will return zero so now let's take a look at the code so you can see first what i did is that i just like i mentioned before i split them based on uh by uh separate the id and the content right so you can see i have a strain array and this split string function right basically takes a string and then we split it by the um basically by the empty string right and then this is the limit so we want to only split the id and the con and the rest of the string right so once i have a strain array that looks like this right the id and the contents then what i do is i basically check to see if it's a number right so first i check to see if it's a letter log or a uh if it's a letter log or a digit log how do i know that well i check the first character right in this case if it's a right if it's a digit right it will between zero to nine then in this case i return a boolean right so if it's a number right so we check to see if the first string is a number in this case it in this case is either true or false right so first what we do is we do a check to see if they're all numbers then we just return true because we want to stay the relative order right otherwise if it's if uh if number one is true but this one or the log two is not a number then we just want to make sure we want to revert the order right because we want to have the digit log come after the letter log and then if this one is true then we want to stay the relative order and then what we do is we check to see if the same content right if this string right here right the remaining content because basically what happens afterwards and here is basically means that we have two letter locks right at this point we have two letter logs what we do is we basically first check to see if the content are the same then what we're going to do is we're going to sort based on their ids right so in this case we basically see comparing this with this right just like this dot compared to right if this is a and this is b right you can see here um if a is bigger than b then we all will have to revert the order right if b is less than a then we have to uh in this case b is less than a then we're just going to continue right or sorry the uh yeah in this case we will basically have to return a value right so you can see here we basically return that and then what we do is we basically compare basically what we're trying to do is we're trying to sort ascending order right so you can see we're basically comparing the content if they're not the same and at the end you can see this is basically how we solve the problem and the time complexity in this uh algorithm is basically just going to be m times n log in and it's basically how many logs we have right or how many strings we have in the logs so you can see here we're doing our unlogging time complexity for sorting right we're sorting n number of logs but for each uh you know in this case for each comparator or each iteration or something right when we every time when we sort something time complexity right or basically this kind of like check you can see we basically have a m right a time complexity of m because you can see we're basically just going to uh traverse um the maximum log that we have we basically have to do our check and for equals two or compared to we usually have to iterate through the string right to compare each and every single character so that's why we have a time complexity of m times n log n | Reorder Data in Log Files | online-stock-span | You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (except the identifier) consist of lowercase English letters.
* **Digit-logs**: All words (except the identifier) consist of digits.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | null | Stack,Design,Monotonic Stack,Data Stream | Medium | 739 |
304 | welcome to mazelico challenge today's problem is range sum query 2d immutable given a 2d matrix handle multiple queries of the following type calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner given by row one column one and its lower right corner given to us by row two column two now we wanna implement a num matrix class where initializes the object with the integer matrix and then there's a function called sum region which is going to return to us the sum of all the elements inside that rectangle now initially we could think we could solve this straightforward by starting at the row and doing a nested for loop and just adding up all the numbers um inside of that rectangle but that would only work but it's not efficient is there some sort of pre-processing that there some sort of pre-processing that there some sort of pre-processing that we can do to make our function a lot faster so let's first think about what we might do if it was like a 1d array so say that we had a 1d array here and we want to figure out what's the sum of some sort of sub array like from here to here or something like that if we had a accumulating sum array so say that we just counted up all the sums in order 3 4 this would be 8 and this would be 10. all we would need to do actually is if we say that we want to calculate this what's the sum between here we would take the very end which gives us the sum from zero to this index or from zero to this index here and subtract whatever the sum is from the one previous so here with zero one four we would take um we would have to have one more integer in front like this to count up um for when it's counting here and we would get okay find the sum of eight and get this number here and minus one so here we can see eight minus three is going to equal five and that's going to be eight minus three right here this three here and that's gonna give us a sum and we can extend this concept to do it row by row we can just create a accumulating sum row per row for in our matrix and then add up all those down the line like we'll do the same calculation for 1d array and that's going to allow us to go from an m times n time complexity to an m complexity okay so let's initially first start off by initializing our dp array which is going to be m and n and let's see this would be the matrix rows and this would be the matrix of the columns now we want to do is create our dp array so call this dp and this needs to have a nested for loop we'll say four blank and range of the columns but we need a plus one here for that zero to account for when we're just getting to the very end zero index and we'll also have to say do this for range of m plus one okay so now we have our dp array now we want to do this accumulating sum here so let's get a little bit tricky but let's see four row in range of and i'm going to start one index and say m plus one and we'll say four column in range of one to n plus one what do we wanna do all right well we'll take the dprc and that's going to equal first the self.matrix first the self.matrix first the self.matrix we have to add whatever's in the matrix right we'll do a c rc minus one and we just add what came out what came before that so that would be uh same row but the minus one column here now let's make sure this looks right before we continue and nope it's not self.matrix all right so that does look like it's working right for each row we're saying 3 4 8 10 here it's like 5 11 14 17 5 11 14 16 17. yep so on and so forth so now all we need to do um with our sum region is just do it for every row so what we'll do is say start with an output of zero we'll say four row in range of we already have a row and row one here right so let's see since we're going to be doing our dp array we're gonna have to add one and here it's inclusive so for row two we're gonna have to actually add two here and i believe that's right let's see now what we'll do is get the self.dp now what we'll do is get the self.dp now what we'll do is get the self.dp for row and we'll get the column 2 column2 and we'll subtract self.dp column2 and we'll subtract self.dp column2 and we'll subtract self.dp r with column one but make sure minus one here finally just return our output and let's see if this works okay it seems i've made a mistake ah okay let's see ah okay so i think i actually need to do plus one here and column one b minus that yep okay so i screwed that up because of the zero index but it looks like it's working so let's go ahead and submit that and there we go that does get accepted so time complexity wise this is m times n when we initialize but the function here only takes m right because we only need to write down the rows so that would be it um we could actually do better here we could extend this concept and instead of doing it for the 1d array what we'll do is create an accumulating sum not only for this 1d array but we'll do it from the 0 cell and we'll iterate down as we count up the sums here like say that we want to find the sum from zero so six what we'll do is just take whatever sum came up here add whatever sum came up here and then subtract whatever sum came up here one time and that's gonna if you imagine like there's an overlap here with like some of this some of that and we add this number but we have to subtract the overlap here which would be this right so um if we did that then we can actually use the node one time by doing the same thing where we get the rolling sum and subtract the overlap between the two okay so let's see if we could get that to work all that needs to change is we still add a number here but now we're going to add two things or add one thing and subtract one thing so we add see dp r c minus one we also need to add r minus one to the previous column here so we add that and we subtract what r minus one c minus one okay so uh let me first make sure that this looks like it's doing what's supposed to okay so that does look right it looks like it's accumulating by both row and cells now instead of having this for loop what we could do is simply return let's see self dot have to get the uh row two and column two i'm trying to think i need to add one here i believe i do i need to add one to both of these okay but we also need to subtract self.dp um see row two plus one to column one and i don't need to subtract one here because it's already done that for me i'll subtract one subtract let's see i also need to do column two plus one but this would be row one and we would add the overlap back because we're subtracting it twice right so we just need to add back row one and column one okay so let's see if that works and that looks like it's working so submit it and there we go so this is the optimal answer this is going to be o 1 time complexity although this is still m times n now it's a little bit confusing i'd be very surprised if you were able to get here but i think understanding that accumulating sum on the 1d array is the key and once you know that i think all the other concepts kind of fall into place alright thanks for watching my channel remember do not trust me i know nothing | Range Sum Query 2D - Immutable | range-sum-query-2d-immutable | Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`. | null | Array,Design,Matrix,Prefix Sum | Medium | 303,308 |
1,656 | so I will discuss about a lead code problem on 656 uh designed and ordered stream so uh yeah we'll be given uh HTML paint ID key value pairs I hope you have already delete this problem so I will going to discuss about the code explanation you behind so first of all we see in our solution bar in Paris unexpected use so I'll discuss why Constructor is used here so first of all see there is no value now this is uh passed as the size of our value of 8 so here is the main cause high Constructor is used here okay uh first of all I will take a picture stick type now it's cheap zeros okay now I will uh resize my Vector because this Vector is not a not different how much size okay so I hope I think yeah I hope you know the concept of Constructor right so and I also repeat that if I call my class already the Constructor plus uh function will be gone automatically so now I recess my Vector size okay so that I can get my size of Vector so and now we stream dot resize password okay now come here I will uh get another Vector for uh get our input so our input will be stored here so the output will be stored here so it also is team type also of our estimates now empty right this stream is now empty and the size is and if the size is five then and blue will be pipe okay so uh now we will start uh the value which is passed in it we call for insert it will be I will be assign this value either this Jimmy vector so stream IDK minus 1 L minus 1 because look here that the order is start from 1 but we know that Vector is zero indexed right so zero next week one means zero two means so on 5 means four right so I have minus one then I'll assign the value okay uh next uh I will check while loop so I is less than our steam dot size okay this size will get by Constructor and we will check we'll check that our listing is not empty right is not empty okay if this follow this condition we will push Str Dot course back now we should be posted by right uh stream okay our R2 passed up to one case is accepted here so now I'll discuss how it worked okay look at uh it has a very Steep and into it pushback has IDK so first of all is uh zero indexed next value is uh we take one index doing next in indexed or indexed okay first of all look at that our input is high right input indicate IDK is 5 and value is not here so the value is now right so which position we insert tag in position 4. in position or okay but look here still our I value is zero so can you follow this first condition that I is similar size right yes then steam of I is not means uh it will not be empty right but it is empty in zero position we look it is still empty right it is still M K so this while loop will not be executed okay so uh next so this value is null right in 0 position our steam value will be sorry our Str value will be what will be that in position so it is now next we will call again insert right first of all we got estimate ordered steam uh by if it's called we get the size of uh estimate then insert first call is insert 3cc okay oh sorry five next insert is three comma CC 3 is in IDK value and this is value okay the next call is 3 comma CCC the 3 means IDK minus 1 means two position in two position it will be CCC row but our still the value of i 0 means in I position uh sorry e zero position value is still empty means uh and this thing okay this is interesting file so in this position also it will be a return empty okay position on next see look one is value and one is IDK Now 1 minus 0 means zero right the esteem zero position we have insert value a okay now check our while loop that in while loop a look that I is similar size okay fine that stream I means steam 0 is not empty and it also right that means in zero position already we have assigned AAA means value is here available so Str dot push back in Steam I position so now we will uh now we'll push our value in the our inner Vector Str vector so here will be inserted AAA okay next is uh insert number uh Port so in this fourth position who is 2 comma BBB to so two means one right so what means BBB now uh our I value in case right first of all it was uh zero uh then it is now one so in one position BB is available so our condition is fulfilled now we'll push back here okay BBB will push back okay next we will increase I The increased value will be 2 right but look at into position we have assigned the value CCC before right so it also will be uh pushed in this position now why it is in the same uh array it is pushed because it is the uh one two three four it is four term bar insert chord so this is that uh as it is same call so it is inserted there okay next is the last call insert now look what is that a 5 comma EEE okay one two three four uh five last okay fine to five call is in chart uh for five again one two a three or sorry for uh poor position we have got BBB and CC okay next we will call the position for uh this so it is uh I so in position uh pipe look here what is happen so in position 5 means four so uh there is a null value so it is also here okay now call insert this port number in third so here look here the ID key is 5 D is full so here look that it also in poor position it is inserted EE okay in Port position now it is inserted EE now we look that our condition will be matched or not it is 2 then in position uh to a chapter also applied with executed is this now three so we have missed it okay so in position three it is now also empty so this condition will not be executed so our string will be in this position is empty okay now the last call in chart so here IDK value is 4 and value is DDD so in position heart will be inserted here in position of 4 means a four minus one is three so DDD but uh okay now our condition will be uh fulfilled and DDD will be inserted there okay next we will increase 1 and it will be four in fourth position also a value is assigned which is eee so it will be also push back in our Stream So in our string is here so okay now we'll submit our code okay um okay it is accepted thank you for watching my video | Design an Ordered Stream | count-good-triplets | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values.
Implement the `OrderedStream` class:
* `OrderedStream(int n)` Constructs the stream to take `n` values.
* `String[] insert(int idKey, String value)` Inserts the pair `(idKey, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order.
**Example:**
**Input**
\[ "OrderedStream ", "insert ", "insert ", "insert ", "insert ", "insert "\]
\[\[5\], \[3, "ccccc "\], \[1, "aaaaa "\], \[2, "bbbbb "\], \[5, "eeeee "\], \[4, "ddddd "\]\]
**Output**
\[null, \[\], \[ "aaaaa "\], \[ "bbbbb ", "ccccc "\], \[\], \[ "ddddd ", "eeeee "\]\]
**Explanation**
// Note that the values ordered by ID is \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc "); // Inserts (3, "ccccc "), returns \[\].
os.insert(1, "aaaaa "); // Inserts (1, "aaaaa "), returns \[ "aaaaa "\].
os.insert(2, "bbbbb "); // Inserts (2, "bbbbb "), returns \[ "bbbbb ", "ccccc "\].
os.insert(5, "eeeee "); // Inserts (5, "eeeee "), returns \[\].
os.insert(4, "ddddd "); // Inserts (4, "ddddd "), returns \[ "ddddd ", "eeeee "\].
// Concatentating all the chunks returned:
// \[\] + \[ "aaaaa "\] + \[ "bbbbb ", "ccccc "\] + \[\] + \[ "ddddd ", "eeeee "\] = \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\]
// The resulting order is the same as the order above.
**Constraints:**
* `1 <= n <= 1000`
* `1 <= id <= n`
* `value.length == 5`
* `value` consists only of lowercase letters.
* Each call to `insert` will have a unique `id.`
* Exactly `n` calls will be made to `insert`. | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. | Array,Enumeration | Easy | 2122 |
9 | so we have to check if the number is palindrome or not and return a Boolean value according to it first we check if it is negative then we return false we do not have to go in the next step and check for the reverse number then if it is not a negative number we go and make a variable as reverse rev and a temporary variable where we store the value of x then we separate out the digits from the last position and put it in the reverse variable and then we check if the variable of the reverse variable is equal to X if it is true then we return that the that it is palindrome and else it automatically returns as false thank you | Palindrome Number | palindrome-number | Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
**Example 3:**
**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.
**Constraints:**
* `-231 <= x <= 231 - 1`
**Follow up:** Could you solve it without converting the integer to a string? | Beware of overflow when you reverse the integer. | Math | Easy | 234,1375 |
1,963 | hey everybody this is larry this is me going with q3 of the weekly contest 253 on lead code minimum number of swaps to make the string balance um so this one is a tricky one and the key thing to note about this problem is to hit the like button hit the subscribe button join me on discord give me some support give me some love uh but yeah and especially if you like these contests uh join me on discord because people talk about contests on my discord all the time and i try to help out as i can anyway so i solved this one in about two minutes and 30 seconds um and i actually spent some time just getting self second guessing myself the short answer is going to be greedy um in a weird way but i think you can usually spend a lot of time on this one if you um if you're not convinced or if you're trying to prove or if you try to do a crazy algorithm so the key thing also is noticing that n is 10 to the sixth so that means that you cannot do something in n square and anything greater than squares can be too slow maybe you can do things in n log n but that's about as fast uh as slow as you can get away with so here i took a better approach of thinking that okay that means that it's probably greedy and i think i also refreshed the page on this point and i saw that people already got it accepted um i was about five minutes in so maybe yeah i saw a couple of people got an accepted so i was like okay maybe it's greedy and i thought to myself all right let's look at the constraints right um n is even this is well-formed and this n is even this is well-formed and this n is even this is well-formed and this is balance you may skip over this particular piece but this piece is the key observation for this piece which is that is perfectly balanced so that means that you don't have any weird edge cases because you can get greedy as much as you can so the greedy way that i did this it's basically okay we implement this using a stack um if you have you know if you have questions about implementing the stack solution for checking whether um to basically balance uh parentheses definitely uh you know do other leak code problems that are relating to stacks and parentheses and so forth to get a good intuition about it um because this is gonna be you know it's gonna be key to understanding it so basically the idea will be that let's say we don't have any swaps this is gonna be roughly speaking this is gonna be our code and the only way that it's gonna be invalid is if stack is less than zero right because if stack is less than zero that means that we have too many uh too many negative things and because in this problem it's always going to be balance because the other possible case is that you have too many of these that are unbalanced at the very end but because that you always have the same number of opens and ends um this is actually not a case that can come up so the only bad case is if you have cases like this right um where you want to go negative so then our greedy solution is okay let's say we have some um some swaps like this what do we do well let's say we have some here so then now we push we probably pop and then we see this one right we see this one we go okay this is actually no good but what does that mean that means that we now want to switch this for the open right and we have to by you know because otherwise this is no good but which one do we switch with well we know that there is going to be one open somewhere in the world that's going to be unmatched in later we don't know where it is and for the purpose of this problem actually it does not matter because you can almost think about you know owning someone money in the future so you're holding you know right now as you get to here oh my god uh if you get to here you're holding someone an open parenthesis so let's actually just borrow one from the future and that's basically what we have and we kind of pay back in the future that's basically the idea behind this greedy and you can do more proofs to figure out why this works and this is because at the worst case you know you can maybe prove by induction as well and if you say sorry this looks weird because it keeps on auto closing for us so this is the base case and then you could kind of build more you know um more things between it but that's basically how you can think about it that way as long as everything in the middle is uh matched up so yeah so now doing um realizing all that we can just go okay if stack is equal to zero then that means that we need to follow uh from the future so then we and what happens when we borrow uh open range right well the stack link goes one and that means that we implement swap by one otherwise we do we don't need you know in a greedy way we don't need uh we don't need an open parens yet so we subtract it by one and that's basically it and this is um already i would say it's a queen solution and that's how you can see how a lot of people did in like a minute or two if they would prove to themselves um but yeah but we just borrow and then we return it differentiate the end and because we're always going to have the equal numbers of parents and closes we know that at the very end the debt would always be paid and then at the very end at this line the stack will be at zero um so as you can see this is going to be linear time because this is just a folder through the stack uh followed for the string and we implemented for the stack and this is all one space because we don't even you know we emulate the stack with a number so this is going to be just all of one space because we have two integers to store the problem um that's all i have for this one you can watch me solve it live during the contest next and you can maybe see how i maybe um just guessed i definitely to be honest during the contest i go load a little bit i was like i wasn't super sure during the contest but i just kind of gave it a go and because i couldn't prove this incorrectly and unfortunately sometimes greedy problems are like that you have to uh for contests anyway because you try to do it as quickly as possible and for me my trade-off was saying okay and for me my trade-off was saying okay and for me my trade-off was saying okay i did this is right and i'd do it quickly because i couldn't disprove it quickly or if this is wrong then i would get back a test case very quickly to figure out and then maybe learn from that test case um but yeah that's all i have for this one you can watch me solve it live during the contest next what a silly mistake okay yikes and i did it to optimize too if i didn't spend optimization i would have saved time so people where you got this that's crazy do yeah thanks for watching hit the like button hit the subscribe button join me on discord let me know what you think about this problem and the explanation and so forth in the comments or in my discord uh if you do contest you know come hang out in the discord and just you know talk nerd to me anyway hope y'all have a great weekend and stay good stay healthy the good mental health i'll see you later bye | Minimum Number of Swaps to Make the String Balanced | find-xor-sum-of-all-pairs-bitwise-and | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** strings, or
* It can be written as `[C]`, where `C` is a **balanced** string.
You may swap the brackets at **any** two indices **any** number of times.
Return _the **minimum** number of swaps to make_ `s` _**balanced**_.
**Example 1:**
**Input:** s = "\]\[\]\[ "
**Output:** 1
**Explanation:** You can make the string balanced by swapping index 0 with index 3.
The resulting string is "\[\[\]\] ".
**Example 2:**
**Input:** s = "\]\]\]\[\[\[ "
**Output:** 2
**Explanation:** You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "\[\]\]\[\]\[ ".
- Swap index 1 with index 5. s = "\[\[\]\[\]\] ".
The resulting string is "\[\[\]\[\]\] ".
**Example 3:**
**Input:** s = "\[\] "
**Output:** 0
**Explanation:** The string is already balanced.
**Constraints:**
* `n == s.length`
* `2 <= n <= 106`
* `n` is even.
* `s[i]` is either `'['` or `']'`.
* The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`. | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum. | Array,Math,Bit Manipulation | Hard | null |
24 | Hello everyone so today we will be discussing question number 24 of lead code which is swap nodes in pairs so la jo problem hai na this is a part of my recurring playlist and in the first video of this playlist I have discussed it in detail. How does Rick work, what is his intuition, how do we use it in problems, then watch that video thoroughly and after watching this, you will understand very well, but even if you have not seen it, I hope you will understand. Not that tricky question, okay, so this is the problem, I will do it in two ways, one is IIT and the other is recceive. Okay, now I will do it ideally in such a way that you are relieved that only recurs can do better than this and let recurs give us the topic. Don't have to deal, okay this is not a topic, it is a tool, we have to use it like a tool so that we can solve our problems, Rashan, if you make a topic and sit down to solve it, then there will be a lot of problem, if you use such a tool, then the question will be solved. It would be better to do this, okay, and the aim of this playlist is that we have to learn to use the recurs as a tool and not make it a topic. When we start using the recurs as a tool and not a topic, then we will have questions. And we will understand better that the questions will be solved easily, so before solving, let us see what we have to do. Okay, so we have been given a gender list. Now what do we have to do in that gender list, which are the pairs and these are the nodes. These are coming in pairs like this, okay, so we have to reverse them, we just have to reverse them in pairs, that means two of two should become 21 and this three of four should become 43 and the new gender list that will be made will be returned like this. If we have to do this, if there is a single node, then the returns will be like this, so now we have understood what we have to do, so let's see its solution iteratively, after that we will see its recursive solution. Okay, so let's solve it iteratively. Now this is our list here, this is our original list and this node here is this is a dummy node and our answer will be stored next to this dummy node, our answer will be stored, it means that our There will be a link list, its head address should be next to this dummy node, that is why we are using it because it is a reference node, it will hold our answer, rest of us keep making any changes in our original list. But in dummy dot next, whatever answer we have at the end, its head address should be stored. What happens with this is that we become sure what we have to return and what we have to return here, whatever our The answer will be stored in dummy don and we have to return the same. Many times we get confused whether to return head or return head dot nex. To avoid confusion, a dummy pointer has been created. Okay, so we solve it like this. We will do that this dummy pointer will hold our answer, now what do we have to do in it like what is the address in one, cross B is its address, what is its address in two, cross C, what is its address in three, cross D is its address, now we have to rotate it pair wise. It means, how should our gender list look like? 2 1 4 3. Two and one have been swapped and three and four have also been swapped. Now whose address should be on the next page of two, fill it yourself and see, pause. Do it and fill it so that you can understand, here there should be cross A, here there should be cross D, here there should be cross C and here there should be null and dummy dot. Next, what should be there is stored cross B. Neither do we have to return the cross B at the end. Now to solve this iteratively, break it down into smaller parts. Let's go with respect. This is the only pair you have. Okay, let's cut it for now. No, this is the gender list, there will be an even bigger gender list next to it, we don't care about that, we have to focus on these two notes right now, okay and after that we are left with the gender dist. We will focus, okay, to understand it, break it down like this. In smaller questions, it will not be much easier. You should understand the gender questions specifically because they become a bit tricky because in this we have to deal with the pointer, right? Let's do one thing, first of all we name these points like this is our head, okay this is our dummy, now what we do is create another pointer, the current pointer in which we are, whatever pointer we are currently in. Let's call it the current pointer. Okay, now let's make a previous pointer of the current one. What is the previous pointer? The pointer before the current one. Okay, we just have to create two extra pointers and nothing else has to be done. We have to reverse with these two pointers only. Look, we need the state of the current node and we need the state of the old node. To reverse it, you will understand why it has to be done, now how to do it, let's see. Okay, so here I have considered these two notes, the first two. And this one here is this pointer, this is the current one and this one is this one, this is the previous pointer, this is the current pointer. Now what I want here is that this dummy is to store my answer and the address of what is in the answer. What is B means the address of two here the address of two now I want the previous dot next pay what comes current dot next right how brother I want here at the end I cross B right and cross B Where can I get current dot next point because it is pointing to natu, now I want to point to dummy two, this is my answer node, so I point to it, now if I do this then it will go. The line gone is fine, it is not pointing to this, it is pointing to cross B, which means it is now going to point here, okay, so I have come from here to here, now dummy, point to this. Right, but one is also pointing to it, I don't want one to point to it, right, I don't want one to point to this, I want one to point to the next one, all the nodes after two. For now, let it point to one, which means I want the next one to be crossed C, the next one to one, it should be crossed C, not the crossed B, so if I make it cross C here and remove this line. Because A is not pointing to it, Y is pointing to Cross C and what is Cross C is this, here is the remaining list, it is mine, so here was Cross C, there was Cross D, right now I have nothing to do with it. Now one is pointing to C. Okay, so how will it be current of next. Look, this is current, is next current of next. Look, this is current, is n't it current of next? It means one cross b, which was just 1 cross b, that should be 1 cross c, where is that c? Okay, so this is the previous one, it is pointing to this node right now and there is cross C in this node, so how will I get it? Previous of Next, I came to this node, Off Next, cross C of mine. Got it, okay, now one is pointing to it, now we saw again friend two is also pointing to this, we don't want two to point to this, we want two to point to this, if you understood then what will happen, now here I am. I want a cross C, no cross A, this is I removed the line, it is not pointing to this, so now it should point to this, okay, so how will I write this, previous of next should be equal to current, look at this, look at doing a swap. What is there in this, whatever is in the RHS in your first equation, will come to the left in your next equation. Similarly, now whatever is in your RHS in the equation, will come to the LHS in the next equation, right? Have to deal with RHS, right in the next equation, so this was just a pattern, whenever I get confused, then I get confused, so I look into the RHS because I know that the next equation will help me with this. If I have to deal, then after that I see which node I have to assign and what to assign, this is a method, if you understand it carefully then you will understand automatically. Okay, now if you untangle this node. Neither how it will look like this zero dummy node is pointing to this two is pointing to one and one is pointing to the remaining list but the remaining list is not fixed yet nor is the remaining list not fixed yet So now we have to work on it, neither what will I do nor in the next loop, means this is my work done, nor is this my current, right now means look here, this is my current too according to this node. Right, and this is my previous, still this is my current, now the new node for me, new pair, is this, so what should be the previous in this should be the previous and this should be the current one right, so I will update it and how will I update it, whatever is previous will become current, see, earlier it was current, now it has become previous, right for this pair and this is new current, so current is equal to current of next bus. That's all you have to do, right? You have to write it inside the while loop, that is, this is the main code that I have written. Now we will write it in the wide loop and put small conditions. The rest of the code for H cases is done, so it is okay. Let's code it and see, after that if the recursive solution is ok then let's quote it. Before writing the complete algorithm, I will put a check that if head is equal to null and head is equal to sorry head of next is equal to null. What does it mean brother, if there are less than two nodes, no, it means if the head is null, sorry, it had to be null. Yes, now if the head is null, then return it as head. If the head of the next node is null, then also return head because Then there is only one node, what will you swap, so I have put a check here, now here I create a dummy node, okay, node A, I call it dummy and what will I do for the dummy here, I will create a new list note. I will create this, I can put any number in it. For example, I have put 20 here. Okay, I can put anything because I will return it next. Right now here is the list node. Here I will create a previous one. What will be the previous of the dummy node? It is equal, right? And here whatever will be my current will become head. Okay, now while current and current of next, now here why am I doing this, I will tell you. Look, first of all, I will give the edge to what I had written. Let me write this here, Previous of Next is equal to current of Next, OK, Previous of Next is equal to current of Next, this is what I am checking here, brother, I am assigning Current of Next, but if it exists. If I don't do it, then I will get an error, neither current nor current of next should exist, okay, now here current of next is the same, I took RHS, current of next is equal to previous of next, okay and here I have completely explained this before, next of next should be equal to current, that is why I am not saying it here again and again, it is equal to do, it is okay and what to do here, previous, now I will update my previous new one, previous e. Equal to current and current is equal to current that next okay now this is my solution here now what will I return means my complete swap is done because I will go to the while loop which will go to the next while loop now. Will consider the pair and after that will return dummy of next. Okay, so let's run it and see. Okay, so this is mine and after submitting it, let's see if this will also run and it will get submitted. Okay, so let's see its receipt. Look, now what we have done iteratively, it is a little tricky, it is not so easy to think about it, if you are doing it for the first time, but if you know the repetitions and you know that you should approach it repetitively, then you will get more. It will be easy, maybe even with the help of recurses you may not get that much the first time but if you have enough practice then you will be able to think iteratively. Thinking iteratively becomes a bit difficult because in this we have to deal with a lot of pointers. Well, let's see the recursive solution. Okay, so let's solve it recursively. Before that, I have kept this item code here because we will refer to it and see how difficult it is to itemize and how easy it becomes. Our recursive solution is fine, so now what did I discuss? For the recursive solution, I need three things. One is the base condition, second is the recurrence relation and third is the task. Okay, now what will be the recurrence relation here? Let's see that first. Like, let's assume that this is my function, now I have to decide on which smaller input I will call it, so let's first of all, what I call my function is that I keep these two notes with me and I send the remaining list to you and you give me the correct answer on the remaining list and return it to me. In the remaining list, you swap all the pairs and return it to me. I am the first two nodes that I have. Meaning, I will swap it and do something and attach it here at the end. Understand, what I have to do is that I have these two nodes, I have to take the tension of them and my code has to take the tension of the remaining list. Now here I have Why did I take these two notes? Why not just one note? Because I have to swap the pairs. Right, I ca n't do anything with one note. I must need two notes. Right, so here I am taking two notes. Okay now. If I am taking two notes here, then I will send B list right, so how will I send that D, if it is mine, then I will do next in it, off next, understand that this is the head, what is the next of this is this From here, the list is being shown which I have to send to the function, so this will be my recurrence relation. Now what will be my base condition, what will be the smallest possible input, right small possible input, what can happen brother see or So whether there is one node or not even a single node, because if there is not even a single node then return it as it is. Even if there is a single node, return it as it. What will we swap and see, I have already written this base condition. This is our base condition in active, I was saying that from here you can refer, from active itself you will make recive, you see here if head is equal to null and head of next is equal to null then we as it is head return. If we do this, then this will be our base condition. Now, why is our base condition happening here? Now in the beginning itself, I said it is fine, but what happens in the recurring case is that we have to tell our code that where is brother? If we want to stop, then our code will keep going on and on, but when the list gets smaller and smaller, then at the end either one pair will be left or not even a single pair will be left. Right, if there is an odd number of elements, if there is an odd number of nodes, then One pair will be left and one node will be left and if there is an even number of nodes then not even a single pair will be left and there will be a tap. If we keep sending our list like this i.e. head of next then the list is getting smaller. sending our list like this i.e. head of next then the list is getting smaller. sending our list like this i.e. head of next then the list is getting smaller. Right then at the end either one node will be left or not even one node will be left. Now if one note is left then we cannot swap. If even one note means not even one note is left if null return. If null is coming then we will return null. We will do it, so this is our base condition, our recurrence relation, we know what to do, now we have to see the task, what is the task that we have to perform, okay, so I told my code that brother, you put mine on the remaining list. Give the correct answer, the remaining two elements, two nodes, I have, I will manage them with them, this is my work, isn't it? Now what is this work of mine, I just have to swap these two, there is nothing else to do, right? So I give them a name p and I call it q. Okay, this node, I don't have to do anything to these two nodes, I have to assign q to it, meaning there should be an A on the next side of q, there is one by which it can be called Point to it and it should stop pointing to it. Okay because the swap is to do right and I want that one which is the new list which has come to us and we have got the answer return on the remaining list which is the correct answer. We have to assign beyond that. So what will happen here is cross B will be replaced by cross C and one is pointing to this one is pointing this one and what will we make return to q so if we make it return to q then How will the one who is our judge see us? How will the online judge interpret the link distance? First came two, then after that came one, and after that the remaining list which is the correct answer. In the remaining list, I have assumed that My function will return me the correct list, so that answer is correct. I have completed this part from my side. These two are correct. Now if these two are correct then this remaining list will also be correct. This is our induction. The theory is right, what are we doing in this, that now I have decided that this remaining list is the correct answer and the task to be performed on these two, I will do the reverse work myself, that's all. What I have to do is if I have done this and assumed that the remaining list is correct and why I returned at the end and if my base condition is also correct then the base condition should be correct and your request is correct. It should be there and the task you are doing should be right. Just pay attention to these three things and your question will be solved automatically. Okay and all, the most important thing in this is the task itself, what do you have to do which element do you have because this is the thing. There will be a repeat, right? And this repeat will keep on happening, every element will work correctly for every pair, right? You are calling on the smaller input, you are calling on the smaller input, then the task will be performed there also, the same thing. It is going to be a pair wise swap. So let's quote it quickly. After that you understand well what I was trying to say. Now let me write down what is the condition here. First of all, what is my base condition? The base condition will be that if head is equal to null and head of next is equal to null. If any such condition occurs that means there is only one node or there is not even one node then what to return. Head as it is return. Do it, now what I have to do here is that my P and Q notes were there and make them. I am here right and what will happen is list note P will become head right and list note why should be equal to head of. Next right now my recurrence relation will come what is the recurrence relation which is p off next should be equal to a which was my function right now I called the function on the smaller input what was the smaller input head off What is next of next? Now I am assuming that the remaining function or the function which is returning the correct answer on the remaining list, then p dot next p will be assigned right not q dot next and q dot next p. Will be assigned p, right, we have to reverse, we have to swap the note, data next should be equal to p and what will we return, q is just like this, nothing else has to be done, so see, it is accepted here and submit it and let's see. And it's done, so you see how small the code was and here I wrote the recurrence relation and this was my task q d nest eq t p This is the task I had to perform pd next equal to this end q d nest eq t p This was my task and this is my recurrence relation and this is my base condition from these three, you can say this also, this has come in your task right, you can say this thing also, you have performed this task, one but this. You saw how easily our recurse save code solved each problem with three things. That is how much we had to think to solve the same problem. That's why I am saying that it has to be used as a tool and not as a topic. So that you do not face any problem in future, see the next question. | Swap Nodes in Pairs | swap-nodes-in-pairs | Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[2,1,4,3\]
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Example 3:**
**Input:** head = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 100]`.
* `0 <= Node.val <= 100` | null | Linked List,Recursion | Medium | 25,528 |
815 | hey everybody this is Larry this is day 12 of the leod day challenge hit the like button hit the Subscribe button join my Discord let me know what you think about today's Fara uh I'm in miara on top of a mountain I forgot the name already because I've been hiking all day and it's siring uh but yeah uh here in Japan and that's what I have for now so you can watch me solve the problem now hey everybody this is Larry you actually already know that I forgot have an intro uh yeah I'm going to start doing more relocks so definitely if you want to follow that Adventure um I have a link below on that channel uh right now I'm in onii and yeah let's get started on today's lead code Pro uh today I went to do a bike ride um a very famous bike ride apparently in uh Japan uh and I didn't take a bus which is I'm put on this one so I'm kind of tired H and I'm my voice is a little bit low right now today uh because I'm inside of BNB and it's late later in the day and it's very quiet and um yeah so I don't want to make sure I don't wake up anyone so definitely uh my apologies if you have to turn up the sound you have to hopefully tomorrow I'll return back to normal anyway today's problem is 815 bus routes you're giving an ARR routes representing bus rout where R Sur is a bus rout for the I bus repeats forever so 157 means so Loops you start the bus stop source and you want to go to the bus stop Target you could travel okay so seems like that's the theme of this week is the shortest path problems right it's a hard problem not quite sure why but I guess we'll see so the least number of buses you may take and I assume they mean buses they mean like doesn't have to be distinct but uh so actually you're trying to minimize not bus stops but buses okay so that means that what does that mean so basically two routes or two buses have a path if they share at least one stop right and then basically just break first search from there right trying to think whether why this is like a hard but maybe this is just an earlier problem where they think everything is a hard um yeah 10 to the 5ifth could be expensive oh I was thinking about so initially I thought it was something like or not it was but I was thinking initially something like for two buses you know do an intersection and then see what stops they have in common but I guess what we can do instead is just build up that lookup table in a more straight forward way right so for example now we can do something like okay and is equal to link well say and then now you have for I range of n um you have B of I and then now you have for stop I guess in here um maybe you have like a stop look up which is um which is a um a dictionary of list and then stop look up of stop we can append I right that means that now all the things here are connected to each other and then now we can yeah right I mean yes but then now what maybe this is why it's hard I'm like this is easy but then I can't I'm not sing it immediately okay well everything in this stop it's only at most 500 square but can we avoid how do we do it in a smarter way right how do we connect like how do we create um do we even need to create that maybe not I'm trying to think how this would work or like because a lot of them a lot of my ideas they can spiral into uh a big complex if you're not careful so I'm trying to think how would you do that right so now we have to look up but how do you construct that graph been taking a lot of buses lately here in Japan but um still it could be 10 to the fifth number of them was ideally I think one thing that I'm missing or I missed a little bit is that the sum of the bout's length is less than 10 to the 15 Fifth so there isn't any Shenanigans where every Star has every rout actually maybe it can actually maybe it does deserve his heart but okay let's say we're at 15 what does that mean right that means that we could start off here or here I guess the way to do it is actually not because once you done a bus you've done all the buses right or all the things on that bus so you never need to do that bus again so I think you just remove stuff I don't know maybe that's a little bit magic right so let's say you have a set right and then now okay let's say start is youal to Source right that means that okay so for stop in stop lookup of source and technically it's not it's look up to bus right so this is a stop to bus look up okay so this is actually the bus and then now routes of bus yeah no I think we could then now we want to say and this is a regular break search right and now Q do aen bus with a distance of zero or just bus it doesn't really matter uh cuz we can just do distances and distances always have to be tied to a bus anyway right because yeah you take the metric is the number of buses you take right so okay so then now distance of bus isal zero right and then now regular PFS stuff the thing you want to do is that here on a pen we want to remove it from future things right so for stop in routes of bus um we want to remove it so stop look up of stop uh remove bus right so then now we don't have to look it up again so then now every time you re you uh check out a bus in any way then we also remove it from future lookups that's the part that I think can get a little sketch and if you remove it from future lookups then you should be okay because that means that now every bus stop can only be removed once so that means that this is bound by a linear in the size of the routes right so yeah so now okay right and now for stop and to bus let's say now we have a bus so now we're want to get adjacent buses where to Rel look at all the stops right next plus is equal to this right if distances of this is greater than distances of current plus one Andes and then now we C this up and this should never be smaller because if it's smaller then you already removed it right so I think that's maybe the big thing is to um remove the stops right wait what is this say no this is an array so sorry so full EMB in this that's why I was like what am I doing when you stop and V up and bus right and then also if stop is equal to s or Target then we return distances of current and then now we can return netive one I mean oh yeah okay I was worried about that I also I that's the part where I should vot this is where we should write a um inq function so something like that right and then now I actually suspected this would happen because uh well I mean just kind of looked like it because you're elating this and then you removing it um I mean the easy way to do it is just I think this would work because now you're creating a new Instinct yeah okay I mean it's not the right answer but at least it doesn't crash actually was one was thinking that it may be too slow but I guess that's fine so sources one okay why am I not queueing okay so it looks at pluss zero plus one Target six oh no what wait what I mean it looks at one oh this is silly okay it's still W but at least is sillier or less silly uh actually now this is right because this is the number of buses so this should be I this is wrong but it's I think just off by one let's give a submit I have some worries about time limit exceeded but apparently have something more basic oh okay so you don't take any buses at all even though there's a bus there fine that's a okay fine that seems like a gotcha but all right so not that bad apparent I got a wrong answer last time too there is the same answer it is exactly the same input what did I do last time I guess I did it the same way except for I did it less complicated um I thought that may be too slow to be honest but yeah uh this is just regular bre search the thing with the removal is that it guarantees uh it may be that it still is but with the removal it guarantees that each stop lookup is only used once uh when it's added right so that means that in the future stop lookups where is that uh it won't have that all those items right so that means that everything here should actually this will always be true right uh oops this will always be true for everything I think maybe I wonder if that's true yeah because of the removal this will always be true actually so you don't even need I mean that if statement doesn't do anything well like it doesn't it's not that much of an optimization but um but yeah so then now it guarantees that's linear time and linear space uh linear being the size of the uh the number of stops so yeah uh let me know what you think uh V plus year if you want to say well that's not even I'm just being lazy linear is the number of routes or number of stops on the total number of stops on the rout and yeah that's what I have for this one let me know what you think stay good stay healthy toal Health I'll see yall later take care bye | Bus Routes | champagne-tower | You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever.
You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.
Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible.
**Example 1:**
**Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6
**Output:** 2
**Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
**Example 2:**
**Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12
**Output:** -1
**Constraints:**
* `1 <= routes.length <= 500`.
* `1 <= routes[i].length <= 105`
* All the values of `routes[i]` are **unique**.
* `sum(routes[i].length) <= 105`
* `0 <= routes[i][j] < 106`
* `0 <= source, target < 106` | null | Dynamic Programming | Medium | 1385 |
907 | hello guys and welcome back to lead Logics this is the sum of subarray minimums from lead code this is a lead code medium and the number for this is 907 so in the given problem we are having an integer ARR and we have to find the minimum B where B ranges over every continuous array of ARR and since the answer may be large we have to return the answer to the modu 10 ra to 9 + 7 so suppose we have the ARR equal to + 7 so suppose we have the ARR equal to + 7 so suppose we have the ARR equal to 3124 so we have to generate all the sub ARs and then take the minimum from each of the sub AR and then simply add and return so we have all the sub arrays here we take the minimum from each sub array you can see 3 1 2 4 then one 2 and in a similar fashion take the minimum from all sub arays add it and return but uh if you would be taking uh generating all the sub arrays and then taking the minimum from it will be very complex and the time limit will definitely be exceeded so we would use something as a mon monotonic stack along with a prefix some pattern in this problem to solve the problem so we would need something like uh we would take left of I array and a right of I array and these two arrays will be used to store this first smaller element to the left and to the right of the current index I and if we have the first small index to the left and the right then we can use the formula IUS left of I into right of IUS one to uh efficiently calculate the number of sub arrays in which AR of I will be the minimum and then we can simply uh then we can simply add the number of uh sub arrays and then we can return I mean we can add the sum and we can return so let's see how the algorithm works we are taking the same example as this one 3124 so first we'll be initializing the two arrays left and the right so the left will be initialized with minus1 because we don't know what the previous element is to the left now and the right will be initialized with four that is the size of the array because we do not know what is the smaller element to the right of four so after this we have to also initialize a stack that will be keep uh that will keep the track of indices in and this track will be kept in a non- decreasing kept in a non- decreasing kept in a non- decreasing fashion so we'll be iterating from the left to the right okay and we have to maintain the non decreasing order so initially when I equal to Z the stack was empty we simply push AR of I onto the stack okay no problem we move to the next value when I equal to 1 ARR of I is 1 now we see the stack top was three and we have a element less than the stack top that means that this will not follow the non-decreasing order and we need to the non-decreasing order and we need to the non-decreasing order and we need to pop the element three that means the element at the top and we pop that and the left of I becomes the previous element that was minus one and stack now becomes empty and then we push the current element I we are actually putting the not putting the current element we are putting the index of the current element onto the stack and then we have the next I equal to 2 so here ARR of I is 2 which is greater than the stack top which is one so we have to do nothing simply push two onto the stack then we go to the next I value which is three we have I AR 5 equal to 4 so the stack top becomes four because we simply push it stack top was previously two now after this iteration the loop becomes left Loop becomes 1 - 1 - 1 and two and the Loop becomes 1 - 1 - 1 and two and the Loop becomes 1 - 1 - 1 and two and the stack contains 1 2 and 3 now we have done the calculation from the left side now it's time for the right side Let's see we clear the stack and then we do the same operations for the right as well we move from the right to the left push onto the stack check if the stack top is greater than the current element pop so you can do the same similar operations on the right side as well and then we can simply calculate using the formula as I told you this formula we can use on every for every particular index using the left and the right and then we can simply uh return the answer by adding it so 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 new to the channel so the first step will be to defining the length now we have to define the arrays to keep the track of previous smaller and the next smaller elements so we have defined the left and the right now it's time to fill the arrays do fill the left with the minus one and we have to fill the right with the length so the right is f with the length now we have to define the stack as well so uh let's take a DQ for stack it will be of integer let's name it stack to new ARR BQ and generate type now since we have to move from the left to the right and then we have to do the similar operation on the right or left so we do I = to z i is than l i left so we do I = to z i is than l i left so we do I = to z i is than l i ++ ++ ++ and while we have to check the stack. Top If the stack but first we'll check if stack is not empty so if the stack is not empty and a of tag top that is given by the peak if it is greater than or equal to the current element that is I then what we need to do we need to pop from the stack otherwise if this tag dot is empty if it is not empty we put left of I equal to stack of uh we'll put this peak that is the top in this if it is not empty otherwise we'll simply P the current element onto the stack we put onto the stack now we have to repeat this for the uh right as well this is for the left but before that we have to clear the stack here so we will do this stack do clear so I can simply copy this because this will not require many changes simply we have to change this part so n i becomes length minus 1 I is greater than equal to Z iusus and this will be the same stack is not empty and AR of stack. peak is greater than equal to this we can do is greater than here there we are using greater than equal to here we can use a greater than only and we'll perform a stack.pop and only and we'll perform a stack.pop and only and we'll perform a stack.pop and this becomes this will become right and this otherwise the same so okay this is for the right we have done for the right now let's define the mode in + 7 this was the value I in + 7 this was the value I in + 7 this was the value I think and we would have a long answer that is zero because the answer can be now see we have to uh do the total number of sub arrays where a i is the minimum and then accordingly we have to calculate the sum so we multiply the count by the value of the current position and we'll add it into the answer and we have to return it by doing the mod so as I already told the formula to you so we'll have answer plus equal to uh this will be converted into long first and then we have I minus left of I into right of IUS I so this is the uh what we were required according to form formula then we do the mod here for this and we have to multiply it to the AR of I value because multiple times if the same things occurs then we have to add it multiple times and once more we can simply do the mod for our safety and we can return from here the answer let's see if it runs fine or not sumary uh some error just let me check DQ is defined like this will be int because the return type is and so runs for the sample test cases let's run for the hidden test cases as well so hidden test cases also pass with a good time complexity and a good memory complexity the time complexity for this solution is O of n because we are traversing the array in linear time twice once here and the space complexity is also of n because we are using two o of n size of arrays like the left and the right so this is the time complexity you can also check the C++ complexity you can also check the C++ complexity you can also check the C++ python JavaScript Solution by going to the solutions panel and check this solution this is my solution here you can go and check for the intuition the approach explained properly the code Java C++ python JavaScript and yes do Java C++ python JavaScript and yes do Java C++ python JavaScript and yes do remember me to I hope the video helped you do like the video share it with your friends and subscribe to the channel if you're new to the channel thank you for watching the video have a nice day | Sum of Subarray Minimums | koko-eating-bananas | Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104` | null | Array,Binary Search | Medium | 788,1335,2188 |
84 | Hello, my name is Suren, this is a solution with easy to parse, number 84 logies rectangle in histogram, what do you need to do in this problem as input, you are given an array of numbers based on these numbers, you need to build graphs, number is the height of the graph, each column always has a width of one, this is the Constant you need calculate what is the maximum area you can place a rectangle on this graph in this example you can place a rectangle with an area of 10 place a rectangle with an area of 10 place a rectangle with an area of 10 Because we take a rectangle with a height of 5 and stretch this height to the adjacent column, the width is 2 because each column has a width of one, there are two columns Well, the minimum height element 5 and it turns out that the maximum area here is 5 multiplied by 2 or 10 in the answer we need to return exactly the maximum area. That is, what we got as a result of multiplying the height by the width and there may be a situation where we are given heights of 2 and 4 And here you can form Two square rectangles horizontally, height 2 and width 2, it turns out 4 or a rectangle with height 4 and width 1 4 by 1 or 2 by 2, you get 4 and we need to give an answer 4 Absolutely No matter how we came to this decision, it can to be both horizontally and vertically, the task constraints indicate that the heights will always be at least one, and the number of elements will be 0 or more. It turns out that we can return 0 if we have n’t received anything, that is, an empty list n’t received anything, that is, an empty list n’t received anything, that is, an empty list at the input. Well, you can see a hint in the tags for the task The stack is exactly through the tag. Let's move on to the analysis of how we would go if we solved this problem just in our heads, I think we went from top to bottom because we immediately see that there are a couple of elements of the highest height, but together they can be visually combined But what if there is a large width here, we can also get some kind of large area? Yes, and according to the conditions of the task, we need to go through the list in the code, we can’t just list in the code, we can’t just list in the code, we can’t just look and therefore Let’s go through the element from and therefore Let’s go through the element from and therefore Let’s go through the element from left to right, let’s start from the very first one, left to right, let’s start from the very first one, left to right, let’s start from the very first one, which is logical here too index 0, I immediately suggest writing down these indices and their values will be index 0 with the value 2, values will be index 0 with the value 2, values will be index 0 with the value 2, so we wrote them down, what we will calculate here, what answer we may have, but Let's prepare in advance that we assume that nothing will be in the list and therefore the answer will be 0 I will indicate it here right away. Now we can calculate the height of this graph, multiply it by the width of one and get a two, immediately write down what we will have here. Two is the next answer, but I suggest not to rush because 5.6 suggest not to rush because 5.6 suggest not to rush because 5.6 are in a row if we took just wrote down 5 and then another six, then we would be doing unnecessary actions because we will then also have to calculate the area of the will then also have to calculate the area of the will then also have to calculate the area of the entire rectangle with 5.6, so entire rectangle with 5.6, so entire rectangle with 5.6, so Let's First look at the next element which, under index 1 and with value 1, write X1 and value 1 But what do we see here We we see that the value of the previous element was greater, that is, two is greater than one, and we need to overwrite the current value. We understand that we cannot extend the two further to the next element, we can only do this by one, so first we take the height of what we have already written down and look how far back we can move by one minus 0 that is, by the index of the current element by the index of the element that we are removing and here it will be one, everything is logical, the width of this element is one, we have one column with a height of 2 Well, we take this height of 2 and multiply by the fact that we got one, here one is equal to 2, this is a new answer that we can remember and now there will be two the maximum value the maximum area that we found we will no longer need these calculations and what do we do with the values that are what do we do with the values that are what do we do with the values that are already here Well for 02 We have already calculated everything, but for 1 and 1 I propose to rewrite what we need to store here. We need to store not the values themselves, we already have them in the list, all values themselves, we already have them in the list, all values themselves, we already have them in the list, all elements by index will be available, but I propose to store from which index the current element can be extended for the index 1 will be index 0 because we can continue the current one from the previous element, so we will write in our column index 0 And the value 1 and this value is not a column with index 0 And value 1 is allowed starting from index 0 We can advance along height 1 from the very beginning like this and Let's continue what we can do with the element at index 2, we can just write it in our column 2 and the value 5 for now because we can extend the current element to index 2 and everything will be fine, but what will happen at index 3 is the same the very 3 and the value 6 again the previous element will be less than the next one and So we can extend the previous one to the next one this applies to the two previous ones But what will happen when we move to index 4 we need to repeat the same thing as we did with index 1 in comparison with index 0 We will first note that the 4th index has a value of 2. But this value will be less than the previous element. So we need to get rid of the previous one, take the element under index 3 with a value of 6, here it is and we can calculate it; its area will be its width 1 calculate it; its area will be its width 1 calculate it; its area will be its width 1 times its height 6 is equal to 6 and this is currently the maximum value, so we will write it in our answer that 6 We are ready to return it as an answer. It is important to note that we take this one for a reason because Each element is 1 wide and so it is clear, but because the current index is 4 And the previous one is 3 that is, 4 -3 but one and 4 And the previous one is 3 that is, 4 -3 but one and 4 And the previous one is 3 that is, 4 -3 but one and therefore we get one, but visually it is clear that the largest column there is 6 and it has no neighbors of such height, but when we go to the element under index 2 Another previous one because we crossed out the current one, it turns out that we take index 4 and subtract two from it Let's write 4 minus 2 equals 2 and this is the width of two elements under indices 2 and 3 and for an element with a value of 5 We don't just take its height, but we take the total area of two elements of the second and area of two elements of the second and area of two elements of the second and third here we need to write down this area, so we multiply the width of 2 by 5 multiply by 2 this two and we get 10 this is the new value that we will store in memory and it will be the answer for now since it is the largest And here is the value 5 with index 2 We also cross out from our list all these calculations are no longer needed and the main thing to note is that now we have two that can start not from the 4th index but even from the second, that is, the index that we deleted last, so Let's write down that 2 is the index and two this is the value that forms a rectangle here, we go to the next element under index 5 and value 3, we write it in our column, here there will be 5 and 3, again three is more than 2, so we do not delete the previous elements and now we have reached the end of our list with values What's end of our list with values What's end of our list with values What's next do We see that there are some elements left that we have not yet removed 0 with the value 1 2 with the value 2 and 5 with the value 3 on the left this is not the index of the value But the index of where this value can be pulled from now We need to go through all the elements that we have left and calculate what area they form, for this we’ll take the width of they form, for this we’ll take the width of they form, for this we’ll take the width of our collection, it’s 6, there are only six our collection, it’s 6, there are only six our collection, it’s 6, there are only six elements and it doesn’t matter what to read, we’ll go from elements and it doesn’t matter what to read, we’ll go from elements and it doesn’t matter what to read, we’ll go from top to bottom or bottom to top, here we’ll top to bottom or bottom to top, here we’ll top to bottom or bottom to top, here we’ll still look for the maximum value and as soon as we find it, we’ll and as soon as we find it, we’ll and as soon as we find it, we’ll overwrite the current ones, let’s go in order overwrite the current ones, let’s go in order overwrite the current ones, let’s go in order and process each from the elements we take an element with index 0 and value 1, it turns out that the width is 6 We take as a basis and subtract index 0, this is the index from which we can start stretching the height 1 is equal to 6 multiplied by 1 is equal to 6 will not be more than 10 so we leave 10 as it turns out that here we have built a graph across the entire width and height 1, take the next element index 2 and value 2 This means that starting from index 2 we can build a rectangle with height 2, take 6 as a base and subtract 2 this is the index from which we can start equal to 4 we multiply the height and this height 2 we multiply by 2 and get 8 is still not more than 10 but Let's visually mark the rectangle that we draw is a rectangle starting from index 2 and to not 4 index A to the fifth We we can stretch it to the very end and it turns out that here 4 multiplied by 2 8 is the area of the maximum rectangle the area of the maximum rectangle the area of the maximum rectangle that we can make at this height starting from index 2 and check the next element in this case it is the last one, we don’t know in advance whether there will be more than 10 don’t know in advance whether there will be more than 10 don’t know in advance whether there will be more than 10 or not will therefore need to calculate everything 6 is the width of the entire collection minus 5 is the index of which we can start equal to 1 and then we will multiply one by the height which is allowed here this is 3 equals 3 So we calculated the area of this last calculated the area of this last calculated the area of this last column, that is, from index 5 to at the very end of the graph all these answers 386 there is no more to tell therefore 10 remains the maximum value but it could have turned out So we would have got some 11 here and then we would have rewritten it in the answer what kind of structure We got here something similar we have already created in previous tasks on the stack and this is the so-called monotonic stack and this is the so-called monotonic stack and this is the so-called monotonic stack Well, either the maximum or minimum stack, the most important thing is that we store a pair of values here, some minimum a pair of values here, some minimum a pair of values here, some minimum value in our case it was the index of the element, the minimum index from which we can start building with such and such a height value Well, since this is a stack, we move from the very bottom to the very top. Well, or vice versa, from the very top to the very bottom, and we don’t know about the earlier bottom, and we don’t know about the earlier bottom, and we don’t know about the earlier elements until we sorted out the last ones that we added, since we go through the entire collection once and in the worst case then we’ll go through this collection case then we’ll go through this collection case then we’ll go through this collection again, it doesn’t matter back or forward, it doesn’t again, it doesn’t matter back or forward, it doesn’t again, it doesn’t matter back or forward, it doesn’t matter which way we go. We complete the task in about N time, where N is the length of the entire collection, but since in the worst case we can store all the elements of the original collection in our stack then from Memory we will also be about from N That's it, we can apply this algorithm to a structure of any length and find the maximum area here. Let's write this in code to begin with, I suggest declaring the result 0 in advance, it can be called whatever you like, that is, it will be area or maximum area Call it Whatever is convenient for you, the most important thing is that at the end you need to return this Max iriya, we also need to create a stack that will store all the values and indices. Where can they start from? Let's call it a stack, you can call it something smarter, but this is enough for yourself, you can indicate that here we store elements in the form of pairs, this can be full or something else and this will be an index and also the value I will pour Well, or hype since we have a list of heights his and we will fill this stack in a loop and count the maximum area we will have to go through two cycles. First, we will fill the stack and then everything that remains on the stack needs to be recalculated, so we will denote the first cycle for Index with a comma hate and will immediately unpack In Me Raid, we need to know the index of the element and numerate will immediately return the index of the element here. Simply pass this is the same hates, that is, We will need to get the index here for the first element for the zero one the value Index 0 And the hate value for example 2 if we are considering an example from the problem Well, inside this loop we will add new elements to the stack, remember that we did apend at the very the end of the stack of elements and here you will need to put an index and also a hate That is, I will pour this value but the index can change if before there were elements with a value greater then the index for this value will be the index from the previous element that we delete so let's write down what this will be Start Well or somehow else there will be an index here And we will already put it on the stack and we will modify this Start. Therefore, before we have already put a new element, we keep them in memory, but the previous elements from the stack need to be checked and, if necessary, removed since we don’t necessary, removed since we don’t necessary, removed since we don’t know how many elements we have already added and how many we will need to go back We need to use a while loop, we do a while loop and check that the stack is not empty the stack can be empty if, for example, we just started or before we deleted everything altogether, but having deleted everything we let's add a new element, so this check is essentially for the very beginning so that we can take the last element only if the stack list is not empty and then we check that the stack is the last element -1 And if the stack is not last element -1 And if the stack is not last element -1 And if the stack is not empty, then there is definitely at least one element there and we can easily find it let's take it and so we added them only here and there pairs and we need to check the height. And what is the height of the last element and we take it at index 1 because index 0 will be at start X1 at hate and this height of the previous element must be compared with the current height hate and if the height of the previous element is greater than the current one That is, if the current element has a value less then we enter this Loop And if it is the same Well or more then we leave it and we need to take the last element from this stack and immediately remove it from there let’s make a stack point pop let’s make a stack point pop let’s make a stack point pop we delete the last element and unpack what we get here, we get the previous one brought the index and also the previous one brought height That is, what was before now we calculate the area remember that we need to take the index of this previous one brought to count to the current index which we store in we get the index in numerate and look at the height and take the product of two elements height It is clear that we are now taking out the brought and the difference of this brought index We first take the index and subtract the Prius Index Let's calculate the area this will be an area and you don’t even have to write will be an area and you don’t even have to write will be an area and you don’t even have to write it down in a separate variable and overwrite Max hieriya will be Max, that is, the maximum value from Max Ire and what we are now calculating. And we will read that we have the height brought by Hyde and we have a difference in indexes, the index that we took in the loop, the index of the element that we are now processing to which we have reached, which is smaller in height Well, and the index of the element that we pulled out. That is, if there is a difference of only one, then here we can take the height by one, as we took with the six, the height for the six is 6 Well, the width is 1, it height for the six is 6 Well, the width is 1, it height for the six is 6 Well, the width is 1, it turns out that the total area is 6 Here We have written into memory What will be the maximum value in this case, it remains to overwrite Start since we have moved back by this element, then we can continue from that index, for example, remember for the two, we first wrote down the index that was the six, then the index that the five had because that two we can stretch starting from index 2 here and here Start will be equal to Prius Index that is, the element that we just pulled out and when we go through all the elements back, for example in the case of two, the element with index 4 we will go to the element with index 32 and here we will write 2 and the value 2 stack append 2.2 So you will go through all the heights 2.2 So you will go through all the heights 2.2 So you will go through all the heights in the list once, but we remember that there may still be values in the stack that need to be still be values in the stack that need to be still be values in the stack that need to be checked, so we will declare another for loop And in the same way this will be the index and the hate that we add into this stack is in Stack and we will unpack each element immediately on the go, there is no need to number it because we put pairs on the stack and these pairs will be decomposed to this index and the hate inside we will overwrite Max Ira again and here we will need to take the maximum value from Max and then go the height of the current element height in the same way as before, multiplied by the width that is formed here. And what width is formed, we need to calculate what will be the difference between the length of Heights LAN from hates, that is, from All elements We have reached the end minus the index with which we start with, this index turns out here, for example, 6 minus 0 and we will go along the entire width from the very beginning to the very end along the height 1 or for example 6 - 2 index along the height 1 or for example 6 - 2 index along the height 1 or for example 6 - 2 index for the value of five we will go starting from this column where 5 to the very end along height 2 and now we have processed all the options and written down Max and you can press the submit button to check the result, I mistyped here and made a mistake, of course the previous height needs to be multiplied by the difference between the current index and the index of the element that we are removing. It is logical that there will not be a comma here, but minus Let's press submit again and see what happens this time everything went well and we see some random numbers and we can be glad that we solved the Hard problem in just 20 lines of code. Did you like the solution? Was the drawing clear this time write about it in the comments, put reactions to let me understand, well, see you soon again | Largest Rectangle in Histogram | largest-rectangle-in-histogram | Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104` | null | Array,Stack,Monotonic Stack | Hard | 85,1918 |
1,300 | hello so continuing on this little code view click on test 16 the second problem was some of the committed array closest to target and so problem is medium problem with 1300 some of mutated array closest to target so the problem says is that given an array and the target value we want to return the integer values such that when we change all the integers larger than that value in the given array to be equal to value the sum of the array gets as close as possible in absolute difference to the value target which means basically as close as possible to it and can be smaller also can be bigger since they said in absolute difference and in case of a Taiwan or 10 just the smallest one the smallest value it that is and so this most difference in terms of the sum and we're gonna return this most value if there is a time and the answer doesn't have to be in the array right so for example in this example it is but so for 9 3 a target is 10 so the closest sum we can get to 10 is by replacing anything bigger than 3 which means we were replaced 4 & 9 it will get means we were replaced 4 & 9 it will get means we were replaced 4 & 9 it will get 9 as the sum which is very close which is the closest thing to 10 that we can do and then if we do this one and the target sum is 5 then the right thing to do is just keep it as there is and return the and just replace anything bigger than 5 which means basically just keep it as it is and get the value with the exact value target which is the best thing we can do a similar thing for the last example if you look here at the length of the array is 10 to the power 4 so or Noven algorithm linear search will be fine but we can't observe we can't do a double loop or something like that so let's see how we can solve this problem okay so let's see how we can solve this problem so the let's take an example here and so let's say we have this example for nine three two five one right so one idea we can think about it is okay so one observe engine first the first observation one can have is well if we try basically after max like if after the max of the array or actually from max array if we set value to be max array then that would mean that we won't ever need so if we set value to equal to max array that means nothing will change in the array right nothing will change in the array because let's say for example if I take nine let's say if I take the value T will be equal to nine well I need to change any value in the array that is bigger the night but since it's the max I won't change nothing now if I take ten I will change also enough and also I think if I take 11 I will change also nothing but sometimes the max is the solution because the array sum is it the exact value like in the problem statement the second example was two three five and target equal to ten so taking exactly value to be five so that we don't change anything will give us seven plus it will give us 5 plus 5 which is 10 right and the problem says if we have multiple solutions like there are very close let's say 6 gets us the same thing 7 we should take the minimum and the minimum is always the max right so that's the so that's one observation we know right so one thing we can say okay let's just try all of them let's try from zero to max or a and pick the max right just brute force that so try all from zero to max all right basically as value so try value to be zero and see if that gives you something close to target and see basically if that gets you something closer than the previous value set it otherwise continue and value equal to 1 all the way into value equal to 9 and if we do that here we'll find out that the solution it is value to be equal to 3 but we'll go all the way until max array and that's fine the only thing is that we since the array length can be the problem says that the array length can be equal to 10 to the power of 4 so that would mean here that we don't want to do over the square algorithm we don't want to do that and so ideally we should have all event right but if we try every one of them and every time we compute the sum in that case right that would be off max array multiplied by n right and that doesn't look like since the also the array values range between the problem says that the array is value are in between 1 and 10 to the power of 5 so we can end up with something that is 10 to the power of 5 multiplied by 10 to the power of 4 so that's not very good right so we will need to kind of make this a little bit better so the way we can do that is okay let's just try sorting right so if we sort the array what will happen so if we saw the array will end up with something like 4 9 3 2 5 1 right so if we sort the array like this we will know like that like this sorting that array won't give us that so sorting that array would give us it will give us 1 2 three two five one right I'm sorry two three four five nine right so if we saw the array and then try values from zero to max which is tonight so we will have we will keep so what we need is keep track of what we need is compute the sum right and the sum will be basically equal to all the values smaller than all the values in the array smaller than value plus all those that got replaced with value right so let's call values all the values that won't get replaced by a value because they are smaller let's call these left some and so and then it the rest that will get replaced because it's bigger than values that would be just the array of it would be basically the sum of value right for all a bigger than value such a is in the array right for a right so what that would mean is that we would just take the left sum so here in this example let's take a couple of values so for value equal to zero first we would have sell a statistic try a couple of examples so for value equal to 0 we would have well nothing is smaller than zero right so everything else is left sum so it's the sum of the entire array so it's a lot more to compute this so it's 1 plus 2 which is 3 6 10 15 and then we would have 24 right so sum would be 24 so actually the some it wouldn't be 24 so basically for zero we will check all the elements in the array the left's let me define maybe left some in a more clear way so left some is all array values smaller than let's call this here t so that we don't get it confused so here T is the value that we are trying to find and so all the array value less than T basically sum of all array values less than check right and so here nothing is less than zero and so the left sum would be 0 right so here left sum would be 0 and the right Sun which means of place everything in the array with zero and so that would be meaning replace everything else in 30 so we'll keep track of where we stopped it and here since we stopped it at I equal to zero because we didn't change anything right so the rights and us call it would be which is the right sum of 0 would be replacing everything with zero so basically it would be a rare I for I in the range so it would be array I would be replace it with 0 so it will be the sum of zeros for the entire portion of the array on the right which essentially means the length of the array so the range would be length of the array - I write so for all length of the array - I write so for all length of the array - I write so for all of them right and so that would give us left some the entire sum to be zero well we will check compare that with the we would have like closest so far or something like that and well we can initialize it with infinity so that we can always get the closest one and then we will compare using the different because the problem says the closest to target in absolute difference and so we'll compare using the absolute difference between the previous target and then your target right and that's pre we will then try for it equal to one and then at that point nothing is smaller than one so still our I equal to zero and still our left sum is equal to zero and I'll write some is old ones so it's one x for all the values that are not bigger than one all the ones that are bigger than one and so that would be basically a length of array - I again and so it would be just like - I again and so it would be just like - I again and so it would be just like that the array right and so we will close this closest so far would now be equal to one and then all try to now when we try to it becomes interesting because 1 is less than 2 right so we advance our I value and then our left some would become the value 1 right and then our right some now is everything except the first value so it's these values here and so it's 2 multiplied by length of the array - multiplied by length of the array - multiplied by length of the array - minus I which pretty much gives us length of the array is 1 2 3 4 5 6 so it gives us 6 minus 1 so it gives us too much so it's a step right so we have 10 so now closes so far because target is equal to 15 so the value for target on considering is 15 right so we compare well 15 minus -1 is right so we compare well 15 minus -1 is right so we compare well 15 minus -1 is equal to 14 and 15 minus 10 is equal to 5 so this one is better and so we said closest so far to be equal to 10 right and then we try three now three also is interesting because 3 is less than smaller than 1 and 2 are smaller than 3 so that would mean we would advance I by 1 by 2 so I was 1 because right now since I write I is smaller than T equal to 2 we know that it since the array sorted is by definition smaller than T equal to 3 so we don't have to go back and count all those that were found in the previous t values and that's where the optimization comes from and so now we can just say I plus 1 so we start from I equal to 1 and start from this left sum we don't need to recalculate it because since it's smaller than T equal to 2 it's necessarily smaller than T equal to 3 because they already sorted so now our I is equal to 0 1 so we advance so now our I is equal to 2 right so now our I is equal to 2 and our left sum is equal to 3 and our right sum would be essentially the value of T so 3 multiplied by length of the array - I right that's all the values that are - I right that's all the values that are - I right that's all the values that are left because that would left that are left because that would mean basically that we will keep one two and then replace everything else so what applies for here what applies to three first replaced with 3 9 or replaced with 3 so that's why we are doing 3 multiplied by all the rest this is length of the array and this is I and so we say length of the array this is I here length of the array - I this is I here length of the array - I this is I here length of the array - I that's the number of 3s we have so that's 3 multiplied by so length of the array we said is 6 - 2 that's 4 and that array we said is 6 - 2 that's 4 and that array we said is 6 - 2 that's 4 and that gives us 12 and so again we compare 12-15 that 5:15 - 12 that's 350 - 12-15 that 5:15 - 12 that's 350 - 12-15 that 5:15 - 12 that's 350 - standards 5 this one is better so again we get closest so far to become 12 and of course when we find closest so far we need to update the current value so here the current value is 2 here the current value is here the current value 3 here the current value is 2 and in this example we could go I could go and try to equal to 4 but this is the answer C equal to 4 will now give us a better answer but yeah so this is the essentially the idea is let's try the values from 0 to all the way to the maximum of the array and it's to avoid doing this here this time here we are going to keep track of left some because since we sorted the array we won't need to calculate the left sum again because when we are here and we already know left sum is this and we are trying a new T value we would know that it met all the values that we already put your left some are smaller than this care of T value right and so we'll just keep increasing I and keep increasing left some right and so let's see how would that look like in terms of code so in terms of code we would have to do would have sold us define our function was fine best value with well we'd had array and tie it so first when you need to sort the array so I take the array we sorted right then we need to have both clauses so far right closest so far and the value that is that it represents and then we initialize that to infinity self float maybe and in Python and then the values will start out as 0 and then we need left some since we keep track of it and it doesn't change we're looping because we are who is out of the array so we initialize it outside of the array and now we can go through the array here and we can go through the possible values using from zero to max array as we said so 40 can range of from zero to the max array value and in Python together value we say a plus 1 from here what we can do is well we all the values smaller than the target value those are left some right so we will need to put these there so we need also our eye index since our eye index doesn't get racialized with each value as you can see here because we know that we already put these values in left sum and so what we do here is we said while of course we have cell elements in the array so while I is less than the length of the array and of course the array value is less than T right because it's bigger we need to replace it so if that's the case then we need to add to the left some right and we need to advance our eye pointer now we have the left some now we need to calculate the right sum which we said is just the target value multiplied by the length of the array minus I and so the sum the current sum that we are trying is left sum plus write sum which is T multiplied by length of the array - I multiplied by length of the array - I multiplied by length of the array - I right and so this will give us the and so now what with that we have the entire sum we need to check if it's better than the clauses so far so we say if in terms of absolute difference of course so if the left sum so we say if fluffed sum is so if left some mind start sorry not love some if the scant target - killing love some if the scant target - killing love some if the scant target - killing some so target - s is of course we want some so target - s is of course we want some so target - s is of course we want the closest right so we try to see if it's less than what we had before which is target - closest so far so if that's the case that means that we find a new better value so we say closest so far is equal to s and then value is equal to T right and then we at the end we return value so we could see here for while going through T we didn't train initialize I and we didn't realize left some we kept accumulating into left some so that we don't go and repeat and so that makes it that we go through the array only once so it's open actually and then we go through all of the T values and so it's kind of open a plus T instead of x and yeah so that's pretty much it so sorting it allows us to do this accumulation here without needing to rationalize the array that's the main insight the rest is just trying all the T values and seeing which one is closest to target yeah so right now we all put this in my code and see if it passes okay so I type it the solution that we just went over so erase sorting and then first after that we go through all the possible values for value and then we act left sum and then we compared against target and we pick the best one and we accumulate must sum and uh and keep increasing I and we never reinitialized them because the that's the optimization we are doing we because they are a assorted it works out so now let's fundus and submit ah submit okay so this passes this cases okay so the other way we can solve this problem is using binary search because we can find specific property of binary search that is when we find usually is we can solve a problem using binary search so let's go over this one so basically with binary search who need to find a pattern where we can see that we can have a predicate so there is the normal binary search of course where you can you need to just find a value at a specific if the value is in the array or not but the more generalized version is we can read to find a predicate or some kind of test function that allows us to kind of have a pattern where that predicate will give us value while we are searching in the range of binary search which is low to high using of course mid value here we can we find that the condition if we pick some mid value its force then its force keeps force in the range but once it reaches the solution and when you keep going to the right it's always true right the condition becomes a true and whenever it went to become the true it keeps being true it never goes back to false like this and of course this is it can be the other way around it's not limited to force them true it can be also like true false but the essential idea is once if it becomes false it never becomes true again right and we are looking either for the first true value first true thing or the first false value and so if we can formulate our problem in terms of finding it the first false value or the first row the last false value or the first true value then we're going to solve the problem in binary search and so that's what I'm going to try to do here with this problem and so one thing we can do is define get some function so if I define f of X as the sum so I'm going to define f of X as the sum of all the values in the array that are less than X otherwise I just pick X right so this is exactly what the problem says it's basically find all the values that are bigger than so here we can say bigger than some specific value replacing them with that value right so that's exactly what I'm doing here and this is for I a in array right so this would be my function so and this is what I'm looking for I'm looking to find the sum using this here using some specific value of x that I want to find this X here such that f of X minus target in terms of course of absolute value is as small as possible right that's what I'm looking for and so here if I find that f of X is bigger than target so if I find that f of X is bigger than target then if I increase X then f of X will be bigger will only increase right because I will be replacing with increasing value and so it will only increase right and so that would mean here that what I can what I would have is so the absolute value for is the absolute value of target minus f of X or f of X minus target so its target minus F f of X and so my function here would be that I would keep I would have something like okay this is not the close as possible this is not let that lost well possible this is not like and then I would have true f of X would be bigger than target and from there it will keep being bigger than target right so here f of X is now bigger than target but once it becomes bigger than target once it becomes a bigger than target it will keep being bigger than target right so and what I'm looking for is just finding these two here and picking the smallest of the two right because it's either the close the solution is either smaller than target but very close to it or bigger than target but very close to it's only these two boundaries the boundaries close to f of X equal to target right so here this portion here would be f of X less than or equal to target and this portion here would be f of X bigger than target right so now I have my binary search pattern and I just need to find what is the range that I will be searching on right so here remember I'm doing f of X so my variable here is X which is the possible value that I'm looking for and so X can be from zero to target or from zero to max array we can it can be more than that so I could try from zero to target because well I can also try max array because if I take max array as my value the array will stay the same if I take something bigger that's not useful because the array will still stay the same right so this is the range of my binary search and that's all I need for binary search I need to find my function that I will that will tell me to go left or right and then I will need to find the range that I will need to go in right so that's pretty much it so the only thing is when do I go left and when do I go right so if I find that my f of X is less than or equal to target right so if I go to the left I won't find anything better because it would be only smaller than target than the previous value so this would mean I would have to go right to find a better solution so this means go right which basically means low equal to mid plus one which that's a Gore or the go right is otherwise if it's bigger than target that means that if I go more right I will only find bigger values so the difference will always be bigger and so I shouldn't go right I should go left right and so here I go left and that would mean high equal to mid minus one and here since I don't know like maybe the closest value is that the one here or maybe here so it's kind of slightly different I'm not looking for the last force or the last true but I'm looking to the smallest value between the two so that would mean here I will need to compare and see which one is smaller right and so that's what I'm going to do here with my balancer so let's just write it in full here so it would be def find this value we'd have the array and target and we'd have our binary search right so here we need of course is was that I already to find the FX function I already to find it here and so my low and high values would be zero and target as I said I can also say this is max array and then normal binary search low less than or equal to high I compute the mid is low plus high / tube the mid is low plus high / tube the mid is low plus high / tube using this so that we can avoid overflow and then the sum would be F of mid right because MIT is representing the values of x that we are looking for and then I need to have a res value that kind of stores the closest sum so far and then I would need to have the value itself tower that I will return and I'll initialize both to I would initialize this one to infinity in this one to 0 right so I would say if s is lost the target as we said earlier that would mean I need to go right so I need to go right which means I to say low equal to mid plus one and since as I said I don't know which one is the solution with it's the last force or the first true so that would mean I would need to say rez is I would just check if the absolute value of target - check if the absolute value of target - check if the absolute value of target - rez - s is better than the previous rez - s is better than the previous rez - s is better than the previous value so it's less than the absolute value for target - the previous value for target - the previous value for target - the previous value which is less then I would assign rest to be s and I was assigned value to be mid right otherwise while I need to go as we said here I need to go left and so that would mean we would do high equal to mid minus one and we will do also the same thing so we'll just take this here and put it here so do the same thing because we don't know if it's not last false or the first true and then at the end once we are done we will just return the value we got right from the two solutions from the smallest one we thought we found and that's pretty much it yeah so that's it for the solution let's float it up and see if it passes this cases okay so here is the code for a binary search solution that we went over so this is the f of X function to just compute the sum starting from the first value and then keeps going to and then replaces the values that are bigger than X and then here we have we are we have our normal binary search thing and then here is the with the function that we said is if f of X is lost none out towards the target we need to go to the right otherwise we need to go to the left and we keep updating because we don't know if the best solution is smallest is the first last force or the last true as we said in the overview and at the end we returned the best of all they would found and that's pretty much it and you can see here this is of log N such that our plugin is of log of target because that's the range you are looking in and then every time we compute the sum which is all them and so it's o of n multiplied by log of target which is still reasonable and when I'm not using any extra space just these values so that's fine so let's submit this okay so this passes all test cases yeah so that's it for this problem thanks for watching and see you next time | 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,749 | hi friends welcome back today we are going to solve fleet code problems 17 49 maximum absolute sum of and sub array it's a medium complexity problem so uh let's go through the description you are given an integer error numbers the absolute sum of a sub array nums one two nums of are right is absolute of nums one plus nums uh i plus one plus nums r minus 1 nums sri return maximum absolute sum of any possibly empty sub array nums note that absolute of x is defined as follows if x is negative integer then absolute of x is equal to minus x is non-negative integer then absolute x is non-negative integer then absolute x is non-negative integer then absolute of x is x so uh we have to find out maximum absolute sum of any sub array in the given array right so for example in this given array if you uh look at the absolute sum right so you can sum these two elements and it is 5 which is the maximum sum we can get here right absolute of 2 plus 3 which is equal to 5 so let's take this second example over here before that we just constraints is nums array length is between 1 to 10 raised to 5 and the value of every element is negative minus 10 raised to 4 to positive 10 raised to 4 right so let's take this second example over here we will discuss our approach to solve this problem so um basically this is the array which is given to us and they have asked us the absolute sum of any sub array right so absolute sum uh basically what it means is so this is our original array right 2 minus 5 1 minus 4 3 minus 2 so we have to also get a negated array right because we want to calculate the maximum absolute sum so what we will do is first we will negate all the elements of this array right like 2 becomes minus 2 minus 5 becomes 5 1 becomes minus 1 minus 4 becomes 4 3 becomes minus 3 and minus 2 becomes 2 so we have negated all the elements in this array and then we will use cadence algorithm right to find out the maximum between these two right original array and negated array and then we will get the maximum of this two right whatever maximum we can get that is the absolute maximum sum of the sub array we can find right so let's go through so the first step is we will negate the array right so we'll go through the n elements of the array we need the array right and we will store that in some other another array right and after that we will use credence algorithm so let's just uh apply the cadence algorithm on this first array so let's let me just write it here so we can go step by step so first array is 2 minus 5 1 minus 4 3 and 2 right 3 and minus 2 right so in cadence algorithm whenever the sum of the consecutive elements so far it drops below zero then we uh make that sum zero right so let's say sum is there so in the beginning sum is zero so when we are uh visiting this element 2 then sum will become 2 right so far only we have one element seen and some became 2 for that element when we are increasing this until this point right so 2 minus 5 which is minus 3 right so minus 3 means the sum is going below 0 right so we will just reassign the sum to 0 basically we don't store minus sum we just assign it to 0 so far again now the sum becomes 0 right now when we are visiting 1 so some of this one element will become 1 again right so sum became 1 after that when we visit minus 4 so sum became minus 4 plus 1 which is minus 3 right so we will reassign that sum to 0 right according to cadence algorithm when sum falls below 0 we reassign that sum to 0 so now we have seen minus four and now we are seeing three so zero plus three is the sum becomes three for this point and we will also keep maximum sum right maximum sum here so far maximum sum here is three right so we will keep updating whenever we find anything maximum right so now we find maximum 3 as of now right so we'll just put 3 in the maximum and after that when we see minus 2 the sum goes to 3 minus 2 which is 1 so sum becomes 1 and maximum sum remains 3 right so this is how we can find out the maximum consecutive sum using cadence algorithm so as you can see here this is 3 that's how we found this three right so we just went uh all the elements and we wanted to find out some maximum sum of consecutive elements right and we are in this case we want to find a find out absolute sum so we created two arrays one is our original array and one is our negated array right because we want to find out absolute sum so now we are done with the original array we found the absolute sum as three now we will go through the negated error right this negated array and we will try to find out the absolute sum for negated array so let me just write down the negated array so it is minus 2 5 minus 1 4 minus 3 2 4 minus 3 and 2 right so we will go one by one so similarly we will store the sum and max right so max i'll write you here max and here i'll write down the sum so first element our sum becomes minus 2 so minus 2 we don't store we always keep it 0 for minus so we will put 0 here right in the beginning max is 0 now we are seeing the second element 5 so sum become 5 right 0 plus 5 is 5 so sum became 5 here maximum we will update from 0 to 5 r right because 5 is bigger than 0 after that we are seeing minus 1 right so minus 1 means 5 minus 1 means sum become 4 at this point maximum we will not update because 4 is less than 5 then we are seeing 4 so 4 plus 4 is equal to 8 we will update our maximum from 5 to 8 because it is bigger than 5 right so our maximum becomes 8 now right 5 is gone it is there so now after that minus 3 came so 8 minus 3 is 5 we will not update max because 5 is less than it then 2 came so 2 plus 5 is 7 right we will not update our max will still remain 8 so at the end it is our maximum absolute sum for this error right so this one is our at eight is our sum so from these two we will pick whatever maximum we find so we find it so we will output it here right so that is how we are going to solve the problem so first step we will um going to create a negated array and then uh we will apply cadence algorithm on original array and negated variable to find out maximum sub array sum of both these arrays and then we will get the maximum from them right so that is our approach so let's just uh take a look at the solution here so ah this is our nums array so first we have created a negated array of the same length as our nums array right and then we have populated the negated array is equal to minus we will just uh put minus to every number right so we will get negated array and then we will create this find sum by cadence right so this is kedan's algorithm we will pass a array and what it does is first it initializes current sum and maximum as the first element of the array right first element of the array and then we will look uh like we will loop from first i is equal to 1 to last element of the array so whenever current sum is greater than zero right then we will increment our current sum plus the current array element right otherwise when the sum is going less than zero then we will what we will do is we are like basically initializing it to 0 and then adding current element i right so that's what it means basically so you we reset it to 0 first and then we added current element which is i th element to the current summary so that's what it is doing and whenever we are finding current sum is becoming greater than our maximum sum so far we will update our maximum sum rate so that's what we have done here right this maximum sum we keep updating right from 0 to 5 to 8 so that's what we are doing here and we are looping through i 1 2 length of array and at the end we will just return maximum sum so we are going to pass both negated array here and the nums array and whatever maximum we will find from those things using cadence algorithm we will just return as the maximum sum right maximum absolute sum of this array so this is the implementation of uh how we can solve this problem using cadence algorithm so we will take couple of examples so for example in this case if you see if we negate like for this array element right so uh you will see the maximum will be like 4 plus 6 10 right 10 will be maximum for the original array and if we negate the array right negate so negate means minus 1 then 2 then 10 then minus 4 then minus 6 then 8 and 2 right 8 and 2. so if you see this is the maximum in this one right 10 plus 2 so which is 12 right so 12 so that's why 12 is the answer for this we will uh run this in our test case so we can check there also so let's just first make sure that it is uh so this one is the this same test case that i just showed you right this case so we should get 12 here as the answer so let's run this one so as you can see we are getting 12 which is correct answer then we will just use the examples that they have given us here to make sure that those examples are passed so first is 5 and second is 8. so here first is 5 and second is 8 so we are getting correct result so we will just submit our solution here so our solution got accepted by lead code so this is the way we can solve maximum absolute sum of any sub array using tradance algorithm so the time complexity is here we are looping through n so this is order of n and for every find sum by grade and algorithm we are passing array and then this one is again order of n right here so time complexity for this solution is order of n so let me just write down here so time complexity is order of n because those are separate loops right they are not nested loops and then we have used some space for this negated error right it is same space as num's array so we can say that space complexity is order of n because we are creating another array to store n elements but we are not using any kind of uh you know like uh external data structures like set or map or anything right so this is just kind of um you can just tell that this is space complexity o n and time complexity also o n right for this algorithm if you haven't already checked my playlist on my channel for lead code and lean code solution please check it now it has over 100 solved problems asked by big tech companies like amazon apple microsoft google facebook and many others those are hand-picked problems asked those are hand-picked problems asked those are hand-picked problems asked previously by these companies and they have a variety of problems like dynamic programming linked list related interview questions graph related interview questions binary search tree related questions then you know string related interview questions two pointers questions so all those varieties is covered there in that playlist and those are explained with examples and java code so please visit that playlist and check it now also if you are preparing for telephonic java interviews then there is a playlist called as java interview it covers frequently asked telephony questions by big tech companies and how to answer those questions and also clarifies the concepts related to the interviews so please go through them if you like this video and if you find it helpful please hit subscribe and like the button your subscription to the channel is really important to us because that is the way the video can reach to more people they can also watch these videos while they are preparing for their interviews or coded interviews and they get helped by seeing those videos so please subscribe to the channel and thanks for watching the video | Maximum Absolute Sum of Any Subarray | sellers-with-no-sales | You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`.
Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`.
Note that `abs(x)` is defined as follows:
* If `x` is a negative integer, then `abs(x) = -x`.
* If `x` is a non-negative integer, then `abs(x) = x`.
**Example 1:**
**Input:** nums = \[1,-3,2,3,-4\]
**Output:** 5
**Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5.
**Example 2:**
**Input:** nums = \[2,-5,1,-4,3,-2\]
**Output:** 8
**Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104` | null | Database | Easy | 1724 |
865 | okay what's up guys John here so today let's take a look at another elite called problem here number 865 a smallest sub tree with all the deepest nodes so this is a this is another tree problem so basically you're given a binary tree and you need to find basically the lowest ancestor for all the deepest nodes right so how can we solve this problem right so first I think it's kind of obvious that we need to find the deepest node first right and once we find the deepest node we will be try to get the lowest root note for those four out deepest nodes right so to calculate the deep it to the depth of a tree we really use a recursion right basically we get the left and right and when we reach the leaf node we return zero otherwise every time when we have eleven right we get them the maximum depth for from both between the left stabs and right taps and then we in return we get the maximum and we +1 and return we get the maximum and we +1 and return we get the maximum and we +1 and we then we return back to this one right so that's how we get the for the current node right that's how we get the maximum node the maximum depth for the left and the right but now we need to add one more layer on top of that right not only we need to get the tabs for left and right we also want to get the note that the tree node of the deepest note so how can we do that right basically let's say we have a left and right so we have a left laptops and right taps here right so let's see we are at this like let's see we are Al to hear the left apps is one right the right tab is also sorry it's also one so also one and then basically our hyper functions will return the tabs of the current node plus the maximum that plus the note of the deepest leaves so far so basically if we have a like a two here right so the left and right there they are the same right if they are same then we know okay so this is the current notice it's our that is the root note we need for the current depth right and then when it comes back to five here right when it comes to the five so the left side is 1 and the right side is 2 right when it's not the same right so what do we do right if so we get the we got the root node from which other side has the deeper depth right because at this moment right on the right side the tree node is still pointing I - right and node is still pointing I - right and node is still pointing I - right and then we are even we're at five okay so we're at five we see okay the right side has tapped up to the wire Lacroix epsilon has one so the tablets of course is two in this case right - of course is two in this case right - of course is two in this case right - two plus one and but the tree node we're still using the right side and we only use the current node when the left side and right side are the same then we know okay so the current node can cover all the Leafs the deep is the leaf node okay so I think that's the and in the end when we finish all the recursion so we simply return the second element from our recursion method that will give us the at the roots note what's the lowest was the lowest root note right okay let me try to call to these things so that you guys can know bit better here so basically I'm gonna have like a helper functions right this is gonna DFS right so node right so basically if not right if note is basically if it's as a leaf node or words nuts nothing there and we simply return the zero and nine right left taps equals to what DFS left DFS no left right and then right cause with DFS no right so now we just need to compare right basically if the left remember the first argument our return is the like it's the tapped and second one is the it's the is a note so far is a current like the current result while we're at this note that the current node that is the is a low which has the lowest common ancestor of all the Leafs node right if left 0 is greater than right 0 right and then we return what we return the left 0 plus 1 that's the depth right and what end the left one right I'll see if left 0 is smaller and right 0 then we return the right side right the right 0 plus 1 and then right 1 and if they are the same right if they're same what we do we simply return any left or right it doesn't really matter I said as the depth plus the current node right because we know the current node it has the common we'll cover it's a common ancestor of both left and right who is the same length same depth right and in the end we simply return the TFS node second one right so basically we're using like we compared the left sub trees adapts and right subtrees that have depth and we just use whichever it's smaller it's we use which side it has a either bigger depth propose the depth and the common ancestor let's just run it so here it should be root here yeah cool so alright so I know this basically the idea here is that we are basically piggybacking on the template of getting the biggest steps here right because at this moment you know the zero so the zero basically this 0 will be that the pies to the biggest depth of the current sub of the current binary tree right and while we're calculating that we're using the left side and the right side and to determine if we should use the current node as our as a result or the where any of the child knows who I think that's it for this problem yeah I hope you I explained a little bit better for this problem and I know there's some other ways you can do it I think one of the other ways is it kind of is more complicated basically you find audio when other nodes has the has a biggest at the biggest length here in here now the first one is the you find all the nodes with the deepest lines deeper steps and then in the second approach in the second loops you just try to find the common ancestor of all the nodes that have the height the biggest depth yeah you can also do that I think that way is like more intuitive but I think it requires a bit more coatings and this way it's like the most efficient way but it requires you to make a little bit modifications on the existing method and you have to be aware of how can you use utilize that the tab from posts the left and right hoop yeah how can you utilize the tabs from both left and right to determine how can which know do you need to return right cool I think yeah I think that's it for this problem yeah thank you so much for watching the videos yeah see you bye | Smallest Subtree with all the Deepest Nodes | robot-room-cleaner | Given the `root` of a binary tree, the depth of each node is **the shortest distance to the root**.
Return _the smallest subtree_ such that it contains **all the deepest nodes** in the original tree.
A node is called **the deepest** if it has the largest depth possible among any node in the entire tree.
The **subtree** of a node is a tree consisting of that node, plus the set of all descendants of that node.
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\]
**Output:** \[2,7,4\]
**Explanation:** We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.
**Example 2:**
**Input:** root = \[1\]
**Output:** \[1\]
**Explanation:** The root is the deepest node in the tree.
**Example 3:**
**Input:** root = \[0,1,3,null,2\]
**Output:** \[2\]
**Explanation:** The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.
**Constraints:**
* The number of nodes in the tree will be in the range `[1, 500]`.
* `0 <= Node.val <= 500`
* The values of the nodes in the tree are **unique**.
**Note:** This question is the same as 1123: [https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/](https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/) | null | Backtracking,Interactive | Hard | 286,1931,1959,2203 |
17 | hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem number 17 letter combinations of a phone number let's read the question prompt given a string containing digits from two to nine inclusive return all possib possible letter combinations that the number could represent return the answer in any order a mapping of digit to letters just like the one on telephone buttons is given below note that one does not map to any letters so we can see that 2 is a b c 3 is d e f 4 is g h i on and on until we get to 9 which is w x y z and there's no nothing for these characters or the 1. so if we're given the example 2 3 what is our output well it's a d a e a f b d b e b f c d c e and c f let's think about how they did that well in the beginning our answer is going to be empty right we haven't taken any characters yet so you know we have this two what are the options from two well we can have a b or c so we have to take each one individually so the first order will be to take the a the second will be to just take the b because we're only allowed to take one right we can't take all three we have to choose one so we have a b and c now from here we have to go into the three what is the three it's going to be d e f so that means for the a we can have a d we can have a e or we can have a f and remember since the 3 is the last element in our input digits this is going to be a solution and this is going to be a solution cool now we're at the b what can we do from here well it's going to be the same as a we can have bd we can have b e or we can have b f cool and since again three is the last element that we have to process here right so we process the two at this level this would be like processing the two and then here we're processing the three so this is a solution then for the c we're going to do the exact same thing we can have cd ce and cf and these are our solutions as we can see these are the exact solutions we're looking for right a d a e a f b d e b f c d c e and c f so that's how we want to solve the problem and the way that we set this up is actually going to be with a backtracking solution and typically what we want to do here is you know we want to take one element explore its entire tree then pretend like we didn't take it and then move on to the next element explore its entire tree and then move on to the next element as if we didn't take it so that might be a little bit confusing if you've never seen backtracking before because it is a little bit um unintuitive how you set it up but once you see the pattern for how you actually write the code you can use the same backtracking pattern to solve you know countless problems on leak code that also use the backtracking pattern so instead of me trying to draw it out and making a mess of it let's look at the code because it's going to be a lot more intuitive to see how it is uh written out as opposed to me trying to draw it with you know my mouse here so i'll see you back in the editor okay we're now in the editor and we need to write the code the first thing that we're going to want to do is actually define a map which maps each digit to all of the possible characters possible for it so i'm just gonna copy and paste this in because i've written it before and just to save time here but you can pause the video now and just copy it for yourself or you can write it out as it's pretty intuitive so here it is basically what we're doing is we're mapping each letter each number sorry to all the letters it corresponds to so obviously 2 a b c 3 d e f and on so pause the video now if you want to copy this or you can just figure it out from the numbers here in the diagram anyway the first thing that we want to do after we've copy and paste that is basically to check if we have an empty input for our digits obviously if we're given an empty string then there's nothing we can create so we should just return the base case which is an empty list so we're going to say if not digits we're going to say we're just going to return an empty list cool now we need to define a variable to store our result so we're going to say self.res is going to be an empty list self.res is going to be an empty list self.res is going to be an empty list now what we need to do is define our function which is going to perform the backtracking because we need to store we need something to do our result right to compute the result so we're going to say def uh we'll call it backtrack and we're going to take in the digits and we're going to take in the current index and we're going to take in the current result as our input parameters so this current index will tell us where we are in the digits remember that when we drew the diagram we processed the two first so that way you know we get an index zero once we've processed it and gotten you know a b c then we can move on and do the three so that would be at index one and then we need to apply all the values from the three to our a b and d c which is how we got a d a e a f b d b e b f c d c e and c f so that will keep track of where we are and then kerres will keep track of the answer that we have so far for each iteration so what is this function going to look like well what when do we stop with the backtracking well we need to stop when the current index is actually greater than the length of our digits right because if we're trying to access something by index and we're outside of the length that it can possibly contain then we'll get an index error and our code is going to blow up so we need to make sure that if the current index is greater than or equal to the length of digits then we know that we've finished processing our input string obviously we can't have an index higher than the you know the length of digits because then we'll be accessing an index that doesn't exist at this point we know that we have parsed out everything and we've built the result as much as we can and we can add whatever the current result is to our solution here so we're going to say self.res that append and remember that self.res that append and remember that self.res that append and remember that kerres is going to be a list of strings and you know we need to return it as one string so that means that we have to join together the kures in order to uh append it to our result and at this point we can just return because we know that we have added it to our result we've processed everything that we can and now we just need to go back otherwise that means that we have to do some processing right if we're still within digits in terms of the index then we know that we still have something to process what we want to do now is we want to basically for each of the characters available to us for the digit that we're processing so say we're going to do three that means we have to process d e and f on top of our result that we've done so far so we're going to say for character in self dot letter digit mapping so basically and extract whatever the letters are for that number of digits of cur idx all right so we're going to parse out whatever the digit is from our digits here and then we're going to look that digit up in the map and get the characters and then iterate over them what we're going to do is we're going to say curse string the append the character then we're going to backtrack so self.backtrack self.backtrack self.backtrack with digits we're gonna say cur index plus one because now we need to go to the next index and we're gonna pass in the cursor oh this actually should be korres apologies kerres we're gonna say current result and then we're gonna say cursestring.pop.pop okay let's um okay so we've written the backtrack function here and now all we need to do in our main function is actually to call it so we'll say self.backtrack it so we'll say self.backtrack it so we'll say self.backtrack uh digits 0 because that's the index that we're starting with and we're obviously starting with an empty result so we use an empty list here and then we just need to return self.res just need to return self.res just need to return self.res let us submit this to double check that it's going to work and curse okay whoops should be kerres apologies and let's submit it double check that it works cool it does now let's go back to the editor to think about how this backtracking works in case it wasn't very clear for you and we'll also talk about the time and space complexity there because it is a little bit more complicated for this problem so i'll see you back in the diagram okay we're back in the editor now let's go through our code line by line and verify why this backtracking solution works so the first thing that we do is we set up this uh letter digit mapping which is pretty self-explanatory right it's each pretty self-explanatory right it's each pretty self-explanatory right it's each digit mapping to each of the characters that it's available to it on the phone number pad this is where we check the base case and we just return an empty list if it doesn't uh if we're given an empty string as the input now we set up our result so let's write that over here we'll kind of just set up our result and this we will store our results here cool so then we call the backtrack function with our digits which we know is 2 3 the current index which is going to be 0 and an empty list now let's go into the backtrack function so we call it and in the beginning right we call it and our result is currently empty so is the current index which is zero is it greater than the length of digits which is two right no it's not so that means that we haven't completed our backtracking yet so we go to this part of the solution so we're going to say 4 character in self dot letter digit mapping of digits cur index so right like if the curindex is 0 that's going to be this 2. so what are the numbers that we have to iterate or the characters we iterate over it's going to be a b and c so that means that a is going to be first so to our current result we're going to append an a right so we're going to append a to our current result so this is going to be it and we'll use string here and then what we're going to do is we're going to call backtrack with the digits and current index plus 1 and the current res which is this a so that means that we're going to go one level deeper now we come back to our backtrack function so our current index is going to be one because we were previously at index zero now we're at index one which corresponds to the three and we're gonna check okay is one greater than or equal to two right because that's length digits no it's not so that means we go here so we again need to go over the characters in the mapping for what is the digit at the first index it's going to be three so that means that we're going to be working with d e f cool so we go through all of those characters so the first one is d so that means that we append it to our current result which remember at this time is a d so we then append it so it's going to be a comma d in our result list here and then what we want to do is we want to call backtrack with the digits current x 1 which is 2 and our current result which is now a d cool so now we go into the back track and we see okay is 2 greater than or equal to the length of digits which is two yes that means that we've finished and we've gotten to the end so we need to append the you know concatenation of a and d to our result here right so we can write res here and this is going to be our um result actually yeah sorry you can't see it's actually cut off anyway uh so yeah we're gonna add that to the result so a d right and it's gonna be one string because we're concatenating uh okay cool so that's going to be there comma okay now since we did that now we return so remember we appended the d we called backtrack and now we're here so we need to pop from our solution the d so really we're going back here so now it's time to process the e so we're going to do the exact same thing so from a we're going to go to a e now and i guess i'll just skip the quotes for simplicity and we're going to backtrack again our index is now going to be two because right we returned to the a which was you know current index was um was uh one and then we add 1 to it so now we're at 2. so again similar to the d we have processed everything so that means it's time to add this to our solution so we're going to concatenate a and e and we're going to add it to our solution and then return now we go to the last character for the three which is f right so we go to af and that's it so then we call backtrack again but now we've reached the end so that means that we can concatenate these two and we say af and we um that's you know the solution and then we return right so now we can pop from our current res now we're back at the a and now we've exhausted this a right we've done this part for every single character uh in the three so now it's time to move on to the b so we go back and now we're here um you know we've popped the a now from our we've you know done the back tracking for everything in the three level so that means that we can pop the a now so our result is now back to this and then we can take the b now so we take the b and we're to go through the same process and i'll kind of you know speed through this but essentially you've seen this before right the first thing we do is we get the bd because we're going over the def again so go to bd we see that when we try to go into bd that we've already done everything we can because obviously we're at the end here so we're going to add now bd to our solution we're going to pop the d and then we're going to go back here to the b and then now we take the e so it becomes b e and then we go b e to our solution because we've processed everything we can there we pop the e so now we just have b again and we'll go to b f this time and that's all that we have uh to process there so we go bf once we do that so that's us appending to the solution and then you know we put we completed everything here so now we pop the f we're back at the b we've completed everything on the b level so that means we pop back to the empty and the last thing that we need to process on the two is going to be this um this c here so let's do that so we take the c and then again like we did with b and a we take c d see that we've processed everything so that way we add it to our solution the concatenation and then we go c e again we've done everything so c e and then we go let's see if this will fit yeah cf it's getting a little bit messy but it's fine because that's the final thing and basically that's how you solve the problem right you go into the a you explore its tree as far as possible then you go back then you go to the b so essentially this backtrack is just depth first search right we're just exploring as far as we can go into our solution here cool now what is the time and space complexity of this algorithm well if we think about it in the worst case we would be given only seven gee that's messy we would be given only sevens or nines so for example we could be given the number seven right which means that each time there are four uh things that we can choose from and since each level then kicks off another you know level of iterations equal to however many is on the next level so like seven um would kick off you know four levels of seven on the next level um this is going to be an exponential solution because every time we go into one level uh we're adding now however many are on that next level um so essentially this is going to be a four to the n solution uh where n is the length of our string here in the worst case right and that's going to be just the dfs part and then we also need to multiply this by n because if you recall here we have this joining right so joining our result is going to take end time to basically build the result so our final runtime complexity is going to be you know 4 to the n times n so this solution you know it isn't very fast but you know this is the best that we can do uh we have to explore every single you know path in this tree to build our final solution we have to leach you know the leaves here so we have to go through every single path and we can't skip any we can't prune any um you know doing it like this we'll have no duplicate paths but even though we have no duplicates it's still going to be 4 to the n times n on the time and then space complexity wise it's actually just going to be um you know big o of n because you know that's what we need to actually store the result if we want to count the you know stack space required um to go down to you know the furthest leaf then it would also be you know four to the n uh times n i think actually plus n i believe um because we need to account for the stack space but if you don't want to count the stack space required to go through the entire tree then it would just be big o of n so that's something you can bring up to your interviewer you can say well you know to store the result we would need big o of n but if we want to count the recursive stack space because every time we call this function recursively obviously you are taking up stack frames so that would be you know four to the n because you're opening up potentially four uh new paths from every one um that you call into in the case that it's a seven or a nine in the other cases it's going to be three but obviously we work with worst time complexity here so hopefully that makes sense this problem is a bit weird if you've never seen backtracking before it can take uh some time to wrap your head around it but essentially if you draw this diagram like we have here uh where you know we build out each level you know one by one and you can see okay we go to the a then we explore the next level and then if we had a num another number so if it was like two three four then you know after we built a d a e a f then we would do the four so it'd be like a adg a d e h a d i and on for a e a f and you could keep going you know up to however many letters you wanted you would just keep building a bigger and bigger solution but essentially that's the um you know the path that you want to take so i'm going to cut that video there hopefully you've you know been able to follow my solution hopefully you enjoyed this video if you did please leave a like comment subscribe and make sure to check out my other videos if you're preparing for on-site interviews happy coding | Letter Combinations of a Phone Number | letter-combinations-of-a-phone-number | Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** digits = "23 "
**Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\]
**Example 2:**
**Input:** digits = " "
**Output:** \[\]
**Example 3:**
**Input:** digits = "2 "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `0 <= digits.length <= 4`
* `digits[i]` is a digit in the range `['2', '9']`. | null | Hash Table,String,Backtracking | Medium | 22,39,401 |
1,675 | hello guys welcome to the codeplay today we will be discussing lead code 1675 minimize deviation in array so in this problem we have given an array of n positive integers you can perform two types of operations on any element of the array of any number of times if the element is even divided by two or else if the element is odd multiply it by two so we have to return minimum deviation the array can have after performing some number of operations so here deviation of the array is maximum difference between any two elements in the array here we can see in example given array is 1 2 3 4 and you can transform the array to 1 2 3 and 2 then to 2 3 and 2 then the deviation will be 3 minus 2 that means minimizing minimum deviation as you can see example 2 and 3 as well so constraints are n should be maximum 10 raise to 5 and numbers number of i should be 10 raise to 9 that means our complexity will be order of n between order of n to order of n square but it does not exceed order of n square so let's see an example so it will be more clear to you suppose we have given an array 2 10 8 and 9 and here you can find minimum deviation is maximum elements minus minimum element that means 8 so this is not minimum so you can find two conditions in question that if element is even you can divide it by two if element is odd you can multiply it by two so these operations you can perform number of times as you wish so i am doing that 10 divided by 2 10 is even so i divide by 2 so 10 divided by 2 that means 5 so new array will become 2 5 8 and 9 so in this array my deviation is maximum element minus minimum element that means 7 so this is nothing but our answer now you can not uh you can do furthermore operations and you will check answer by yourself this is minimum answer 7. let's move forward to the solution but before moving to solution there is prerequisite that you should know what is priority queue and what is that using priority say priority queue or using order set we will be able to solve this question so if you know that means good if you don't know then try to read articles or something else so let's move forward the solution using priority queue let's start with the solution i have divided solution into three parts first step is making a priority queue second step is even number decreasing step and third step is if the maximum element is odd or even let's start with the first step making a priority queue making a priority q step is pretty simple if our element is odd then i will multiply it to 2 i am using this property so priority q insertion step i will go through loop so first is 2 is even there is no need to do anything with 2 so simply i will insert 2 into priority queue after there is a 10 so 10 is a even number so there is no need to do anything so i will insert 10 after there is 8 so 8 is also even there is no need to do anything with 8 so i also insert 8 when we come at the 9 so 9 is odd number so i will use that property i will multiply by 2 that means 9 into 2 so it will become 18 so i will insert it to the priority queue so it is maximum since it is maximum so 18 is inserting here and 10 will insert here so now my priority queue is complete so let's move forward to the second step of our solution in the second step i am going to use first property for question that even number if it is even number then i can divide it to 2 so let's start with the even number decreasing step doing that i will also update my minimum variable maximum variable and difference variable so this is nothing but our start our answer so let's start with the priority number division step since first element of the priority queue is even number so i can divide it to 2 so let's divide 18 by 2 so it will become 9 and 9 is not a maximum element of priority queue so it will be it will replace by something else so first element of the priority q will become 10 second element is 9 is nothing but 18 divided by 2 and third and for as it is so now my priority q will become something looks like this so since priority queue have a maximum element 10 and 10 is even number so i can further divide 10 into 2 10 divided by 2 is nothing but 5 so 5 is not maximum element in our priority q so pi will replace it something uh in priority queue and our maximum element is 9 so 9 will store it top element after that 8 after 5 is nothing but 10 divided by 2 and 2. so now my priority queue will look something like this since our maximum element of the priority queue is 9 and it is odd number so i will move forward to the third solution so i will going to find what is the difference of the priority q so here difference is minimum element is 2 maximum element is 9 and difference is nothing but 7 so this is nothing but our storing our answer now i think question and their approach is clear to you guys so let's do some coding so initially i have declared minimum variable difference variable and priority queue from stl library so let's take from one and one element from the mask and check if it takes x for and i will simply multiply by two and also maintain minimum variables so you know equals to minimum okay here i am and also pick you dot push it so now my first step is clear let's move on with the second step while there was even elements at the priority queue top of the passage simple i'll try to take your top element is so also i will maintain my minimum variable mixing level so difference is nothing but minimum of difference from the maximum minus okay also maintain minimum variable minimum equals to minimum since it is maximum is even so i will divide it to by two after then i will check minimum variable is my minimum comma maximum divided by two divided by 2 is nothing but i will using second property so e1 value property okay and simply i will push that maxi my by two into or priority q sub tricky dot push let's see okay now maximum element is either or either even if it is even then i will come in the loop if it is odd i'll come out from the loop so i have also written a minimum of difference in trans minimum of difference comma since it is odd so my minimum variable it is not update so simply i will whatever pick uh whatever maximum element of the priority q is simple minus minimum it is also our answer from both what whatever minimum is there it will return our answer so let's try to run our code i hope it's correct yeah so let's submit to solution and here we go guys thank you guys for watching see you soon | Minimize Deviation in Array | magnetic-force-between-two-balls | You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109` | If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible. | Array,Binary Search,Sorting | Medium | 2188 |
1,062 | all right guys let's do this uh given a string is find out the length of the longest repeating substring or sub strings there could be multiple okay yeah but in any case the length would be highest return zero also we have to just return the length and not the substring so return 0 if no repeating substring exists okay so it has to be repeating that is the first criteria and then you have to see which one is the longest in which so abcd nothing is repeating a b at least a is repeating another time right a b uh is also repeating again a b then bb doesn't repeat ba also repeats two um yeah it's a is repeating then you check a b is repeating abc is repeating as long as you can find one you can go ahead to the next window right that is the good thing the one that will always be there yeah abc there we see it repeating not here so if bc has come here then we check again here we see here if we say repeat oh bca no caav no we go through windows of a particular thing and we can't find any repeating one then we can just exit that yeah whatever was the max for the max so this is one way in this case uh string length is 1500 it's possible that uh we get till 750 so we do 750 tries which is like kind of like n square only in a way what else can we do can we know beforehand if a particular substring exists later on no okay then i think we'll be going till not n by two actually not n by two it will be n only for and range one two land office right we choose it we try to check in windows or in characters we'll have a dictionary again so what map and or we can even have a saved boundary and now what we will try to do is we will go through words in that range so far i in range we'll start from zero right so uh it has to be more like we can first put in dot add uh n characters right so it's like s of zero till n so if it was one then we are adding only zeroth character which is one character which is fine and then we're gonna run uh this from first character or not in that case like if youth got added then we're gonna run it from n onwards uh to length of s minus n or minus n plus minus n minus one minus n would be minus one why are we going to there only this is the starting point yeah this would be the starting point then the zeroth thing now then this should go from one number yep i'm gonna pick up s of i to i plus n correct and i'm gonna check if current word is this if current in word map uh we're gonna set max found to zero right now if current is in word map we can set max 1 to n right because we found something or repeating often and then we can kind of break this loop and when whenever we break this loop it's going to move on to the next end if we are not able to yeah for that given window if max found not equal to n right now or if x bond is less than n then we can kind of uh break from here also and return max form will just work this seems to uh we have not done try run we have not done test cases we've not done complexity analysis so we'll do all of that let's just check with certain uh certain inputs so before we do that here also it's working maybe it was an easy question so one good thing that i do is i hide the difficulty of the question you can't see the difficulty because that makes it more interview like i have no clue and i will give whatever would be my best try because as soon as you see something easy right so see for a we got uh the wrong output so let's try to debug this case what should happen so we'll go inside maximum with zero and would go from one to in the face uh and then it's gonna check what map is going to become empty set worldwide it's gonna add s of one which would just be a right and uh hey we are not adding things to word map only that's gonna cause the problem now how did it even work like everything everywhere it was starting with those characters that's why it worked uh so we're gonna add to word map the current thing but this doesn't make sense you have to add it afterwards yeah now let's see what's happening so you pick up an a then it goes from i one to whatever one to two it will check it'll come up as a only it'll check it's found max one will become one so it's gonna break this loop uh one is less than zero no uh so it's not breaking this it becomes two then the vessel is by the way five uh so now it gets to two and it's going to pick up the first two which is double a uh for double d also it checks it's able to find for triple now for three times when it gets to n equals to three it gives the first three a's and then it's starting from i equal to one and we are doing one two one plus three which is four so this guys right that also exists so it will set it to three then we're gonna go ahead four so zero two zero one two three will get set now when you go to one two one plus and n is four five which is so this should give four times a only right oh this is the problem i think tenth of x is five minus four becomes one plus one now let me do a case where the repeating string is not at the starting so maybe this is db and then you have b a b let's see if we get two now we are getting two how about this case say d this would ddb and then you have say caav and this is also c a b so now it's bcaa so it should be four hmm okay this is working so from a complexity perspective what's happening here is you're doing n and you're doing again kind of like n only because then this and can take any value so it's n square solution right now uh maybe there would have been a better way this is like is this kind of a brute force way not sure anyway let's try to submit maybe i'll give time limit exceeded no this is actually one of the fastest solution wow okay did not expect that at all it's also fast from this aspect okay cool i guess we have solved it in nicely bye | Longest Repeating Substring | partition-array-into-three-parts-with-equal-sum | Given a string `s`, return _the length of the longest repeating substrings_. If no repeating substring exists, return `0`.
**Example 1:**
**Input:** s = "abcd "
**Output:** 0
**Explanation:** There is no repeating substring.
**Example 2:**
**Input:** s = "abbaba "
**Output:** 2
**Explanation:** The longest repeating substrings are "ab " and "ba ", each of which occurs twice.
**Example 3:**
**Input:** s = "aabcaabdaab "
**Output:** 3
**Explanation:** The longest repeating substring is "aab ", which occurs `3` times.
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters. | If we have three parts with the same sum, what is the sum of each?
If you can find the first part, can you find the second part? | Array,Greedy | Easy | 2102 |
136 | what's up guys Xavier Ellen here today I'm going over a single number it's an easy solution on leak code please subscribe to my channel if you haven't already and hit that like button it helps their YouTube algorithm so my channel can grow so yeah today I was learning about house or not learning reviewing hashmaps and I decided to work on some hashmap problems so I'll be going over some of those so this one reads given a non-empty array of reads given a non-empty array of reads given a non-empty array of integers every element appears twice except for one find that single one and their note is so this is like their challenge you should have a linear runtime complexity could you implement it without using extra memory so when I saw that I was like obviously it's possible so we should definitely do it that way it's the most impressive way by administer you guys two solutions one is hash map which obviously it's not going to be it's not it's going to use extra memory but I'm going to show you guys the other way which is doesn't use extra memory which is look has to do with electrical engineering a little it's very low-level stuff but both the use of very low-level stuff but both the use of very low-level stuff but both the use of linear runtime so this is very easy X description I don't have to explain it the answer is four because it just appears once one because it appears once so let's go over the hashmap solution first we have a hash map so remember hashmaps have a key and then a value and I'm just gonna name it half map new hash map and we're just going to loop through nomes and we're gonna store the values in the map so mapped out put I so this is the key so for that key we're going to use the map get for default I had to refresh my memory on this function I had to look it up again kind of route how it worked so the way it works is you have if so it's telling the hashmap to look up this value i so i in this case in the first case there would be two the first time it's not going to have it so it's going to say put the default value there well we're gonna put a zero but we're gonna put plus one at the end because in the second case we are gonna have a two and the value is going to be one so it's going to say grab that value and put it there and return that value but we're gonna add one to it this time so we're basically updating our map counting that's how we count how many are in the array basically and so that's that for them then we have a second for you so if math okay so we just need to get i so we want to grab i we're gonna if the value at I equals one so that's basically saying there's only one value there then we return I so hopefully that makes sense let me see if I can explain it better it's saying get the key I and if the value which is this integer which is what we're putting here is one return it so that it means that's the one that is there's only one of that value otherwise we're going to return 0 so let's just run that perfect it's not very fast so I'm gonna show you guys the other way now which is more impressive this has to do with electrical engineering if you I have learned about electrical engineering that all its bit manipulation so let me zoom in again okay so I recorded my solution and explanation for the XOR and realize I made a few mistakes I just feel like I didn't explain it well so I'm recording so the explore solution is it's a electrical engineering topic it has to do with manipulation so this is the for like logic boards this is the logic symbol for it if I don't know if you guys are familiar with that I learned in some electrical engineering classes also it is this symbol 2 plus so where is the tab so I'm gonna show you guys on my iPad real quick so this is actually supposed to be a plus I drew an X so this is this symbol so if we do 1 exclusive or as soon as the board means exactly what it sounds like it means exclusively or so 1 or 0 is gonna be one because it's exclusively or 1 if you did one or 0 it would still be just 1 so it's a little bit different than its movable or just regular or if you do one exclusive or one it's 0 but if it was just or it would be 1 because it can be both or either the only way or is false if it is 0 or 0 which is 0 but let's just stick to exclusive board that's like a whole nother topic so when you get to bigger numbers like 4 & 2 you get to bigger numbers like 4 & 2 you get to bigger numbers like 4 & 2 you have to convert them to binary so let's convert 4 to binary it's 1 0 hopefully you guys know binary 1 0 2 is 0 1 0 make sure you put the leading 0 that's where it's easy to make mistakes so let's go through this if you do exclusive or there's only one in the first place so we put a 1 there the second one is their school savour as well because there's a zero to one but in the third one they're both zeros so we're gonna put the zero because they're the same so we get 4 plus 2 is 6 so 4 exclusive or 2 is 6 so I'm gonna cut it out real quick so then I equals we're gonna set it equal to 0 so and then we're just going to loop through nums and we're gonna do the exclusive war all the way to so I equals so the symbol for exclusive or is the caret symbol so I choose more and then we just need to return I so let me explain why this works because it might not make that first basically what's happening is let me write out my test case that I created for this some problem oh they erased it ok anyways if we do let me just write a new one to cheese 2 3 4 so I'm gonna write that out on my iPad 2 3 4 2 1 so basically how it's gonna work is since we're doing an exclusive or these are all the numbers that are the same are going to cancel out regardless if we match them up at first so let me show you real quick if we do 2 exclusive or 3 so we have 1 0 & we do 2 exclusive or 3 so we have 1 0 & we do 2 exclusive or 3 so we have 1 0 & 1 the exclusive or for this is 1/3 no 1 the exclusive or for this is 1/3 no 1 the exclusive or for this is 1/3 no it's 0 1 which is 1 so we have one remaining basically we go to the next one so we have 3 exclusive or actually no we have one because we have two keep the one that's left over so one exclusive or four it's basically gonna cancel out all the same numbers because you're breaking the numbers down into one the single ones so we're gonna cancel out all those ones and whatever is left is gonna be our answer so because we're breaking them all down into binary so one four is just one zero this is just one let's add our leading zeros exclusive four so we have one and zero and then one so that's five so now we have five exclusive or three so let's draw one zero one exclusive or zero one that gets us one in the first place and then one as well and then zero so we get six and then we're back to four so six exclusive or four so we have one zero and exclusive war one zero so that kids 0 1 and 0 which is 2 and then it's toots - no way there it's two it's toots - no way there it's two it's toots - no way there it's two exclusive Lord - obviously it was just exclusive Lord - obviously it was just exclusive Lord - obviously it was just like can't five its exclusive or we're gonna be returned to zero and that leaves us with zero exclusive or one which is just gonna be one so we get the right answer back so that's why that works you got to think I was like on a bitwise level we're breaking it down into just single ones so that's why that works it helps to take and collect your engineering classes but you don't have to obviously so this one works a lot faster if I could zoom out yeah it gives us a hundred percent so that's the explanation for that hopefully that makes sense first time I've tried recording and then explain it very well hopefully that time that worked a lot better thanks for watching | 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 |
237 | Jhal Soft Udayveer Looking at This Problem and Digit No Dinner Least Shows the President She is the Function to Delete a Node in Nursing Play List I Will Not Give You Access to Be Held at Least You Will Gain Access to Not Be Deleted and Avoid the Knot Withdraw 98100 and consider only 100 internal you do to the like this student to and unreal ok so in this cream just want to delete the second and were giving access to the head and shoulders and not show in this whole world will just update point of node Want To Delete Notice Subscribe Now To Receive New Updates Notification More List Song Start Doing So Will Love You To The Language From 9 to the Video then subscribe to the Page Qualities Of Singh List So Without Point Drop Back To The Previous Not So S To What We can do it is the portion adhesive person a project which can be used to reduce node do it is the way will update back to the number four will use this point now school this point end replaced with a not one but will need a to end Three And Don't See The Original 1234 Angry Per Give Access To The Second In The Morning Modified Acid Not Doing Anything Liquid Soap Review Back To The Best And Liquid Egg Fried Idli The Code Simple See Soap Possible For The Nodule Should No Problem Luttu Not Give Work Not Suggested Yes 11 Chapter End Which Can Submit A Solution Jhal Hai Ya So It's Butter City 4% Solid Is Hai Ya So It's Butter City 4% Solid Is Hai Ya So It's Butter City 4% Solid Is Appointment Time Algorithm No Space Required Airtel Tower 16 Ignore Extra Specific Half Thank You | Delete Node in a Linked List | delete-node-in-a-linked-list | There is a singly-linked list `head` and we want to delete a node `node` in it.
You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`.
All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list.
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
* The value of the given node should not exist in the linked list.
* The number of nodes in the linked list should decrease by one.
* All the values before `node` should be in the same order.
* All the values after `node` should be in the same order.
**Custom testing:**
* For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list.
* We will build the linked list and pass the node to your function.
* The output will be the entire list after calling your function.
**Example 1:**
**Input:** head = \[4,5,1,9\], node = 5
**Output:** \[4,1,9\]
**Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
**Example 2:**
**Input:** head = \[4,5,1,9\], node = 1
**Output:** \[4,5,9\]
**Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
**Constraints:**
* The number of the nodes in the given list is in the range `[2, 1000]`.
* `-1000 <= Node.val <= 1000`
* The value of each node in the list is **unique**.
* The `node` to be deleted is **in the list** and is **not a tail** node. | null | Linked List | Easy | 203 |
61 | hi my name is Angy and welcome back today we'll see how to rotate link list for example if the link list is 1 2 3 4 and five and our K is equals to two we need to rotate twice in first rotation five will come in the starting and our link list would be 5 1 2 3 and four five have come in the starting in the second rotation four will come in the starting so our link list would be 4 51 2 and three that will be our output so our goal is to return 4 five 1 2 and 3 similarly in the second example when the link list is 0 1 and 2 K is equals to 4 in the first rotation two will come in the starting so linkless would be 2 0 and 1 in rotation two one will come in the starting so it will be 1 2 and zero in rot rotation three 0 will come in the starting 0 1 and two and finally in the fourth rotation two will come in the starting that will be our goal so it would be 2 0 and 1 let's move on to steps for linkless rotation the first point is for handling the base cases so if head is equals to null meaning there is no element in the link list or k is equals to zero meaning there is no need of rotation we can simply return the original head okay first point is clear second Point says Traverse the entire list to find its length also make note of last note so therefore we have length of linkless also we have reference of last note as per the second Point okay third Point says recalculate the value of K which is equals to K modulus length but why we will understand from this previous example here you see the link list is 0 1 and 2 value of K is equal to 4 length is equals to 3 if we say k is equal to K modus length which is 4 modus 3 = to one therefore we only need to 3 = to one therefore we only need to 3 = to one therefore we only need to rotate once if we rotate once two will come in the starting and it will be 2 0 and 1 therefore this is our answer if you see what we got at the rotation 4 is equals to if we rotate only once therefore it is important to recalculate the value of K okay moving on if K is equals to Z again return original head okay fourth third point is also clear in the fourth point we need to iterate the length minus K minus one time to find New Tail to understand this point we will look at the example number one so if you see this example here the tail is equals to five why because Five Dot next is equals to n this is our last node but what we want that three should be our tail node so we need to find New Tail which is over here so what we'll do we'll iterate the length minus K - one we'll iterate the length minus K - one we'll iterate the length minus K - one time so here the length is equals to 5 - 2 - so here the length is equals to 5 - 2 - so here the length is equals to 5 - 2 - 1 which is = 2 let's say initially new 1 which is = 2 let's say initially new 1 which is = 2 let's say initially new tail is pointing towards the head which is one and we need to iterate till Point 3 Let's understand how initially I is equals to zero okay it will go inside the loop and New Tail I will write NT for it new tail will move one step ahead now it is pointing towards two from one it has jumped to note 2 now I is equals to 1 is less than two okay it will go inside the loop and New Tail will move one step ahead which is three in this case and then I value will increase to two is not less than two and then it will come out of the loop so we are successful in finding the new tail which is three over here so what we got the new tail is equals to note three very well let's look at the other point in the fifth point we need to set new head to New Tail do next so if you see over here our new tail is three so new tail dot next will be equals to 4 which will be our new head in the output here the head was one but what we need four as the new head so we got our new head which is four over here so till now we have got our new tail also we have got our new head which is four in this case let's look at the other point in the other point we need to disconnect the rotated part by setting new tail do next is equals to n very well that is what we wanted new tail. next is equals to null now we can say New Tail do next equals to null why because we have already stored new tail. next which is our new head in another variable okay in so in the last step we need to connect dots we need to connect original tail to original head so if you remember in point number two we have stored reference of last node now we will utilize that reference so if you see here we have got our new tail and we have set new tail. next is equals to To None also we have got our new head so new head is four and new tail is equals to three so we have one two and three as one part and head is pointing towards the node one and new head contains reference of node four and five so what we need to do we need to say last node do next so last node do next equals to head so what will happen four five and five will now contain reference of head note which is 1 2 and 3 and simply we can return our new head so this will achieve our goal of rotating the link list by K time so this is our goal if you see here it will be 4 5 1 2 and 3 it is 4 1 second it is 4 5 1 2 and 3 so I hope all the points are clear to you now we'll be writing pseudo code by utilizing these points so pseudo code would be very easy for us first we need to check the base condition if head is equals to null or k is equals to zero return head second point is calculating the length of linkless also keeping a reference of tail node so what we'll do int length is equals to one tail is equals to head because we know that head is not equals to we have already checked over here we'll keep on iterating till tail do next is not equals to null tail will become tail do NEX and length plus I hope the second point is also clear the only point which we needs to remember that we need to find the length also keep reference of last node if you want to twist the code that is all up to you third point is adjusting the rotation count which is K modulus length uh which we have seen in the example if K is equals to zero we can simply return the head we need to find new head which we can find by iterating from I equal to0 till length minus K minus 1 Point okay then we need to connect the dots the new head will be new tail do next will equals to null remember 3 do next is equals to null and tail do next which is our original tailex is equals to head and simply we can return the head I hope the pseudo code is clear now let's move on to lead code so this is problem number 6 one rotate list we'll be writing code step by step first step is checking the base condition so if head is equals to null or k is equals to Z I'm sorry or k is equals to zero what we need to do we need to return head okay second step is calculating the length of Link list also keeping reference of the last node so what we say list note tail is equals to head in length is equals to 1 while tail do next is not equals to n we'll keep on iterating tail will become tail dot next and length plus therefore we have reference of last note also we have calculated length now what we need to do we need to recalculate value of K so K is equals to K modulus length right if K is equals to Zer again check if there is no need of rotation we can simply return head okay now we need to find New Tail so we need to iterate let's say new list node new tail is equals to head for in i = to0 i less than length - K -1 for in i = to0 i less than length - K -1 for in i = to0 i less than length - K -1 and I ++ our new tail would Beals to New Tail ++ our new tail would Beals to New Tail ++ our new tail would Beals to New Tail dot next okay we have got the new Tail as well now what we need to do we need to find the new head so our new head would be equals to New Tail dot next the last point we need to connect the dots so what we need to do the new tail dot next equals to null and our original tail node which is in the tail variable tail dot next is equals to head and we can simply return new underscore head okay let's try to run the program accepted all the test cases are accepted let's try to submit the program so there you go all the test cases are accepted successfully now it's time to have a cup of coffee and W followup question the question here is you need to remove the nth node from the end of the link list so here the link list is 1 2 3 4 and five you need to remove the second node from the end so the first note from the end is five the second node from the end is four so you need to remove this node which is four highlighted in red color and return the modified head so the link list would be 1 2 3 and five I hope the question is clear try to solve this question by yourself and if you have any issues we will solve this question in follow P you I hope you have enjoyed this video very much notes are available in the description below please do like share and subscribe we'll meet in another video till then bye-bye another video till then bye-bye another video till then bye-bye take care | Rotate List | rotate-list | Given the `head` of a linked list, rotate the list to the right by `k` places.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[4,5,1,2,3\]
**Example 2:**
**Input:** head = \[0,1,2\], k = 4
**Output:** \[2,0,1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 500]`.
* `-100 <= Node.val <= 100`
* `0 <= k <= 2 * 109` | null | Linked List,Two Pointers | Medium | 189,725 |
1,627 | hello friends and welcome to my channel let's have a look at problem 1627 together graph connectivity with threshold in this video we are going to share a solution based on this joint set data structure also known as unit fund this problem is marked hard in leader code however if we carefully analyze the statement of the logic in the problem we can come up with a very short solution so this problem asks us to return an array called answer where the length of answer equals to that of the queries and i is true if for the ice query there is a path connecting the two nodes in that query so the condition for two cities to be directly connected if is that there is a common divisor for x and y that is strictly larger than some given threshold so this condition actually is equivalent to the following statement so x and y are directly connected if and only if their greatest common divisor is larger than the threshold value so this is the main statement or logic in this problem so here are three examples given we are not going to go over the three examples now so after we analyze the problem you are encouraged to work through all the examples so now let's look at the constraint for this problem the first constraint is about the number of cities which can be up to an order 10 to the power 4 so 10 to the power of 4 is a decent large number so when we devise an solution we need to take temp complexity into consideration the second question is about the threshold which is less or equal than in as it should be so the final two constraint is about the queries so in each query the two cities are different so this is more or less a consistent consistency assumption with that said let's look at the method so as we mentioned we're going to use give a solution based on this joint set data structure so the idea is actually very routine we are going to use this joint set data structure to build clusters and within a cluster two nodes are connected so this idea is listed here however a question arises so how to effectively do unit operations in this problem we cannot do it in a purely brute force way so let's recall two cities x and y can be connected if and only if their greatest common divisor is strictly larger than the given threshold so we are going to do the unit using the following nested for loops so due to the requirement from this problem we're going to look at a threshold value that is larger than the given threshold so we are going to iterate for a city x let's see in the range threshold plus 1 upwards and then when we look at another city we're going to just look at the multiples of city x so this way we're iterating like in range 2 times x up to n with a step x so here we start from 2 times x means that we do not need to check y equals x so this way actually it can accelerate the connectivity procedure or merge procedure effectively so this is the reason because we are looking at multiples of cty multiple multiples of ctx at y equals qx then this way the greatest common divisor equals x which is larger than the threshold so with the key idea explained let's specify our plan so first i'm going to implement the union fund inside the solution function the reason we choose this um kind of implementation is that the number of cities is given a priority so in general we can actually implement the universe as a separate class also that is the solution class so secondly we're going to do a course temp complexity analysis after we solving the problem so here are some initializations so in order to implement the disjoint set data structure they initialize two dictionaries one is parents one is rex the parents will start the node parent relationships and the reacts will start the node and direct relationships or the information so this is the initialization at the very beginning each node or each city is a single node cluster so its parents is itself and its rank is one so next we are going to define the send function so for this the fan function accept one argument this i is the city or the node so like 1 2 up to n in this problem setting so this is a very routine to implement but i'll choose to implement this uh past compression so let's introduce a temporary variable called result and its um state is i uh we're going to return the final stage of the result so next basically is a well loop so result if the result does not equal to the parents of the results then we're going to update the results to be its parents then after we exit this well loop we're going to return this result so that's the standard of vanilla fan so here we're going to use path compression to accelerate the procedure of solution so we're going to introduce a path which is a set then we're going to add all the intermediate nodes to the path result and pass and result so this way after we exit this while loop then we have a stage that is result equals its parents then we're going to redirect all the intermediate node to this result so basically for loop for node impulse then we're going to set the appearance to be the result so next time if we want to find the roots of a given node it's much faster so this is the path by puff compression the fans back um with puff compression so next let's look at the union um function it will accept the two um arguments two cities and then first i'm going to check if i1 and a2 are in the sim cluster if so we do nothing otherwise we do the merge or union so let's see um r1 let's call this root r1 r2 equals fan i1 sun i2 so we're going to check if r1 does not equal equals to r2 if they're not equal then we're going to track their rank information and then do the merge so if rex r1 is greater or equal to that of rex r2 then we're going to set the parents of r2 and to be r1 and then we're going to increment the rank of r1 by that of r2 this is one case and in the other case we essentially do the same thing but we reverse the direction let's copy these two lines and then those modifications we're going to set the parents of r1 equals that equals r2 and then we're going to increment the rank of r2 by that of r1 so that's the full implementation for the fan and union methods so now we are ready to look at the problem logic in other words we are going to do the units for cities so this is the real work for this problem as we mentioned we're going to iterate for city one let's see x in range so we're going to threshold plus one so this makes sure the common factor will greater than threshold so up to n and then um that's it so for y in range so we're going to start from two times x then ending at n and with a step x then we're going to union these two cities so union x y so that's all we need to do to make the graph finally we're going to prepare the return for this problem what we want to return is that for the two nodes or the two cities in each of the queries we're going to check if they're in they are connected by a post in other words if they are in the same cluster so this is actually very straightforward so we're going to check if they have the same representative or delicate delegate for x y inquiries so that's it for this uh solution uh i guess let's first do a special case check oh yeah it passes a special case now let's do a generic kiss check oh yeah it passes the generic case i guess for this problem so that's the structure so we first implemented the sand and the union help function or unified data structures within the solution function then we make the connectivity of the cities and finally we check if two cities in each of the query are in the same cluster in others if they are connected so this is the first part of our plan to set the second part of our plan is a temp complexity analysis so we're going to do a very rough time complexity analysis so notice that in this problem the main work is in part two the two uh the two for loop so each um and so each of the instance we're going to do a unit operation right so now let's look at the temp complexity analysis so uh first i'm trying to count how many units we are doing so in other words car is corresponding to the first atom here so the time on the nested for loop so we're going to use s to denote the threshold and the number of total cities is m so in the inner loop we are actually it with the step x so basically we are doing n over x steps and in the out for loop we are going to check the threshold value from s plus 1 to m so this summation is the number of unit operations we actually do in the process then if we put the n in the denominator outside the summation symbol we're going to have n times this summation over one over x then we're going to use the approximation we're going to use this integral to approximate this summation so in other words this is the integral from s plus 1 to n over the integrand 1 over x so the added derivative of vendor x is nothing but logarithm so then we can get the number of unit operations we are doing is actually n times logarithm m minus logarithm s plus web so notice that here the logarithm is natural logarithm but this is okay because we can count temp complexity up to a constant or we can see we are using big o notation so this is part one so now let's look at part two then we're going to count the whole time complexity so we're going to do a analysis that is not very rigorous or not very precise we're going to count the average time so let's amortize temp for unit to be rn so here this function alpha n is a slow growing function so it has a name it's the inverse argument function so roughly if this is a temp complexity for each of the unit operation and then the total temp we're using is n logarithm n minus logarithm s plus 1 times this r m up to a constant so that's the full temp complexity for this problem it's very rough but if you are interested in knowing the details so you can check the wikipedia item for this joint set data structure i guess that's about it for this problem thank you very much | Graph Connectivity With Threshold | last-moment-before-all-ants-fall-out-of-a-plank | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true:
* `x % z == 0`,
* `y % z == 0`, and
* `z > threshold`.
Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them).
Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ `ith` _query, there is a path between_ `ai` _and_ `bi`_, or_ `answer[i]` _is_ `false` _if there is no path._
**Example 1:**
**Input:** n = 6, threshold = 2, queries = \[\[1,4\],\[2,5\],\[3,6\]\]
**Output:** \[false,false,true\]
**Explanation:** The divisors for each number:
1: 1
2: 1, 2
3: 1, 3
4: 1, 2, 4
5: 1, 5
6: 1, 2, 3, 6
Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the
only ones directly connected. The result of each query:
\[1,4\] 1 is not connected to 4
\[2,5\] 2 is not connected to 5
\[3,6\] 3 is connected to 6 through path 3--6
**Example 2:**
**Input:** n = 6, threshold = 0, queries = \[\[4,5\],\[3,4\],\[3,2\],\[2,6\],\[1,3\]\]
**Output:** \[true,true,true,true,true\]
**Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0,
all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.
**Example 3:**
**Input:** n = 5, threshold = 1, queries = \[\[4,5\],\[4,5\],\[3,2\],\[2,3\],\[3,4\]\]
**Output:** \[false,false,false,false,false\]
**Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.
Please notice that there can be multiple queries for the same pair of nodes \[x, y\], and that the query \[x, y\] is equivalent to the query \[y, x\].
**Constraints:**
* `2 <= n <= 104`
* `0 <= threshold <= n`
* `1 <= queries.length <= 105`
* `queries[i].length == 2`
* `1 <= ai, bi <= cities`
* `ai != bi` | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. | Array,Brainteaser,Simulation | Medium | 2317 |
64 | Hello hello friends in this session where to introduce another light to problem minimum 5 some divine famous interview mode to turn off day I gave the company poison five numbers only all you need to two apk file path from top to bottom united Egg Identification Subscribe Possible Only Who Died At Any Point In Liquid Right Down Keep Subscribe To Minimum Old For Example Deposit Angry Edifice Time Stand Don't Forget Subscribe And Very First Approach Them But Didn't Want To Take Much For Her In Her And Only Right Directions at every step at every path will wash to-do list at minimum wash to-do list at minimum Only Move Specific Logic Minimum Nine But Difficult Minimum Will Discuss What Will They Will Take Another Same To You Om That Bloody Understand Salary First Step Will Calculate Curative We First To Prove This Arundhati Fakir Will Copy Person Not Only 12345 Withdraw Its Natives Who Will Calculate The First Like This From This Is The Only One To Do Places Which Can Only For Us That South Relative Sham S For Plus To Me 6 Till Now They Have Only One Direction Right Down But Researchers Say More Than 150 Se Minimum Set Top And Spread With Obscure Subscribe To I Will Move Their Rights As With The Top And Curative Sham Here Five Plus One Witch Sex With Flute Celebrity Including 7 Plus One Peeth See Small Village Itself With Knowing Feel With Top Celebrity Including 7 Plus Two High School Subscribe Sensitive Will Hear From Top Celebrity Six Pieces 790 Will Win 7 Nav This Field Minimum Possible Values Which Say Keep At Minimum Piece Seventh Divine Values Which Say Keep At Minimum Piece Seventh Divine Values Which Say Keep At Minimum Piece Seventh Divine Answer Minute Written This Value Back Digital Logic Minimum 50 Dynamic Programming Like Left Side Na All The Best Wishes Are To Channel Let's Declare Variables Should Read Length jhal ki declaration are with same dimensions to hold your relatives spoon cell jhal my tab where will be no change in the first loot ka paste ki naav letter calculate kyun lete upra top rock on jhal ki similarly calculate kyun platform ke alam hai jhal To a Now Feel Responsible Addicted State Follow Us On Jhal 13 Sarat2 Possibilities Me to Find the Minimum Possible Primitive Snake to Finally Returned Bottom Right Frill Value is to an Old and Coding Letter Court Had Already Written in the Process of Time Where Calling Minimum First Function With Multiple Input Array Bluetooth Settings Eric Schmidt Shiv Let's Share About What Is The Shadow Of Hoon I Think We Need To Change This System That Ego 0 That Boat Dowry Expectant Mothers About How To Find Minimum 5 Some Like It Thanks For Watching Please Don't Like this video and subscribe the Channel thank you | Minimum Path Sum | minimum-path-sum | Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100` | null | Array,Dynamic Programming,Matrix | Medium | 62,174,741,2067,2192 |
101 | Hello gas welcome you are going to do question number 22 of my channel delete code number one zero one is an easy level question but these questions are really good and give options in the starting face of your interviews ok in the beginning we ask such questions. Then gradually they increase the level, then you should come to such questions, it is better that the question is in the name of Symmetric Tree, Microsoft Meta Semen Business Amazon OK, what is input and output, then you will understand the question, but it is not like that, just tell you that it is symmetric. Is it not symmetric? So if a mirror is placed in the middle, if I take the mother, I have written a function which will tell me whether it is my image or not, then it is okay, so now this is the root, so on the left side of the root, I have Send it and get up and send it, first of all and I have sent it, the value of both should be equal, the correct value should be equal, only then it will be symmetric, so okay, first let's check what is the value of L ] All those should be my images, right? I am checking the check function. I have sent that Alka will be sent left and R will be sent right. Both of them will have to check this diagram which has been made for me. What have I done for me, this one is in the court. I have converted this route to the left and right of the route, I have sent it here, it is ok, the value of both should be equal, the value of right, left and right, so I checked it here, ok, the first condition is that the left one should be compared, after that which left one should be compared. Will it be from the right side of RK? Here I have written that it will be right. You are comparing it with the left side of RK, that is why you are creating my image. This will be compared with this. I just wrote the same code in my spare time, nothing new. I have done it, that's why I want to say, it is very important to write a story. Story means writing on paper. There should be a drain here. If you do n't even take the right for it, then both are drains. But if this happens, then how can it happen that both N's are connected? I have also written it and if you look at it, I have written whatever is visible in the diagram, I have not done anything new , , , so if you do all three and will not waste much time, you will understand what I said and what I will send the check for the root and the rights for the root. I will check both of them. Okay, so what did I do? Then it is fine, it is very good. If both the taps are not there, then what is the power? What can happen to me, if this is equal, then the value of R is equal. If both of these are equal, then the value of R is exactly the same as the diagram on the left, nothing else is written extra in this. If nothing happens then return calls. Okay, it was a simple code, I wrote the diagram as it was 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 |
212 | hello everyone Aaron here and welcome back to lead code today we are doing the word search 2 problem so this one is being pre-recorded so if you've seen being pre-recorded so if you've seen being pre-recorded so if you've seen this I must be on holiday and I hope you're all having a wonderful time and I'll be back soon to the regular programming I'm actually recording this on bonfire night in the UK so we'll see how many loud fireworks interrupt this video or buses apparently anyway diving right in with the instructions given an M by 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 okay so if we had ete or something as a word we could just do e t e like that but here we can do um oath oata oh so we don't have to carry on a straight line we can bend and wiggle our way through the grid um we can't do it pea because there's no P that's uh well yeah we can under P because there's no P um it's like the confusing sentence uh eat we can do eat and Rain r but the a is not authoringly connected so we can't do rain so we can only do the eat and the oath um it looks like we don't need to maintain the order in the output so I think we can just return these in any order obviously this is not going to work oh actually no it's not quite obvious why it's not going to work um so a b we cannot get to the C basically we can't get to the C and then we also even if we could if this was a c we also couldn't reuse the B so that's IMM immediately out as well um oh God these words can get very long um the board is never going to be huge uh sorry no the words can't get long we can just have very many words holy moly oh geez okay we can have three thousand words so we need to be somewhat efficient now okay if we need to be somewhat efficient so the E the obvious way to approach this is to just start searching the board but I don't think that's going to be quick enough I really don't think that's gonna be quick enough um but we don't actually care that it's a board well we kind of care for adjacency Okay so what's currently going through my head is that this list of lists is basically going to be a real pain to work with so can we not work with it can I do something that's basically transforms this into something that makes it very easy to find the words and I'm thinking if I map each letter to every position it's in yeah so if I'm trying to find oath I look at all the places where an O is and it's just here then I look at all the places where an a is and one of those is adjacent to that o so I'm going to take that position then I'm going to look for all the places a t is and one of those is adjacent to the A and I'm going to look at for all the places that have an h and one of those is adjacent to the T right that seems reasonable then I try P there's no p um so that immediately failed eat we have an e we could try here there is no a so we need to try a different e uh okay so it's a little bit of a backtracking thing once we're inside each word but here I can go E A is adjacent to the e um T is adjacent to that a and that success Rain r there is no adjacent a so we stop okay I think that's what I want to do um so letter positions there's self Dot um make letter index of the board and then it's basically return W for w in words if self dot can make word w that's a position okay make a letter index board self board let's start with the easy let's make the index so um the index is going to be empty and for I in range plan board 4J in range land board zero um ugh I can't really bother doing all the complicated stuff so collections this is a hard problem so I'm going to take whatever cheats I can um to make things quick and going well actually it doesn't matter here this is a little in fact I'm going to make this a list because it'll be slightly more memory efficient um and that might help us a little bit in terms of speed so I want to do index dot append index of board I J and I want to append i j so if this is looking at an o um if I've seen the O before I will append if I haven't seen the O the default it will start it with a list with an empty list so that's our index can make word self word letter positions right now what we want to do is how do I want to do this I want to keep us used positions oh no so effectively what we're doing here is backtracking so let's this is my I'm going to use my standard backtracking algorithm um a backtrack function takes a state Neighbors is goal um so what we do if is goal state yield state um else for s and neighbors of State yield from backtrack s a force is gold right so now what I need to do is basically Define the functions is goal and neighbors for the state so this date is initially going to well what do I want to do here Okay so state is going to start as none but it's going to become basically a tuple which is of I J pairs um and I'm using a tuple more as an immutable list than actually as a tuple but that's just more of a quirk of python um now is goal um oops that's not at all what I wanted to do death is goal um for a particular state let's call this start state if state is none yeah typing return false um if Len state is equal to the length of the words and do I need to check that it's made the word no I don't need to because I will make sure that the neighbors are always generated to be correct okay so then it's going to be the neighbors of a particular state next letter is the word uh sorry uh no let's handle the if state is none return letter positions of word zero um in fact I want to make this okay P Singleton for p in left positions uh and I want that to be a list so the initial state is none uh then what I want to do is I basically want to create a tuple containing just the initial pair so if my word starts with an O I want to return a list containing the O as a Singleton Tuple um of the O positions as a Singleton triple now in this case there's only one so that this is going to be a list of one element that one element is a tuple of one element and that element is the zero pair for where the O is yeah but that gets more complicated as we go on so here for the a for example um that's fine um else um next positions is equal to letter positions for the word at Len state minus one so if the state has a length of one that would mean we've seen just to position zero oh in fact I don't want to do the minus one there it will end away because if we've seen if we've looked at the zeroth thing then this has a length of one which means the next letter is the thing at position one and the word um oh that's a point um let's go up here LF Len state is equal to Len word return and empty list um else that yeah so this there here we find the next letter the next set of positions that we could go to so we're looking for all the positions for an A and it's these two no these three here um for so let's create a list of viable positions which is initially empty for pause in next positions not in here in um if Paul's in state continue getting more space so this is just saying if I've already been to this location when trying to make this work word don't use it again so this is our ete fix basically if I go e to T to e again that's not allowed um then if not so let's do a little helper function self.json State negative one pulse um in fact let's change this to be more obvious if pause not in state and it's adjacent to the last thing we were at viable positions dot append pause return viable positions now we need to do our adjacent they are adjacent if well um X Y um I one J one is P1 I2 J2 is equal to P2 then they are adjacent if i1 is equal to I2 and J1 minus J2 in fact I went through an absolute value on that and abs is equal to one uh that we can do this as a return that piping is very hard apparently today um or I one minus I2 is equal to one again that should be an absolute value and J1 is equal to J2 so this is saying either they're in the same row and just differ by one in the their yeah they're in the same row and just differ by one in their column or they're in the same column and just differ by one and their row there's a lot of moving pieces we have suddenly coded up fairly quickly but I think that generally works now this one here needs to be finished off so what I want to do is if well hang on what I want to do here basically I want to do this backtrack if I can get anything at all foreign this is very bad never use a bear except but I can't remember what the end of it is it um no I just can't remember uh basically I want to try and get anything off my backtrack and if I can get anything at all then I've succeeded if I can't get anything I failed let's see how horribly broken this is W is not defined hang on oh if not in that's just a silly typo okay it knew we couldn't get p but I didn't know why it thought we could get rain okay show me why did you think we could get rain those are all not we've specifically decided the state is a goal if state is none return false what how does that work not hang on let's just Mark that as being there are you seeing the same thing here I don't understand that at all very confused so it should go X is none then it immediately goes here before it goes here what no I'm very confused by this what have I got wrong here it must be something very obvious I'm missing I feel like this is a very simple thing I've not understood IE Supply these arguments back to front that's all I did wrong uh all right now there's another problem now I can't say any of them were so we get zero that's expected hang on okay so hang on what are the neighbors here I sees oh no that's not what I meant to do that's what I'm doing wrong here I want to do State plus pause for pause in viable positions that's my problem I'm not correctly updating the state that's better much better right let's get rid of these Diagnostics am I still printing anything I don't think so no I'm not good let's use all the example test cases I was too quick now the question is the code going to be quick enough you were not signed it what do you mean I'm not signed in I am signed in it says right there I'm assigned it and anyway use the example test cases okay good that seems to work now the question is it fast enough only one way to find out oh apparently I tried this again two years ago uh it was one a while ago I was doing that I tried to do two years ago and it looks like I managed to solve it but it wasn't fast enough and I suspect we're going to have the same problem today yep time limit exceeded for this monstrosity I don't remember doing this one don't remember what the solution is well I never found the solution apparently so it is timing out how can I make this quicker well I guess one thing is I don't need to actually build up a list here what I can do is I can yield State plus pause I can just do all of that inline um no this is wrong as well no that's correct actually but I'll still turn it into a yield 4p in letter positions word zero yields p this one here is just going to be return an empty list um that's about as quick as it's going to get because it'll just check if these errators is empty or not because I don't know where it was slow obviously the back track is in some sense slow but how could I a priori see none of these are very long so this Paul's not in state that's never going to be super slow I don't think I guess to a certain extent um the letters in here I could do a quick check at the beginning of if any um L not in letter positions for l in Word term false that's a bit of a special case though so basically it's just saying if there are no if this string contains a letter that's just not even in the grid don't bother doing a search maybe that is the special case we need to handle just to pass this test because that should certainly be faster apparently not maybe we're just doing this the wrong way there's no way we need to search because this turns into well let's see exactly what it turns into print letter positions I don't know if it'll show it to me because we're timing out um hopefully it will am I meant to go the other way because I've kind of been assuming that the word list is more restricted like how many words could I make here I could make oh well I can make all the Singletons I can make all the doubles right there no that's huge there's no way that's what I meant to do because this can be up to 144 characters and that's two to the 100 but no that's stupid no we're not doing that um maybe it's restricted enough actually how no two to 144 is an overestimate because that's picking any possible subset but it is more restricted than that because of this adjacency required so for example I can't have okay that's not a strain I can generate from this grid no it still feels way too slow it's got to be some let me just quickly put that in there just so we can see what letter positions is fairly sure yeah it's just as a b pair how can I speed this up I guess I um no that wouldn't help in this case anyway so what I was going to say was maybe next inside net well next to the a I could store the letters that are adjacent to an a but that would just give me B which is no help whatsoever because I could turn this into a giant search tree oh the a at zero one is adjacent to these bees at these positions and they have these adjacencies and basically turn this into a giant tree that I just need to search but that's yeah no going back to the table um I could group the inputs because all of these start with a b so once I've found that uh no because they could have different parts to get there so I was going to say well what I could do is just find the path to build this prefix and then just test what I can finish but the problem is there might be more than one way to get that prefix and I then need to test all possible ways of reaching that prefix anyway and that doesn't save us any work at all um unless I could memorize it foreign where does the LR UK live in Python is it funk tools well it didn't immediately die um let's just still not fast enough is it definitely does run yeah it does um is that going to work because this gets really cleared every time I enter the function probably not so that's probably not a helpful optimization anyway I'm just trying to think how can I do less work and I genuinely don't know because the problem is I feel like with this grid you could snake your Ababa be so many ways that you can't really cut off the head of the workload just need to do less if I turn those around this check is order one and this check is ordered k for the cabin length of it so perhaps if we can reject this out of hand first that's very slightly faster this doesn't need to be stored in a separate variable um what else can I do to make this install bailing out that makes it quicker but it also makes it wrong um oh that was quick enough just swapping those around oh wow um so this search here is all Decay but it's such a small cat I guess we're doing it so often that it actually matters hang on let's do scene is set state does that help I guess these timings are going to be too flaky to really know timeline exceeded so if I undo this change I guess I could change my representation entirely no that would be slow again why don't we weren't we fast enough before hang on what did I do wrong hang on no that's where we were before and this is now too slow again we must be right on the Tipping Point of being fast enough no we're fast enough again hang on What's the whatever no I don't want to write down differently hang on no I don't understand um I don't understand let's submit it and see if it's fast enough I doubt it seems to be pretty borderline um if we pass I think it's more good luck than good management uh time I've exceeded on a different problem at least but it's exactly the same problem structure except we can't rely on our thing uh our cheat um well we could do a I wouldn't even save this case I don't think I was just thinking what we could do is rather than doing this check we could count the letters um and say well this is looking for one two three four five six let's say 10 A's and other 10 A's in here cost her 10a's in here it's a grid of freaking eight um no I'm fundamentally approaching this wrong and I'm fairly sure it's the backtrack because this is pretty it's pretty quick to tell us where we need to go there's no point walking the word backwards because well if it really doesn't matter um nothing we do here is all dependent and they could just give me the string in the opposite direction and that ruins that optimization um how can I do less work here how can I change neighbors so that we are just returning fewer Neighbors basically maybe this is slightly wrong because in this particular case it's more work yeah there's only four adjacent positions yeah this is the wrong way round so let's just call this is adjacent um this is let's make this self.board um self.board and i j Celta board IJ is equal to word P so let's do p is equal to oh goodness p is equal to Len state yield State plus i j um and pause not in um if I'm only looking yeah no I still want to do that full check so rather than doing that I'll do this so I wanted to hear is Jason locations so p and I J is equal to p and what I want to do is I want to return um m n for M and potential locations if m is greater than zero and n oops is greater than or equal to zero and that's the wrong way around completely um and N is less than oh sorry m is less than length and it's less than lamb self.board and it's less than lamb self.board and it's less than lamb self.board zero and it's like I want to break that way okay so potential locations is equal to the list containing I minus 1 J pi plus 1 J i j minus one i j plus one let's see if that's a little quicker I hold very little hope in theory it should be we're now searching just four locations rather than potentially many locations it's just we no it's still too slow foreign still works even okay it still works at least just too slow get rid of that is it this again what can I do to make this so one thing I'm thinking is we can do a we can change how the state is represented we'll have our nun here but then what I want it to be is an IJ pair set and the last position so this is going to be lens state zero this is going to be State One so this is going to be the Frozen set containing the p um that's meant to be there and then okay so it's Frozen set containing the point and then we get here what I want to do is I want to return state zero unioned with the Frozen set containing just i j with i j that can be l that'll save us a little bit now I don't know if this is the right syntax but let's give it a go well didn't immediately break it's probably a good sign memory limit exceeded that one's new um okay what can I do here seriously a memory limit so the Frozen sets are taking up too much space while I'm here let's tidy this up let's use the class function it's a little bit to our advantage foreign set I don't know if I'm allowed to do that um I think it has to be done this way with this Union I can't use a regular set because that would mutate well maybe I can just use a regular set but I don't think it's any more memory efficient oops the head didn't fix that back to time limit exceeds well quickly check this still works generally and let me just copy that test case again so it definitely still works we're just too slow what am I missing what am I not fully understood about this problem let me look at it again if I've s memory limit again I'm hitting something strange here now this is kicking my ass and I don't know why maybe the previous state representation was the right way to do it oh that was also wrong okay before I go and revert back let's just try that shouldn't I can't imagine it'll make a difference but I'd rather fix those bugs before I give up on this perch completely yeah all right what have I not understood what is the trick that I don't understand so there's lots of ways to do these first A's then I just need to decide have I got to the final lesson or not but there's no way to cut off the first set of A's you see this one's annoying because if I just reversed the string this would in theory be very fast but that's just a weird hack not a meaningful thing um I guess in one sense I should be picking A's that head towards the letters that I'm trying to end with but that's just such a weird optimization so I'm thinking here my backtrack is basically a depth as such what if I swapped it out for uh a star or something like that to make sure I'm aiming for any of the remaining letters in the string but that no that's just a weird that's not does not generalizable that's the problem that would work for this particular problem like if I do this is that fast oh maybe it's not I would have expected to be much faster actually now it's a Memory limit exceeded so let's undo all the state crap um revert back to the state I had before because I think that's a better representation what's going on here did I never find the IJ ones or if I just output them in the wrong order ew that's what I've done wrong um no that's not what I've done wrong I was gonna say oh I reversed them but I didn't put them back again but no I only reverse them to go into the function check that's now there's the IJ thank you am I expected to Output these in a certain order that's Earth and each thank you I mean I'm going to preserve the order anyway so it can't be the order as such that's breaking me let's try this one again let's see why that see if that's breaking that one's passing so this one and it's very fast because it's hacking around a particular Quirk of the data set this one's wrong but why that's unhelpful wait hang on why did that one cut off God how much am I printing why did I find so many more things oh there's something hey lots of A's with a t a on it I'm finding that but I shouldn't be able to oops show me that this is going to get very annoying very quickly well let's take that much and then add it in here so I shouldn't be able to find that so why did I think I could pause is wrong why hang on why isn't that failing at all what have I set pause to that should just be a poles should be undefined shouldn't it oh God I don't know that why did that work at all what's going on why what's pause doesn't exist so that variable should have been I guess it was never being hit um but it clearly was bit now and I don't understand okay can I get rid of this weird reversing now if I do that because I don't want to leave that reversing in because that's a weird hack to get around the particular test cases no it's too slow it is too slow all right let's do that and exceeded maybe I do want to go back to my weird hybrid state foreign oops I'm gonna have state zero or the set containing i j paired with i j this will be a memory error time limit exceeded what happens if I do my reverse trick again let's see if we don't get a memory error and I spell functions correctly don't like that I don't like that's hacky hopefully the tests are going to penalize me for it yeah good they've got that test case in there too how can I go faster how can I do less this is pretty quick if you know what M self dot m is Lan board self.n is land M self dot m is Lan board self.n is land M self dot m is Lan board self.n is land board zero damn n jeez stealth.m self Dot and um these ones up here need to have cells in front of me um get rid of this don't like this try again that shouldn't have made much of a difference but who knows time limit exceeded don't need this guy anymore what am I missing I'm just trying too many things is it there's too many start positions because one way to think about it is if I'm at if I'm three steps in and the last thing I looked at is the same um yeah if I'm the same length through the string and the state I'm out is the same then I don't need to go back there again um so there's a cache here um what I want to do if I'm back to where I was there's no point continuing um so memory is just a set so what I want to do is I want to have something that turns this into a semi-unique semi-unique semi-unique thing I can throw in the memory and the way I want to do that let's call this memorize it's more of a hash in a way but yeah it is what it is um so what I want to do is I want to return the Lan state zero a long State one that is the memory and it was why is that let's have a look at some of these oh but it didn't print anything at all um that's interesting maybe it's non-local memory what how is that not printing anything that's something I don't understand do I get there at all what's going on okay I get there a lot so I call memorize but I don't quite understand why I never get to the line immediately after calling memorize is it just because no that doesn't make sense foreign it never does anything have I've got to get here okay I get there we call this oh if state is none why doesn't that error oh there may as well make none thing that's going to be way too much printing output 11 exceeded set no none okay let's try it with less printing because that may not be helpful that's clearly not helpful um set on my printing I think that's all my printing let's go again the reason I'm hoping this works is just because there's so many ways to get from here to Here For example but if they all end up no it's not far off got that one no I got that one so if that's doing good it seemed faster well it finished put it that way uh these are all good I'm still not sure how many over is it just a little bit oh no it's over by many words actually no it's missing many words sorry we only found up to there we're missing all of these oh I know why we're missing many caching's bad we can't do this and we can't do it because the path I take matters if I take a different circuitous route to get to the seventh a that will block a potential path I could take it could block a future dip into that part I can't even oh my goodness the one optimization that seems to be fast enough doesn't freaking work um Maybe that's good enough in instead whoa no it isn't I guess I still need that part nope how did that do better so I know this should be what no what oh what if I just do that oh I know what's going on I had forgotten I had changed the state representation again um and I can't just throw it's this except here dop iteration I don't trust myself to have that correct um time limit exceeded again I trust myself with that um it is concealing errors that I need to catch this is why you know I have a bear except um so at least the length was making it faster if I finish this one it's going to be an awfully long video foreign oh gosh I don't know can I go faster what have I not I just I'm fiddling around the edges and I need a fundamental rethink I think that's the problem foreign but I don't understand I'm treating the words independently and I think that's wrong but I don't see how I can not treat them independently so the reason I'm thinking uh the problem is I'm redoing lots of work I'm finding all the ways that you can't do all of these prefixes here and all the ways you can't do all the prefixes here again there's a limited set of ways that you can get here that I would like to reuse here so what I'm there are two ways I'm trying to think one is to make this memory smarter and to basically memorize every prefix that I see so that I can immediately just jump because Neighbors I think I need to de-generalize this because if I've seen this string yeah so once I've seen the a I know all states for an a once I've seen a I know all the states for an a um scene dates is going to be that so what I want to do not a dictionary um how can I do this generally maybe I don't want to do any of this at all let's move no I don't know what I want to do that's my problem that I'm currently fighting um because it's for hang on so the start state is initially the list containing none um let's call this s return any can make s for SN stock States the idea is that initially the start States is none but for I in actually that's let's say the empty string starts there um for Iron Range LAN word what I want to do is I want to say if the word indexed up to I don't want to I'll do that offsetting in here negative I plus one um is in scene States start States in fact um is equal to scene States word uh let's just take that pre break So eventually it'll slice this all the way down to the empty string uh now the trick becomes um thank you now let's do this differently this is the default dict with a set and I want to set scene States all the empty string to container none foreign let's use memorize and what memorize can do now is s is called The Empty string oh Alex um I want to revert my state again I keep flip-flopping on how I want this keep flip-flopping on how I want this keep flip-flopping on how I want this steak to be designed one day I will decide so the reason I'm reverting this is because what I want to do now is be able to rebuild the word so it's Four Paws in state okay hang on if state is none okay s is the entry string for poles in state s let's make it a list dot append self.board I J W is the join of s uh and then what I want to do is I want to set scene States w dot add so this is saying I've been here before well a possible state for this word prefix is s so basically if I get all the way to here I immediately know all the different states that I should start from bollocks um no yeah this isn't helpful it doesn't memorize anything oh I no I didn't that doesn't need to be global I can put it in here so there um you know what let's use this now yeah heck let's just go nuts foreign States whoops that's because yeah that's correct that shouldn't have a self on the front why is this thing never getting updated I'm gonna put that in because I think there's an exception J is not defined that's the kind of thing I needed help with ah now it's memorizing things we got the wrong answer but we're memorizing things ah thank god um okay these are all the places you can okay that's good oops no actually I want to keep that one but I do want to get rid of all of those are we correctly starting further along yeah we are actually no we're not oh bollocks that's not correct show me scene States again no there's more than one way to get to a it's because we weren't exhaustive maybe here it's worth forcing this to do too much work to begin with so I save work in the long run huh oh wait the edited yeah didn't close the parentheses that I typed um so this isn't Theory extremely wasteful in one sense but potentially quite unwastable in another so the reason I'm tossing it whether it's the right thing to do is because basically before we were saying if you can find any way to do it you're good now I'd like you to find always to do the first one so that the rest will then be much quicker foreign what do I do because when I back out early I find one way to get here and then great done but that means I've only memorized one way to get here but then I just reuse it for all of them I don't acknowledge that there's potentially more than one way to get there so what I need to do here is to start state is equal to set um so let's do this again try uh next return true except stop duration okay false so this slight difference changes the start States we no longer just output limits so now we no longer just do the start States for where we got to but if that fails we try uh one step back which should get around the problem of we didn't search exhaustively thing is this may put things in a bad order time limit exceeded because I want foreign let's do it as a list just so I know that we're doing this in the right order the reason I'm worried we're doing out of order is because set has no order inherently python did change that um exceeded Pop um this feels like an improvement still work in general to that age okay it still works in general just these big ones it's still too slow so what am I not understanding because now we are reusing previous knowledge I'm looking at this and saying well I know how to get this far so I can at least start my search from there and if that doesn't work well I could at least restart it from there that doesn't work I can at least restart it from there and is this where I need to memorize that might be what I need to do so let's do this seen States this time as a set non-local is seen States this non-local is seen States this non-local is seen States this time seeing States this time dot append foreign this needs to come up here oops because in here or stay in scene State this time and the thinking here is not good apparently the idea was that we're going to not only record things seen in every run but we're going to record them specifically for this word in the sense that if this didn't work I'm going to try this but I don't need to retry all of the things that got me to here but that's not necessarily true for the next one it's probably worth trying this again just to see if I can get to the B so that's why that one needs to change every time this needs to be spaced out I'm getting myself confused okay foreign why is that now not working the idea is if I've already seen this state in this run there's no point extending it any further oh but that's always crap oh that's always true what can I do with that well let's slice it um ignoring the last thing time limit exceeded thank you how can I do this work I just can't track and that's the thing I don't know how to avoid how can I not backtrack I don't like that um foreign that's not what I want to do so I'm changing this API a little bit um and the way I'm changing it is that now this just returns true or false just to make it a little easier to work out what's going on still too slow though where is it too slow is this one still too slow because this is quite this one I almost was fast enough on in the past I've made quite a few tweaks since then no still too slow oh so that one's now fast enough that's interesting does that hold generally okay that one's fast enough we're still on this one being too slow so we're making improvements um is this the problem sorry this is slow maybe I make this a two State One so I'll just state zero plus l um apologies for the loud vehicles I have to put up with them all damn night um Okay so the state now contains both the um word and the set of coordinates so here we're just going to do this check still I'm going to throw this in as well just to be extra safe um this is our start state every time now we extend both the positions and the string so in here now we don't need to do any of this so this is now state zero well might as well make that State One no let's make it the whole state that doesn't feel like a big enough change to actually make it worthwhile but who knows I haven't exceeded it was not enough who would have thought it where am I starting each time let's just see that probably gonna be too much output there that's unexpected ordering I guess it's not so we do actually cut off a fair bit of work on the first one the problem is well this one just requires a lot of options because it's not successfully none of these are a good starting point these ones are better I cut out a lot of work for these oh no I don't I'm still seeing lots of options show me what word I'm doing it each time foreign we have to try lots of different things AAC oh my God we have to try lots of things again it's because we don't know which is going to be successful and I'm not sure we can know which is going to be successful can we well we could immediately prune a lot all the ones that go from 3 8 for example well no that's not true in general either because all the ones that end in the same place I don't need to retry all the different ways of getting there but I do because I might not just be extending by one thing I might be extending by several things and then but then the path I've taken matters yeah it's just so long so many different ways of making this many A's oh we switched to a d at some point but we've done again so yeah it doesn't really matter um oh so that means switch happened there so we did actually save some time in a way so it's an improvement it's just not a good enough Improvement what else can be done about this because this is good like we're jumping all over the place on our tail here we're trying lots of different finishing points to try and make that D happen is that one two three four five six seven eight nine one two three four five six seven eight no Okay so foreign it's just each of these I will reject them fairly quickly because what we would do is we would start the search find the neighbors and immediately find that there's almost certainly not a d right next to it and so return no Neighbors ending that search so be fairly quick it's just too big a search space I don't get it we've done the hard work once to get the nine A's basically we know all ways to make nine A's and we reuse that information a lot do I just do this with a tree a try like t-r-i-e so t-r-i-e so t-r-i-e so as I'm with that help who kind of end me up where I am now so a try is basically a non-deterministic a try is basically a non-deterministic a try is basically a non-deterministic string is one way of thinking about it um so what we could do could we do um I'm just trying to think could we walk a try and how much would that save us so if we build a try of all the strings these would all basically be a whole lot of A's with a couple of leaves a couple of different branches at the very bottom we still need to do a back track but we're not backtracking over one string anymore we're kind of backtracking over all the strings at the same time so then how would that change things so our neighbors would be again all of the yeah maybe that's be a complete rewrite but it might be worth it because the memorized would probably not need to be done anymore his goal would stay the same effectively but neighbors would change to be not just if the board is the letter if it's any of the possible letters at that level of the try oh what the heck let's give it a go you can't hurt um let's do I want to do this anymore yes I do so then what I want to do is words try self-talk build words try self-talk build words try self-talk build trial words then what I want to do is day um self-top makeable words try so let's do make it build try first um now try is basically a kind of tree so let's make a fast node class try node um in it oh my goodness by typing self um value I guess oh what the heck let's just leave that um self dot letter oh now I need that is a letter and then self.next is a dictionary and this dictionary is a dict from at least we capitalized of stir to try nodes so what I want to do is the root is equal to a um tree node with the empty string root dot bill um stand with the entire words return route and up here the way we want to deal with this is extend self word list so what we want to do is effectively group our word list by the first letter so groupings is a dictionary so for word in word list all right let's make the default decked with a list in it um groupings word zero dot append word sliced from one self dot next is equal to l uh Prime node um with l in it oh gosh what I want to do here uh yeah so I want to do this a little differently here so um for letter sub words in groupings dot items self.next is a try node self.next is a try node self.next is a try node built with the letter um how do I want to do this actually self Dot is terminal can be false to begin with sub in fact now we'll do this and extend here if yeah that's what we want to do so I'm just trying to think the trick of the try is you need to know where it's going to end basically um if word is equal to the empty string self-duck is terminal self-duck is terminal self-duck is terminal is true otherwise we need to carry on and then what we want to do is I want to do um self.next for the letter there's a try node with that letter if I do anything to store the letter I probably don't do I anyway I will anyway for now um self.next dot extend self.next dot extend self.next dot extend sub words right that should build us a try so now what I need to do is makeable words self try so a lot of this now needs to be the same as we had before depth is goal state and we're going to go back to just our Tuple of coordinates um actually how do we want to do this we're not going to go back to our tubular coordinates we're going to keep our pair which is word um word chords is the state if tried up contains words in fact that's all we want to do isn't it return it contains word there Neighbors that I want to get rid of this business oops that's not the right cucumber um state so let's do the coords is equal to state so this is going to look similar oops that's a good point um if state is none turn false um if state is none return false and then here L is equal to oh gosh what is it no it's not that um it's possible letters is um oh that's something I need to change about this words can be prefixes of one another so that needs to change um foreign extensions of the word and then it's for IJ in adjacent positions of course negative one if self dot boards i j in possible letters and I J not in chords we're going to extend the state appropriately and then let's keep this simple ish for now um can make I will keep like this we don't need memorized anymore up there in fact I'll just get rid of this completely um so that's return can make none so I need to update my try to do depth extensions of keyword um if word does not equal the empty string return um hang on letter is word zero if letter not in self.next self.next self.next return just the empty set um return self.next the letter dot extensions of word dropping the first letter um if the word does equal the empty string in fact that's probably a better way to do it the word is the empty string foreign self Dot next dot keys and I think I'll just make that a set for simplicity's sake does this work extend oops self-talknext letter oops self-talknext letter oops self-talknext letter dot extend neighbors is not defined because I can't spell server error oh geez I don't think that one's my fault um let's just kill that I'm not making any progress with that let's try again oh that's a good point foreign is return S 0 for s n that except I should absolutely have done this with the example test cases first because they are much easier to debug okay Neighbors state is none I don't want to return that what I want to do is I want to return um what do I want to return try dot extensions of the empty list that gives me all the first letters I want to do a yield from with this and then I want to make this an else here so each of these is a letter L for L and try um but I don't want to do that I want to do l P for l in try extensions or p and self dots letter positions of l I think that is the start State I actually want I didn't do try dot contains it contains self word if word is equal to the empty string and self dot is terminal return true Ellis word zero knot in self dot next return false else turn any um of the Tito self.next l dot contains hang on what do I want to do so yeah what I want to do is I want to do self dot next word zero contains word one onwards string index out of range word zero word is equal to the empty string return false where's that oh that's the problem solved up board I J in fact let's just do that indexing immediately that works let's try this one which we were fast enough to pass before just let's see if we're a bit quicker this time doesn't look promising oh we find too many copies time them exceeded okay um the problem is prefixes so as we saw there okay let's undo that particular transform because it's concealing something that's actually a bit of a problem we're finding many ways to make the same word and we just simply don't need to how can we know that so if I have toast and toaster for example I need to keep going because what this is going to do now is just fail to stop I'm just thinking well no don't eat that try is a set in a way but round is a set non-local if word in found false if B found dot add word return B that worked but that don't like it but potentially that's what we need to do okay so this one think we're still going to be a little slow but we might be a lot closer than we were oh my God we're fast enough okay um a bit of a surprise this is going to be an absolute Marathon video this succeeds the submission with me spending way too long on completely the wrong solution which looked about right oh God please be fast enough please fast enough no bloody hell why is this too slow thank you so the thinking here is that once we've found all the words we can immediately stop it's a bit of a hack for this one um but perhaps is good enough is this still fast enough for this monstrosity that's an extra check we have to do every time and might just be slow enough to push us over the limit so I'm living exceeded we're now too slow so fragile so the tree means we can search for lots of things in parallel but it means we don't know when to stop a backtrack quite easily perhaps what we need to do is also Mark the words as found or not inside our try because then that would more naturally cut off our search the word is empty self-top found is equal to true I'm going to return true as well um then what I'm gonna do is say um self dot next word zero dot mark has found um with word one if all T dot found or t in self dot next dot items okay don't want to return anything there um what I want to do if we want to have this all found business so I'm just sort of thinking I can Mark these things as found but uh let's do that so the extensions here so what I want to do is return the set k for K and self.next.keys okay let's do this with items um if not T dot we found um no that's going to be a problem we'll only Mark terminal things as found no there's more I want to do here um if it's a leaf hang on something else I want to do here what I want to do is only return the next branches if we're still looking for anything foreign yeah that's correct so then down here Mark is found if get rid of all of those if all um Marcus found yeah okay if Len self.next is equal to zero or all Len self.next is equal to zero or all Len self.next is equal to zero or all T dot or children found or t in self.next dot items children children children found gets set to true yeah so you mark this is found is that correct I think that's correct this is quite complicated and I'm really struggling a bit it's also quite late at night here um if there's nowhere else to go obviously all the children have been found or if all the children of every child have been found then it's been found oh heck let's just test it time limit exceeded let's get rid of this check I don't like Ah that's something I should do I need to mark this as found foreign words trying to be so contains which are not self Dot found the object is not callable Mark is found foreign triple has no attribute all children found values still too no quick enough oh my god um Oh Happy Days this one yes this one I can't remember which one I did when yes oh it's so borderline yes uh maybe so slow yes oh my God this is gonna be what I've three hour two hour at least video oh my God it's very nearly midnight here I am exhausted um I didn't think I was gonna get that this is a nicer solution this try is a nicer solution um these two things I haven't been hard about whether I want to combine them oh Jesus that could be made nicer just by doing that oh holy crap okay that hopefully you'll not find that worthwhile um you know what I was recording this as it's nearly midnight here and I don't know if you can hear that very loud motorbike just went past the window that's what I have to deal with it's flat um I was going to save this as a one to put out when I'm away I think this just needs to be shown this is that this needs to go up tonight or tomorrow at this point because oh my goodness that one was an absolute Beast of a problem it this better be hard this better be yeah it's a hard thing like girl it's a hard problem um because I found it very hard um if you gave it a go do let me know how you're meant to do it because I don't know if that's how you're meant to do it and I just spent an eternity going around the wrong solution I'm sure there were many times in there when I was dead silent um anyway tell me how you meant to do it put me out of my misery um other than that I hope you're having a good weekend remember to like comment subscribe all of that good stuff and I will see you next time bye | 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 |
743 | hello everyone welcome back to my channel in this video i will discuss the question network delay time with the gesture algorithm from the description we can say we have a network of nodes we also have a list of array as times including the value between each nodes and the time and now we have a star node as k from the star note we send the signal to the rest of nodes we need to return how many time all the nodes receive the signal from example one we can say the star node is node 2 and it spins times 1 to send to node 1 and then it spend time 2 to send to the node 4 so the result is 2 if we could not find the result we need to return -1 in this kind of problem we to return -1 in this kind of problem we to return -1 in this kind of problem we can use the gesture algorithm to solve it and this kind of algorithm need a priority cube based on the normal bfi's algorithm we can use the priority queue to traverse the node in increasing order of times as required to reach them so in each iteration we can reach the node in shortest time which could help us to fund the faster time and first of all we need to build the graph based on the time input and then we create a priority queue sort the order based on the times we intentionally the queue with the start node and the time zero we need to create a hashmap to save the time used in each node and then we can iterated the priority queue the current node would be the first value of the array and the current time used it's the second one of the ray and once we get this value we need to update the hashmap about the time cost if we already visited it we don't visit again and based on the node we iterated the next node from the graph we made we can know the next node dates the first of the array and next this is the second one and the way plus the time we use the update the value into the queue once we finish this iteration we can get the result from the hashmap about time cost before that we need to check if the map didn't have all the node that means some node could not just receive the signal we need to return -1 and then the signal we need to return -1 and then the signal we need to return -1 and then we can get the max value from the map as the result let's run the code so the time complicity of the algorithm is o of m plus e log n and is the number of nodes e is the number of edges the priority queue spent the e log in and save all the time into the map cause the on the space complexity is o and plus e if you like this video please subscribe me and give me a thumbs up thank you for watching | Network Delay Time | closest-leaf-in-a-binary-tree | You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target.
We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
**Example 1:**
**Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2
**Output:** 2
**Example 2:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 1
**Output:** 1
**Example 3:**
**Input:** times = \[\[1,2,1\]\], n = 2, k = 2
**Output:** -1
**Constraints:**
* `1 <= k <= n <= 100`
* `1 <= times.length <= 6000`
* `times[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `0 <= wi <= 100`
* All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.) | Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target. | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | null |
26 | so Hello everyone, Let's solve the next problem from the code: Remove duplicate From sorted the code: Remove duplicate From sorted the code: Remove duplicate From sorted array Here the joke is also very similar to the previous problem, open it here, I've already solved it, so let's move on to the description of the ideas, it'll probably be better to start with this array, it's sorted, so let's say leave it alone unique elements at the very beginning, return the number where these unique elements end, that is, here we have 123 left. This is what we return to him, the number 5, that is, these first five numbers are unique, then there are numbers that Well, they are not important to us, they can stand as they want and what do we come to, let's quickly copy this one and how this can be solved because we will have a pointer to what we should insert and we will iterate from the first index, that is, this 01. So we operate from here and compare the future index, that is, this one with the past if it is not equal. This is the number from under this index, we insert it into our index. And if it is equal, then we continue to iterate through this array. In search of a unique element, when it is found unique, then we insert it again into our index here. Let me write probably. So we have an index, it will always be equal to one because the first number will be unique and we probably don’t need anything else, which means we create probably don’t need anything else, which means we create probably don’t need anything else, which means we create a cycle if we start from one more throughout the entire cycle and operate on it, see if our number is equal to us and minus 1 is what it means. More precisely, it does not equal. This means that we can insert it. So we insert it into us with insert Index, which we will take from the current iteration and the current iteration with the help of and is indicated and we will increase our Enter. That’s it, that is, Enter. That’s it, that is, Enter. That’s it, that is, logically we start with index units because this is the first pointer that we can insert something in. Our first element will always be unique, yes. As a result, we check what we will allow, so we check that the unit is equal to the first element, it equals, which means we move on it doesn’t enter this condition and the doesn’t enter this condition and the doesn’t enter this condition and the next iteration occurs, that is, and plus now we have two already, they Sert index we still have one as before. So now we are already comparing the Two if our two is not equal to the previous element, that is, and minus 1 it does not equal, which means it is unique in its kind, it can be inserted into the pointer to our institute, it is equal to one and what we do is we insert therefore the pointer and increase our pointer to insert by one and the next time we check there that so we found a deuce, it’s excellent From the previous Tape So it’s it’s excellent From the previous Tape So it’s it’s excellent From the previous Tape So it’s unique, we’ll insert it into unique, we’ll insert it into unique, we’ll insert it into our insertion pointer, that’s it, that’s our insertion pointer, that’s it, that’s our insertion pointer, that’s it, that’s all, let’s all, let’s all, let’s write the tests here, nothing new, initialize the object 0, or rather, create an object, initialize it here, input data as indicated above, here Input so-and-so should get two and Input so-and-so should get two and Input so-and-so should get two and our array will actually change. Let's check that we really will have 2. So, we return the Intex sensor, logically because the index doesn’t certify, it will logically because the index doesn’t certify, it will logically because the index doesn’t certify, it will also show how many elements we logically need to have unique because we are training with inserting through it Now, let me write another similar method that tests us, it will have these input data and the output should be 5. Everything works fine. Let’s Everything works fine. Let’s Everything works fine. Let’s insert our solution and see how optimal it is. In fact, we’ll submit the optimal it is. In fact, we’ll submit the optimal it is. In fact, we’ll submit the solution correctly. Okay. efficiency is one hundred percent according to memory 5 percent but here guys There’s memory 5 percent but here guys There’s memory 5 percent but here guys There’s nothing to be done here Well, something can be done but it seems to me that the solution will be acceptable here we have no longer with the same efficiency as ours and therefore for the human eye This solution is very good and excellent in efficiency, if from memory there is something too critical, you write there in the comments, we will listen to you and maybe we’ll make we will listen to you and maybe we’ll make we will listen to you and maybe we’ll make another video, so thank you all for watching, write comments here | Remove Duplicates from Sorted Array | remove-duplicates-from-sorted-array | Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_ `nums`.
Consider the number of unique elements of `nums` be `k`, to get accepted, you need to do the following things:
* Change the array `nums` such that the first `k` elements of `nums` contain the unique elements in the order they were present in `nums` initially. The remaining elements of `nums` are not important as well as the size of `nums`.
* Return `k`.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:** 2, nums = \[1,2,\_\]
**Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,2,2,3,3,4\]
**Output:** 5, nums = \[0,1,2,3,4,\_,\_,\_,\_,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-100 <= nums[i] <= 100`
* `nums` is sorted in **non-decreasing** order. | In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element. | Array,Two Pointers | Easy | 27,80 |
345 | all right welcome to this video let's solve Lika prom 345 reverse vowels of a string now of course you can solve this problem by using regular expressions which I see a lot of solutions doing and that's perfectly fine however personally I suck at regular expressions and your asked us and say a whiteboarding interview and you know you don't know regular expressions that well you could get stuck right now of course your ass is on site or perhaps say a phone screening you're allowed to Google things but maybe you know you're stressed out and you know all the regular expression syntax will confuse you and so I decided to go with a non regular expression approach and it's more intuitive to me cuz I'm not good regular expressions but of course if you solve this using regular expressions you're more than welcome to write this is just my take my solution and of course you like this kind of content be sure to LIKE comment subscribe hit that notification bell and you can check out my full length courses on kaa with that being said let's with that being said let's with that being said let's get started so hopefully you read the directions but of course if you haven't we're gonna reverse the vowels right some vowels are AEIOU they're not where I could include Y says so right here so the Val's are a and oh we're to swap them right and so let's get start of my non regular expression solution so I'll say Kant's vowels is equal to this hash table I'm gonna use a hash table to store the vowels because I want that all one lookup time that hash tables give us and of course it look like this right we'll say a is a vowel will say true right so is a capital a that's also Valis will say true so it's e blah but right now it's empty so we gotta fill it up with vowels so I'll say for const char of AEIOU and then also the uppercase version right so for of loops you can put you can loop over strings or arrays so I'll pass in the string which has in which has all the vowels excluding why and I'll say vowels at Chartres right from up here balus char is equal to true so this fills up this empty vowels hash table slash JavaScript object to look like this so now we have something to refer to if something is a vowel now I'll say Const characters okay so let me explain something now strings in JavaScript are e mutable right that's a really fancy way of saying we can't really modify strings directly right and what they want you to do is we'll reverse the balance of a string right take this e and o reverse them but we can't modify strings directly in JavaScript they're immutable so how do we solve this bump what we're gonna do is turn the string into an array and then we can modify arrays directly right you know dot push or we can swap things around the array so turn the string into an array which we can modify then once we modify that array by swapping the vowels blah turn our array back into a string I hope that makes sense so again strings are immutable we'll turn it into a array of characters so say s dot split on an empty space alright then what I'm gonna do is to switch things to reverse that things around right in my array of characters now I won't have a left and a right pointer and then swap the things at the left and right pointer if they're vowels and then shrink the left and right pointer swap if necessary until we reach like the center of the word or array we're working with right so we need a left and right pointer right there start opposite ends will say let left be equal to zero because left is on the first character of the array we creative characters first thing in that array that index 0 and of course the right pointer has to be on the opposite end so I'll say let right be equal to s dot length minus 1 and I'll say while left pointer is less than right pointer all right now we got to make sure the left pointer is at a valid vowel if it's not keep moving it up and up until the left pointer is at a vowel so I'll just repeat while left is less than right and I'll do s left in vowels is equal to false so whatever is that S at index left is not a vowel we can also just condemn this - I'll take this out and then put this - I'll take this out and then put this - I'll take this out and then put the knot marker right here okay this just makes the code a little bit shorter I'll say left plus equals one and again all this is saying is that if the left pointer right now is not a vowel keep moving it up until it's out of valid vowel right awesome and we got to do the same for the right pointer if the right pointer is not a valid vowel keep moving it down and down within the boundaries of the array right characters so I actually just copied this I'm gonna say an S right is not invalid so we have the exclamation mark when do right - equals exclamation mark when do right - equals exclamation mark when do right - equals one okay now after these two while loops within this while loop finish okay now the left and right pointer are gonna be invalid vowels and we gotta swap them around now I personally find swapping a bit hard to understand so I always delegate swapping to a helper function I'll call swap and swap will give me one second so swap which is outside our reverse vowels function will take in three arguments write an array and I and the J index and of course we can do our I is not equal to RJ right the swap this is a swapping logic RJ is equal to R I here's a swap it's not perfect though because we just set our I to be equal to RJ so we say RJ is equal to RI we're saying RJ is equal to RJ so we need to store the old value of RI to avoid this problem so I'll say Const temp is equal to R I then replace this here with temp all right so we have that swap helper function okay let's go back up to reverse vowels so again after these two while loops finished now the left and right pointer are at valid vowels and we got to swap them thankfully we have the swap helper function so I'll say swap and takes in the array when you swap with so I'll pass in characters so swap characters and it needs to be provide two valid indices to swap with I and J here would be well left and right and of course we're in a while loop we want to make sure that doesn't run on infinitely so I'll say left plus equals one and right minus equals one okay so now our characters array right the vowels have been swapped around but we need to return a string back so let's turn our array where we just swapped all that stuff around we got to turn this array back into a string and to do that in JavaScript we'll use dot joint on the array so I'll say return characters join on an empty space all right so now our characters array with everything that has been swapped is now back into a string and yeah we should actually be good to go so I'm gonna copy everything harro delete code paste it in make sure it works passes their tests all right great it does so was the reverse ballast complexity analysis time complexities of n where n is the number of characters in a string now it's important to note that a lot of times if you're new to programming or you're not really familiar of while loops it's easy to think that hey nested while loops are you know it's like quad dragged or cubed time complexity but notice that these inner while loops only run while left is less than right so worst case all these loops go over every character in the input string both n at worse right so that's what we got that all then time complexity and space complexities o of n because remember we have that characters variable where we turn the string into an array and that is the same length as the input string so oh then space complexity alright that should be it for this video | Reverse Vowels of a String | reverse-vowels-of-a-string | Given a string `s`, reverse only all the vowels in the string and return it.
The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once.
**Example 1:**
**Input:** s = "hello"
**Output:** "holle"
**Example 2:**
**Input:** s = "leetcode"
**Output:** "leotcede"
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consist of **printable ASCII** characters. | null | Two Pointers,String | Easy | 344,1089 |
213 | hello everyone I hope you guys are doing good so today we'll be discussing another problem of a blind 75 series problem 230 House robber 2. so I hope you have seen the video of problem House robber the problem that I have covered just before this problem just has a simple deviation from house rubber in this problem we have been given an array nums let's say two three two and the value at each index of our array tells us the amount of money stashed in a given house in a neighborhood and we have been given a few conditions to Rob all of them and we have to tell the maximum that we can come out after robbing the entire neighborhood so the conditions given are we cannot drop the ages in houses so ages and houses cannot be wrong and the neighborhood is just like a circle that means if there are three houses they are like one two and three so what this does is now the first house is the last house so even if while solving a problem in house rubber what we did was we simply calculated this plus this and said that the max that we can come out from the neighborhood is equals to four but now as this is a neighbor of this or the first house is the last house let's say the first house second house third house so house three and one they are both actually neighbors so they are adjacent so we cannot Rob these houses together so now our solution becomes this so I'll just we have a simple example or just a simple trick that would help us solve this problem using the same logic using the same approach that we used in solving house robot so now let's say we have a neighborhood and let's say we have one two three four and five houses in the neighborhood and now we start robbing from this house let's say this is the first house and after solving uh after solving the last problem cops robber problem we know that there are only two scenarios that we either Rob house one this let's call it R1 and then we rob this house or the current house and either we keep on our maximum amount just by considering that no robbing House 2 is more profitable than robbing both of the houses this was a condition for house robber and we can simply apply the same condition if we divided our problem into two arrays which would be the first scenario would be we'll start robbing from the second house and keep on robbing till here this will be one of our arrays and the second scenario would be we will start robbing from the first house and we'll keep on dropping till here so by doing this we avoid the condition that the first house will again be the last house so we cannot drop the first house in the last house together so simply what we have to do is first will Define a helper function will be the same that helps help this solve the problem House robber and this will only take an array let's say and what a helper function does is it calculates let's say R1 comma R2 R1 and R2 are robbing house phone and robbing house two similar as we did in the problem House robber and now we'll go on traversal array for let's say n and array will say and keep note of a temporary variable that will be maximum of either one plus n or R2 then we'll set R1 as R2 and R2 as the temporary variable and just return R2 and now we come to the mean part of just switching our solution and now what we have to do is we have to return either you have to return the maximum of either uh self.helper function okay uh self.helper function okay uh self.helper function okay with numbs houses of index one and above now we are not considering the house at index 0 so we are avoiding the problem that the first house is the last house which would make both of them adjacent or what we can do is we can calculate self.helper and now we'll not go or consider the last house just let me put this down here and this third case or the final case because what if we have just a single house for that we'll be considering numbers of zero and let's try and run our solution as we can see this is a pretty efficient solution I hope you guys understood thank you and have a nice day | House Robber II | house-robber-ii | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[2,3,2\]
**Output:** 3
**Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
**Example 2:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000` | Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved. | Array,Dynamic Programming | Medium | 198,256,276,337,600,656 |
1,759 | all right let's try uh and um medium difficulty problem count of homogeneous substrings given a string as return the number of homogeneous substrings of s since the answer may be too large return it modulo or something a string is homogeneous if all the characters of the string are the same a substring is homogeneous if a contiguous sequence of characters a substring is a contingency no so uh question is what given a string number of homogeneous substrings so in this case a BB CCC and a but okay it says 13 because okay individual one also you count not some largest or anything so yeah one a yeah you get the idea X Y has two GTG has okay of length one of length two of length three of length four of length five um okay why is it 15 uh is it do they matter from the like does the index matter so let's see uh y this is considered to have five different homogeneous substrings I would just consider this as a substrings but maybe it's looking at indexes so it first is just one length so zero one two three four and then two length will be um zero one and then okay you get the idea right zero one uh Z oh sorry uh one two three four and I know length three so now it's changing to of length one you have five of length two you'll have one uh one two okay so starting from one till starting from this so basically four of length three you will have three a plant four you will have two of length five will have one and if you sum all of it five plus four nine three twelve to fourteen one fifty all right get the idea so but if you get the pattern then the length of the pattern is in the length of the pattern it's you get you like this can be metaphor right it's another pattern is five then it's five plus four plus C plus two plus one this is better than six and six plus five plus and so on so which is okay uh like uh what and then plus one or n minus one by two right so if the length of pattern this and then basically sum of one to one right uh so that is fine now to find all these different patterns let me just quite basic again um you see when your character differs right nothing else so uh okay so you do alone one is your initial count equals to zero and then four uh yes maybe we have two pointers of course zero J starts with zero as well maybe just start with one okay and then you go to while I preferable let's try guys J is less than store length what exactly do you check uh JS character with the ice character or maybe just the previous guys character so if uh start carrot J is not equals to start carrot I then count plus equals to okay so first you count may be n or can I say n equals to M minus J here also G minus I rather so for example zero and one in that case let me one yeah so J minus I count equals to n times the minus 1 by 2 okay too many of this but five yeah okay too many brackets but yeah so there you get this count plus and then now you do is uh your I becomes J and uh right becomes J that is fair and V2 J plus every time so does this make sense so let's do ABCD right so your iOS 0 uh your J starts with one and obviously again I do not match so uh so you get one and then now your js2 I is one okay JS is 3 I is uh two okay I think there is one problem so okay so we're looking at in case of ABCD you start with i z i and J uh so you start with is 0 and js1 and for J equals to 1 um you do a sum which is fair by J equals to power J equals to 2 we do one another for J equals to three for J equals to four the volume is breaking you come out uh but you have to do this thing again right one more time like a case of Case of uh all Z is easy right so uh everything will match so your I will be zero your J will be by zero one two three four which will be five right because you'll become out in zip will be five so yeah so you do this uh one more time essentially outside the while loop as well and then you do just uh click on your account that's an example just cases and see if they pass oh you got the wrong answer okay let's see if it turns around so first one process 13 we got 13 second one answer is 2 we got two oh no this is expected so we got five zero and ten but it was 13 2 and 15. I think this X Y where we got zero is a trick is a problematic one so let's think about this X and Y again okay so yeah all this is good we compare ybx and when we compare by the Dax We compare y with X they match they don't match okay so n is one count is equals to 1 times uh okay so that's a problem here um it does not works counter thing does not work for Land one is it okay so also length two fifths there that the answer will be okay of length one and of length two so one plus one two so is the okay so for five we are saying five times four by two which is 20 by 2 which is 10 even that is from okay so it's an N plus one by two then five six flag two yeah okay so it's not n and minus one it is n times n plus one so for one it will be 1 times 2 by 2 okay now submit all right we get around oh okay so there was another bit around uh the answer will be too large okay to modulo this foreign just here but okay let's see thank you okay possible velocity conversion from double to end thank you and your wrong answer again foreign we want to try one more thing which is this I can do a personal mode here as well to see if that helps it's just not going to help her foreign is that the only one that does not work okay I guess this is a tricky one it is taxing the limit only nothing else logic doesn't seem to have any problem as such uh foreign so 10 to the power 5 and uh now how much answer you can get after the power five Okay so foreign okay so in modular you want uh 10 to the power 9 plus 7 I guess okay so the mod it does not understand mod but so let's copy a command what do I do okay so this oh not this I want to 10 to the power 9 so 1 2 3 4 5 6 7 8 9. and then it's over nine plus seven okay calculate the answer is four double nine six five and what you're getting seems to be not that um yeah there's a problem I guess then uh let's print this yeah it's sort of sure not only I guess why it's pretty like that if I make it's just it can it not begin it will come tonight yes okay so this is fine how about I keep the counters into only and uh how about because my okay I am how about I print what the value this is so maybe remove other percentile more is gone foreign but that's not even the right answer so what's happening is something weird that's what is happening uh I guess it's n plus 1 by 2 that calculation devices but here this N I suspect this has to happen like a double Maybe uh okay you might count as double again and that's that makes sense or because the answer itself is wrong right okay yeah so it was just stupid okay let's do this basically this another person by 2 was using as an integer and that was causing problems okay | Count Number of Homogenous Substrings | find-the-missing-ids | Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`.
A string is **homogenous** if all the characters of the string are the same.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "abbcccaa "
**Output:** 13
**Explanation:** The homogenous substrings are listed as below:
"a " appears 3 times.
"aa " appears 1 time.
"b " appears 2 times.
"bb " appears 1 time.
"c " appears 3 times.
"cc " appears 2 times.
"ccc " appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
**Example 2:**
**Input:** s = "xy "
**Output:** 2
**Explanation:** The homogenous substrings are "x " and "y ".
**Example 3:**
**Input:** s = "zzzzz "
**Output:** 15
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase letters. | null | Database | Medium | 1357,1420,1467 |
1,420 | hello friends today I'm gonna talk about new Dakota 14 2002 array where you can find the maximun you can Center the K comparisons the party that you are given also of my operation our code that is trying to find the maximum value and the corresponding medicine the index for meat and co-ceo walls is a search cost meat and co-ceo walls is a search cost meat and co-ceo walls is a search cost which is x-rays or number of comparisons which is x-rays or number of comparisons which is x-rays or number of comparisons you need and you are given all you need your K and M and K and user name and the names of the way M is the maximum value you need your videos there for each element in the array face so it's caused the number of comparisons to find the medicine man index and based on the conditions you're gonna find the number of ways to few days away here is an example here and you go to a ministry hey everyone we have the 1 comparisons and the element I was already he's one of trees and the names of the radius is 2 so we can Chaeronea her with the element from one from 1 to 3 there are six possible ways to come to constrain the array and other cases now there's make him father is actually his power has a problem here and because here for example we have one two and three after meketa why this kind of our house oh she has a two three there is a sub problem here and the 1 for 3 with a number of ways we are we depend all the number of to 300 here and also the K is also has the okay is a comparisons and University pens ok - oh I assume we have ok now it's about - oh I assume we have ok now it's about - oh I assume we have ok now it's about the started and enter here you have N and M oh yes and you forward we wait on the north consider K here if there will be the how many number of ways to cut all the way hmm there will be the m house M because she should be the UH eg element have M so it should be the mm house and his body he element you Germans should have the M values to fetch you so mm harren parallel we have to consider the K here for a consider case you wish we should consider the man some values here and we all were already found that for example he always we hope will always equal to 3 and you will have the sweet and which is the maximum value which if we place it in the for separation so and 7 develop for the two for the second position so this is will have only one comparison in water so the melt value is worried we've decided and how many conventions we need and so it's actually the maximum value within days and for example here we have raised a very heavily and - over we have raised a very heavily and - over we have raised a very heavily and - over here and also LEM numbers if m and nor am i and the number is dividends yes we that is me that way and we have to have a nice toe one more comparisons in Walter if I numb is less s is necessary when we add a number numb in through this way to construct our various names three we don't here we do need to add comparison time times again we have to find out where we have the current and maximum so far for each element and also we have to construct her for you see her meant for one who to M be where we are going to you see because you shittin number clarity joke Madison month so there are these ways to the conservative know the answers so basically we can't define or functionally that the current leaders and also community and also the kind okay - one time okay - one time okay - one time okay and also the kind of mess for me we have ten pasado a three dimensional ways freedom you know Masuda many ways to consolidation function father tanning program in programming and I'm here I'm according to consider the Tabata mastered with the memorization appeal so we have define of TIF our recursive function of here mmm because your function for example called help or have evolved kinder the array index and also the kind of hi mags and also so it cost okay there is here as a retirement and so you know where depends on that hook there are two cases the foster case is that now here is before you seek kinder for any kind and number in the array that is smaller than a character max if a smaller analysis way to know needed to as an addict here again which aster and there's the one universe class 1 and the second case is that you for the lamb with every number in the array is bigger than kinda medicine now so literally we are steep it will also need to but decreases the criminal as well everyone on this so basically hmm this is a recursive way how I consulted hmm the recursive function for TP and if we have these three element for the making used as the mobilization so based on this idea we consult the way how we program it so let's program into so first away define initialization here which by the help of a machine I kinda nested we can start from n to 0 and minus 1 to 0 so which oh so here we can use in there's a minus 1 you know evil wait sorry dances from down my minus 1 to 0 your as well we were sorry from 0 to n minus 1 as Singapore Zoo work here with constructor in the mix and also the such cost there's a cluster and that is a cake and also the time to m and D P for the memorization so we get the chair the titleist whether it is already with a kid a lot and give a tip yeah GPR unit EP because return it if he are for the memorization and secondary which has a mcconnell base case without the base case is that why that you've already nurses or only one and also the costly for a while well written Jeremy data we have one element wha wait to select X otherwise it was the dance is y by the caustic will be 0 return 0 oh you've got cost equal to they were always very return 0 because we cannot have more comparisons that is we cannot construct way animal so number always input 0 anyway the finally because your way means that from one to him em and then you for the cartel Valerie's smaller than the max and here that is wait chief justic raises our money - no - wha raises our money - no - wha raises our money - no - wha no need to decrease the cost otherwise we - craziness and also decreases the we - craziness and also decreases the we - craziness and also decreases the cost of Iowa and they put this result in - yes and return Tyrell tight there is letter away how to get choose easy an element as maximum for the first operation you know kind of contractual ray next will be the hem and kind in the J this it cost this heavy though okay I'm DP and then we get home answers he always just readin that because the arraignment could be the mass memory where we cause rather away from spittin left to right for the first element we need to copy the maximun the second mm anubius has no game for the new conservatory so we have this four loop over here okay something is below clear oh I didn't know how to tell you know kind immense and stay is bigger than so it's in serie de noche is bigger than kind man so kind of magazine has already changed so it's J now okay yeah we made it | Build Array Where You Can Find The Maximum Exactly K Comparisons | find-the-start-and-end-number-of-continuous-ranges | You are given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
* `arr` has exactly `n` integers.
* `1 <= arr[i] <= m` where `(0 <= i < n)`.
* After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`.
Return _the number of ways_ to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer **must be** computed modulo `109 + 7`.
**Example 1:**
**Input:** n = 2, m = 3, k = 1
**Output:** 6
**Explanation:** The possible arrays are \[1, 1\], \[2, 1\], \[2, 2\], \[3, 1\], \[3, 2\] \[3, 3\]
**Example 2:**
**Input:** n = 5, m = 2, k = 3
**Output:** 0
**Explanation:** There are no possible arrays that satisify the mentioned conditions.
**Example 3:**
**Input:** n = 9, m = 1, k = 1
**Output:** 1
**Explanation:** The only possible array is \[1, 1, 1, 1, 1, 1, 1, 1, 1\]
**Constraints:**
* `1 <= n <= 50`
* `1 <= m <= 100`
* `0 <= k <= n` | null | Database | Medium | 1357,1759 |
1,218 | hey what's up guys chung here again so today let's take a look at this uh problem here uh number 1218 longest arithmetic subsequence of given difference okay another array problem here so you're given like uh an array here okay an unsorted array okay it could be either zero like uh any integer basically and another difference here so it asks you to find the lung the arithmetic subsequence so what's the arithmetic subsequence um so the arithmetic subsequence means that you know for example if the difference is one okay basically the next number right so the next number in this subsequence should be uh equal to the previous one plus this difference okay basically that's how it's example here how he explained this which is an arithmetic subsequent such that the difference between okay so this is better so the difference between adjacent elements in the subsequence equals difference okay so for example this one you know there's a one two three four so the difference is one so which means this one should be so the difference between each of the eight adjacent elements should be one in this case it happens to be all the numbers basically one two three four that's why the longest subsequence uh is four okay how about this one right so for this one you guys as you can see the difference between each number each like adjacent element is instead of one is two that's why the output is one so this one tells us the minimum answer right for this problem is one okay basically no matter what's the difference here which the number itself should always count as a subsequence okay and uh this one yeah and so the difference can also be an active which means it's going to be a decreasing number so in this case it's going to be a seven five three and one okay so and they ask you to find the longest ones um cool and uh yeah so the input length is a 10 to the power of five okay this thing is like uh the number range is like also 10 to the power of 4 okay so this one this constraint tells us you know so our algorithm should be either o log o n or n log n okay um okay so i mean every time when we see like this kind of problem you know it first okay so it asks us to find the longest the sorry where is that the longest okay and i think the first thing i mean i'm going to try is can we solve this with a binary search okay um so remember the binary so the binary search is the uh we search the answer let's say we search the number okay that's the longest one can we solve it right so the binary search probably not right because you know for the binary search you know your helper functions has to be uh either increasing or decreasing okay but with this one let's say we uh basically let's say you if we're searching the k is the longest subsequence okay and then we're trying to show with this like k is the longest subsequence can we find such thing can we find such sub uh subsequence that has like this the length of k whose difference is this difference i mean if we can't find it right it means that we have to go okay let me think um i think binary search is doable but the issue for the binary search is you know for the so let's say assuming we're trying to use a binary search so basically the helper function what it does is with a given length right with a given length k is a given length k can we find a subsequence that exists in this that has the length k okay so in order to find that basically we have to loop through odd array here okay we have to look through other array from the first one to somewhere here right and then since it's a subsequence right we have to basically for each of the element here we will try to find if there is like a subsequence with the length k if this one if the first one let's say one doesn't have it then we need to move two to five and for each of the loop here right we have to go through all the elements all the way from starting to the end then we can make sure okay one doesn't have a subsequence uh doesn't have a k line subsequence starting with one okay and same for the same thing for the five seven and for each one of them so the time complexity for this it's gonna be a so for the hyper function itself it's gonna be a n square right plus the plus binary search is going to be n square log n okay this will definitely tle given the uh our constraints here so i mean the binary search is definitely doable but it will not pass right so which means the binary search is not one of our options then what's gonna what's uh what's other our options are other options so with this like constraints we can certainly think about dp right so basically you know for this problem you know the dp is a little bit different because the way this dp works is instead of using like a array here right we're going to use a hash table so why is that because of the range of the numbers here you know since the uh so basically the dp we're going to define it here is that we're going to define like the dp sorry dp i means right uh dpi means that uh this number right sorry this like number i ending the last element is this i and what's the uh what's the length what's the maximum length right uh of the of a subsequence that ending with this number i okay who's uh the difference it is one so that and every time when we have like a dp so that the dpi minus one equals to what equals to uh the dp uh sorry the one plus dp uh i minus difference right yeah so basically that's going to be our like uh the state transition function here so why is that because let's take a look at this one so at the beginning right so dp one means like one and also since we're storing not the index right since we're storing like the numbers here right restoring the number itself and as you guys can see the range of the number is like it's pretty big that's why we cannot use a db here because sorry we cannot use a list here instead we need to use a hash table to store our like dp result so basically you know every time we have the new numbers here we'll try to look for basically if this number uh our target number okay so basically this i minus difference will be our target right gonna be the values we're trying to use basically if this one it does not exist okay does not exist in the hash table right basically we will uh we will store we'll store this one to the hash table with the value one because the number itself will always uh has one length right and then okay so basically when we have one here right we have one the uh um so when we have one here the target is dp uh one minus one which will be zero which means the tar the old data we're trying to use is not there that's why we're gonna store the dp one equals to one okay and now we're at two here so the dp2 okay so the dp2 we're trying we're looking for one right because we know in order to make this subsequence arithmetic for the current two we need a one and so that's why we're looking for do we have a one in the hash table yes we do right that's why we do uh and then we just do this one plus dp one which is two okay same thing for dp3 okay then three and then four okay and yeah so that's for this one and every time when we have a new numbers right we have a new number so i have a new dp numbers we're trying to update our final answer why is that because you know the uh the longest substring the sorry the longest subsequence might not be at the end of the uh array so we should so that's why we need to keep updating our final result every time when we have a dp value here so same thing so let's go over the example three here one more time so with one here right so with one uh the is one d at what the uh the target is one plus two which is three which does not exist in the in a hash table that's why the dp1 is one so the dp1 is one okay so for five so the five is the uh five plus two is seven right it's not also it's not in the rdp hash table so this one is one seven is also one right because for seven we're looking for nine okay so for eight we're looking for 10 which is not in the dp so still one so but now right let's see now we are we're looking we're at five here one again right but for five now let's it will try to look for seven again but okay at this time seven is isn't it's in the hash table okay that's why at this moment five is two okay and then when we add three here we're looking for five is also in the hash table which uh whose value is two then the three has three here four we're looking for six it's not in the hash table so it's one two we're looking for two oh sorry for two we're looking for four right and the four is in there so two is two and one we're looking for three is here so this is four so in the end the answer is four cool yes i think that's pretty much the uh the thinking process and let's try to code these things up here so a few things here and array okay and then uh so we're gonna have like a hash table right and so the hash table is the length right so uh how can i name these things there's gonna be a well i'll just call dp sorry about the name in here i'll just cut the dp and also we need that answer here equal to zero okay so now for a number right for number uh for number in uh in array okay so the target is what target is this target is the uh the number uh miners uh difference right okay and if target not in dp okay then we know okay this number it's a single number right which means it has it should have the length one okay so that means dp uh remember it's not target okay it's this number itself right it's number not the target uh equals to one okay else dp number equals to if the target is in the dp then we can simply use that right we use a one plus uh dp uh target okay and then in the end we simply update that uh yeah sorry about that it's my uh rice cooker yeah it's lunch time for me so yeah okay let's continue uh so answer equals to max answer dot p num okay and in the end we simply return the answer okay so this should just work let's try to run this code yeah so this one passed submit so it passed all right so it's a and it's pretty interesting like dp problem you know and the only difference is they are we uh we don't do a dp we don't pre-populate we don't do a dp we don't pre-populate we don't do a dp we don't pre-populate the dp array here like what we did before like the end here like the something like this okay right the reason being is that the key the thing we're trying to use here is the uh um it's a number itself right it's not the sequence basically right it's the number itself that's why because the target we're looking for is a number plus a difference which this target could be a huge number right because the difference and the number itself could be anything so that and when we use this target to find the uh the previously calculated value for this target we cannot use like the dp uh we cannot use like the list here instead we should use a hash table okay and the space and time complexity right so pretty uh obvious right this time complexity is the uh o off n right because we are only looping through the uh the arrays one the array wants and the space is also uh o of n right the length of n because we'll be storing up to ends number in this dp hash table cool i think that's pretty much it is for this problem yeah and thank you so much for watching the videos guys and stay tuned and yeah i think i'll be seeing you guys soon yeah time for lunch for me alright bye | Longest Arithmetic Subsequence of Given Difference | lowest-common-ancestor-of-deepest-leaves | Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`.
A **subsequence** is a sequence that can be derived from `arr` by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[1,2,3,4\], difference = 1
**Output:** 4
**Explanation:** The longest arithmetic subsequence is \[1,2,3,4\].
**Example 2:**
**Input:** arr = \[1,3,5,7\], difference = 1
**Output:** 1
**Explanation:** The longest arithmetic subsequence is any single element.
**Example 3:**
**Input:** arr = \[1,5,7,8,5,3,4,2,1\], difference = -2
**Output:** 4
**Explanation:** The longest arithmetic subsequence is \[7,5,3,1\].
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i], difference <= 104`
The node of a binary tree is a leaf if and only if it has no children. The depth of the node of a binary tree is the number of nodes along the path from the root node down to the node itself. | Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer. | Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | 1816 |
1,015 | Hello friends welcome to front my this absolutely smooth individual like this question Beerwah subscribe to the Page if you liked The Video then subscribe to the Channel subscribe and subscribe this Video I will never get rich and organized The Video then subscribe to The Amazing Limited Number of Women subscribe 0 subscribe The Amazing Loot-Loot subscribe The Amazing Loot-Loot subscribe The Amazing Loot-Loot subscribe Video subscribe Kare Candy Crush Kuna Family Thursday subscribe this Video subscribe Video In Between There Eggs subscribe and subscribe over all the world this video subscribe To Pimple One Can Be Done 0 Vidron in subscribe Video then subscribe to The Amazing subscribe Video subscribe The Channel and subscribe this Video give a recommendation Web value added in the current multiple of a Danish Mallick return - 52 है - 52 है - 52 है अदर्विज मुनिट यू है ए प्रीविजी मैंडी टी आम तलू ओबर्सुस्क्रिबे टो में अदर्विज मुनिट यू है ए प्रीविजी मैंडी टी आम तलू ओबर्सुस्क्रिबे टो में इंग्लिश समैंट JOIN 210 इंग्लिश समैंट JOIN 210 इंग्लिश समैंट JOIN 210 A Plus One And Finding A Model S Of Now Give This Cream And See Less Tum To Biji Raho Ho Divine Have Find The Value Wishes Otherwise Very Little Subscribe Without Toe's Sweater Height Pawan Love Status For 269 Midcap - Unmukt S 269 Midcap - Unmukt S 269 Midcap - Unmukt S 123 Garima Relationship Report Submitted Successfully with Some Cases of Balancing Complications of U Ajay | Smallest Integer Divisible by K | smallest-integer-divisible-by-k | Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`.
Return _the **length** of_ `n`. If there is no such `n`, return -1.
**Note:** `n` may not fit in a 64-bit signed integer.
**Example 1:**
**Input:** k = 1
**Output:** 1
**Explanation:** The smallest answer is n = 1, which has length 1.
**Example 2:**
**Input:** k = 2
**Output:** -1
**Explanation:** There is no such positive integer n divisible by 2.
**Example 3:**
**Input:** k = 3
**Output:** 3
**Explanation:** The smallest answer is n = 111, which has length 3.
**Constraints:**
* `1 <= k <= 105` | null | null | Medium | null |
1,071 | Hello friends today I am going to solve liquid problem number 1071 greatest common divisor of strings so in this problem we are given two strings string one and string two and we need to return a larger string X such that the string acts divides both at string 1 and string two so this problem is actually a greatest common divisor problem in the form of strings so let's look at this problem with some examples all right so what is the greatest common divisor suppose we are given a value 3 and a value to two integers what's the greatest common divisor of these two integers well it's equals to one now let's suppose we have a string of length three and of length two suppose the stringy is a b c and the next string is AP then the greatest common divisor is of course one but are these two strings um does this two string has a common string that makes the both of the string well it doesn't have any common string right the only thing common is a b and a b but this C is not present in this string so basically there is no such string X which could divide both of these strings equally so what about if we have something like a and another string a and a so of course we can form a string of length a length one which consists of only the character a which you divide these two both of these two strings right so it would divide this um in equal three parts and this in two parts so basically this length we get it from the greatest common divisor so that is what we are going to do we are going to find the greatest common divisor of the length of these two strings and then that grid is common device that length would actually be the length of the string X and the string X would actually be the substring starting from 0 to the greatest common divisor so let's look at this example this is of length 6 and of length 3 right so we have six and three now what's the greatest common divisor of both of these well we just know by our intuition that's three right because 3 would divide 6 and it doesn't give any remainder the remainder is 0 and 3 divided by 3 is equals to zero I mean equals to one the remainder is zero right so three is the greatest common devices so now that we know the length of X so the length of X is equals to 3. now what's the string X well string X is the string starting from length uh index 0 to index three well we are not going to include the last index but definitely the index 0. so this length of either of these two strings because that divides it equally right so if we take 0 to 3 what's that string of course it's starting from 0 1 and 2. so this ABC is the string right in the same case they took this string also it would be the same a b and c starting from 0 1 and 2 and not taking the character on the index three so this would be our string X and that is what we are going to return now that we know we understand what this problem is let's try to code this solution so we will we are going to need the greatest common divisor for these two strings so let's first of all take the length of the two strings now that we have the length let's define our greatest common divisor function which takes the length to length x y and if the length of Y is equals to zero then we are going to return X else what are we going to do is we are going to call our gcd function again with the values Y and the models of X with y and then finally return the value so the greatest common divisor would be equals to the gcd called upon the values MN and then we are going to return the value of string um starting from string one um and we are going to slice the string starting from 0 to our division so the slice it actually slices from zero to the element before this index so that is what we want now we are missing one thing here what a if these two strings are not equal right and in the example that I showed you a b c and a b these two strings are not going to have any greatest common divisor like it's not going to have any string X that would divide both of these string so how do we know that this case so we could know this case just by like concatenating the two strings so if you concatenate string one and string two and then string two and string one what is the result well this results in a b c and this results in a b c a b so these two strings are not actually equal right so that is when we know that we do not have any um greatest common divisors so we are going to check if string one plus string 2 is not equals to string two plus string one then we are going to return an empty string why don't we do it in the first place so that all right let's throw run our code cool let's submit it so time complexity is O of n | Greatest Common Divisor of Strings | binary-prefix-divisible-by-5 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. | Array | Easy | null |
43 | okay let's talk about multiply string so in this question it's so hard to explain and i've tried multiple time recording the video but think about it like when you want to convert to a two individual string right you actually cannot convert the entire uh string to integer at first because you are in a stack overflow so the problem is you convert a single integer a single string single character into the integer and then you do the multiplication and then you come very bad so that's how it is so let's give this guy credit for graph and he actually explained pretty well so imagine you have one two three and times 45 right so you do a multiplication of 3 times 5 15 2 times 5 is 10 and then 1 times 5 is 5 right so another i mean another index is 4 times 3 is 12 4 times 2 is 8 and 4 times 1 once four so you end up in this problem right what do you mean in this problem is that um you are going to have a result of integer array for this uh list result right these two multiplication results right so you're going to have the maximum possibility that you can end up with so you're going to say the length of the one and then plus the length of nums 2 will be the greatest right so imagine nice 999 times 999 right so you will you know that the maximum is 5 index right so this is how it is and let's think about how you how do you actually do it so uh when you're doing this right eight plus one plus five plus one you will end up more than ten right you need to carry one everyone before you right so this is how you actually that you can actually store your position that store your carry into the position of p1 i mean imagine this let me imagine p1 i will use the same variable later so let's see so this is p1 this is p2 so p2 will remain uh what will remain less than 10 so which means um i will mod 10 later and i will divide by 10 for the carry and then when you just add this index i mean uh add this number into a solobill final solution okay let's just stop holding too much topping and let's see so i'll say in m equal to nums one that lens and equal to nums to that length right it will be the idea position ideal solution so the position the in the array the result will be the maximum and plus n right so i'm gonna start from back so i'm gonna start from the back right so that would be like this right and this one j plus k j minus my so this is pretty standard right so i do need to do the multiplication right so let's just go more mult okay so i will say m one that shot at i and since it's characterized i need to make sure i subtract by 0 then do the multiplication for numbers 2 and this is j sorry and they will subtract character 0 so how can you actually know p1 and p2 so p1 is definitely before p2 right in this example p1 is before p2 so when you have plus one it's definitely p2 so things p1 will become i plus j and g2 will become i plus j plus one this is how it is and we have a sum so what was actually equal to sum so sum is equal to um okay let's initial is multiple right but it's actually you need plus the carrier which is uh which is p2 so imagine that you at least you're at least uh a list rule right you need to add the value for this column right so in this column you end up adding i mean that will definitely add right so in this index it's actually seven it's not one so one plus five plus one is seven right so we when you do at least multiplication you obtain that a plus seven so that would be there will be position at p2 right then what you actually need to do is that you need to say position py is equal to plus equal by the way plus equal to sum divided by 10 right i just said it and p2 will become some 10 this is actually um you don't want to carry over 10 to 2 p1 so p2 is 15 right now you agree with me right a plus one nine plus one ten plus five is fifteen so you wanna carry one into p1 but p2 should remain less than ten so which is five so this is why i say p2 is sum mod 10 and p1 sum divided by 10 and then you need to just keep adding so this is what is plus equal you are no longer the p2 for plus 18 and plus equals right so that would be your solution so what should i return i should i return the stream right so i need stream builder i will say speaker to neutral builder and what happens if okay so the maximum possibility the maximum length is n plus one what happened like folks always just for this example if the index zero is zero but in this one should be nine i mean in this case should be four right five sorry five in this one is five right but you will have zero before the five right so you can actually uh use the check function so i mean check boolean so i will say single to false i'm going to traverse the entire uh entire numbers in position and hit p equal to zero and not seen so since four right at the end if since first i can just continue and so if i know the first index is zero and i'm didn't see the number yet i would say continue if i do then i will say symbol to true and then i will append sp.n the number which is sp.n the number which is sp.n the number which is p ref and they just return specifi.2 so what happened the sp that specifi.2 so what happened the sp that specifi.2 so what happened the sp that tuition is zero so i mean the length is zero so you just return zero so sp the length equals zero uh you will just return string 0 all this way you will return the entire string so let's just run it and see what happens so this question is pretty hard so i passed so let's talk about time and space so in this question the worst case for the time like for example this index i or i mean j sorry j times three times for the uh three times in number one right so every single integer has two times uh another string index integer right so which is n times n is that boolean is that brutal force right and so that would be the time capacity and same as the space complexity say the space complexity will be m plus n so it's not at times but it's n plus and they are going to be the maximum amount of integer you can actually store into a result so n plus n for the space and m times and for the time capacity and this one is hard then don't worry about it i don't actually memorize it or get familiar with this kind of question just keep practicing and go | Multiply Strings | multiply-strings | Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string.
**Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly.
**Example 1:**
**Input:** num1 = "2", num2 = "3"
**Output:** "6"
**Example 2:**
**Input:** num1 = "123", num2 = "456"
**Output:** "56088"
**Constraints:**
* `1 <= num1.length, num2.length <= 200`
* `num1` and `num2` consist of digits only.
* Both `num1` and `num2` do not contain any leading zero, except the number `0` itself. | null | Math,String,Simulation | Medium | 2,66,67,415 |
171 | in this video I will solve it called problem number 171 excel sheet call number so we are given a contact o as appear in an Excel spreadsheet and we need to return its corresponding column number so this problem is the same as converting number from base 26 to a stand so let's look at some examples for example a B to convert it we will just multiply a by 26 and then add B so I mean we will multiply 26 by a which is 1 and then we will be which is 2 and we will get 28 let's look more complicated example for example something like this to convert it we will need to multiply first digit of this number by the cube of 26 then multiply second number by the square of 26 then we will multiply third number by the first power of 26 then we'll add the last digit so we can write the same thing 26 times C + H so looking at this formula we can see that at each iteration we will multiply our temporary number by 26 and then we will add the current digit so we can write a loop to do this let's write this loop so we'll declare result and then 4 for each char C in our string s we will do this we will multiply a result by 26 and add char - the code of result by 26 and add char - the code of result by 26 and add char - the code of a and plus 1 so when we subtract code of char a from our current char we get the number of this char but starting from 0 so for example if we subtract the code of char a from char B we will get 1 but we will need 2 for B so we'll add 1 here and then at the end you just return the result so let's check our solution now Oh out we gave us overflow so the result Inc number is very long so we can use unsigned long for the result let's check it once again ok now it was accepted the problem was the type of our result it was too small for this problem so we change it with unsigned long guys please subscribe to my channel and ask me to solve other league code videos and thank you for watching if you have any questions feel free to ask in the comments below and also if you need the codes problem asked me to post the link to my code thank you | Excel Sheet Column Number | excel-sheet-column-number | Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`. | null | Math,String | Easy | 168,2304 |
203 | hey everyone and today we are going to select a little question remembering to this elements so you are giving head of link to this and the integer bar remove all the nodes of the linked list that has node bar equal bar and returns a new head so let's see the example so you are given one two six three four five six and the bar is six so we have to remove the value 6 from input link to this so in this case we have to remove these six and connect from two to three and then we have one more six so remove D6 and connect to new from five so like this and then yeah um very simple questions so let me explain how to solve this question before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the right button or leave a comment thank you for your support okay so let me explain with this example one two six three four five six and then we have to remove six so to solve this question um I create a like an answer node and a pointing the head which is one and also I create a dummy node and uh I copy answer node to Domino so dummy node also pointing head so the reason why we use the like a answer node and the dummy node is that so basically we iterate through all nodes one by one with Domino so now hit head is here so if um we don't create the answer node and a dummy node and then use head like to iterate through the like an old one by one so in the end we have to return the like entire new linked list so if is let's say in the end here how can we return the like an entire um linked list right so that's why um we have to stay uh at the very beginning so that's why we need an answer a node so also um so the reason why we use Domino is that so what if uh fast node is six and the head is now here so in that case we have to remove um this node but uh we are now head node so it's gonna be tough to delete the current node so that's why we need like a um before hit node so that's why we create a dummy node and pointing the hit so that we can delete fast node if first node is six so yeah let's iterate through the node and check the um next node so next node is one so we have to delete the six so they are not same in the case uh dummy node next here and again take the next value 2 and the value 6 so they are not same so just move let me know to next and then next value is six and the value is six so they are same in that case current node.next should be current node.next should be current node.next should be current node dot next so we connect like this so that we can delete this node right and then move next so move next means this dummy node Move Like an X and then take the next value so node X4 so in that case just move next and then take the next node five so terminal next and then and take next node so next node is six so we have to delete this node so last note is pointing no right usually so all we have to do is uh do the same thing this so dummy dot next should be dummy dot next so that we can pointing no and then I'll move next so now dummy node is no so we finish iteration so now we can create like one two three four five and no yeah after that um as I explained earlier uh answer nodes through pointing hit so that's why in this case uh a DOT oops next is like a DOT next means entire new linked list like a one two three four five and new yeah so that is the basic idea to solve discretion so with that being said let's get into school okay so let's write Circle first of all create an answer mode so list node and uh you can put any values so I put zero and the next node should be head and I copy on the Node to Domino answer and uh let's uh iterating the node a linked list so why and the if dummy is not no y Ummy and next so dummy has a next value and the dummy dot next are you we call bar so in the case um update dummy dot next we call dummy dot next and the next and then after that we move forward to the next node so the army equals next after that just return answer dot next yeah so that's it let me submit it yeah looks good and the time complexity of this solution should be Oda of n so where n is the number of nodes in the linked list so this is because this code iterates through the linked list once with a single while loop the inner while loop only runs when the value of next node match the given value and in the worst case it may iterate through all the node in the linked list so that's why order of n so space complexity is actually o1 so this code use the constant amount of extra space so the only extra space used is for the two pointer like an answer in the dummy which are used to manipulate the linked list and they do not depend on the size of the input to increase the original linked list is modified in place and there are no additional data structures are used so result in constant space complexity so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question | Remove Linked List Elements | remove-linked-list-elements | Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50` | null | Linked List,Recursion | Easy | 27,237,2216 |
1,594 | Loot Gaye Loot In This Video Tamilnadu Medicine Problem Maximum Nupur Ne Matrix 200 Person Me Matrix Of Information And You Will Be Started With 0 Fashion And Unique To Avoid Affordable For Children Last Point Name Addison Antioxidant Productive Work Number 66 On Confined Maximum On Top Secretary Organization Here I Do 56001 Patna Pirates Multiply All The Note Electronic Product Maximize This Positive Unit Do Deal Constraints Man Yes Okay They Maximum Of Motion Fitting Problem So They Can Have OLX Pe Pirates Ne 1999 Ruby 216 In The Middle Of A Matrix Engaged Busy Calling Remedy 25th Mahendra Sonth Willow This Window Edifice Approach Will Quit After Pulling 16 Twitter User Informative The Software Behaving Art Direction More Not Unwell Its Pure Form 5500 White Problem Vikrami Samvat 1212 Hai So Let's Thursday First Grade The Answer Is Agree Number 201 Number Unmute 15 12345 Phone Number 9483 Ko The Software Professional One For The Answer Lakhvi - Profit Net Balance At Least 500 Lakhvi - Profit Net Balance At Least 500 Lakhvi - Profit Net Balance At Least 500 600 800 Model Number Hai The Last Example Dada Host Reached Britain Government 251 person decorated top 250 unit 9000 two so let's look better clean and vice chancellor Dr phone number 3 minutes members were returning officer mintu present 269 and looted cash old age pension Kiran made 500 1000 I grade 100MB left taking not only and great number Of us in the form of the contents are based on me jaan i am a great fan more product to take care of the difficult to embark singh redhu passing now us number of columns in the election 2014 a flexi handed over to the art cultural center metro station Ramdayal Shehnai Understanding Macaroni Column Number and Current Product Wise Grade Software 2020 Mode Off Ko Anna Dhan Welcome Back Hotspot He for us Nippana on the show The End Wherever E That House Very-2 Second Breaking The Best House Very-2 Second Breaking The Best House Very-2 Second Breaking The Best Pimple on Birth and Crush Laga Words Are Not in mood to go Same to you Flash light come back to his part Bihar Loot first Ajmer-Dadar The maximum number Loot first Ajmer-Dadar The maximum number Loot first Ajmer-Dadar The maximum number of literature festival number possible So to-do list is verma-500 list is verma-500 list is verma-500 Google 200 Sudhir Record Travel Information System person Current 0000 Status Video Love Some One More Thing To Do Sexy Condition Great With Organic Numbers Where Is Pe Nishan Gaya And Number Option Person Bhi 2018 Superhit The Return Of The Day Previous Song Phir Se Saaf Kaise Function Hai A Solid Mishra Anjali Welcome To And Dub 206 Is Arthritis Loop Imo Number Will Determine The Final Product Safar 10 Minutes To Make The Video Mein Ek Ajnabi Ko Full HD Video Ton Adhik Hai Ajay Ko Hua Tha Aur Sunao Loot Kal Ke Morning Time Ghanti Hai Loot Lo Jhaloo Time Pim Aur Vivar Ke Sermon please like interview comment subscribe channel loot | Maximum Non Negative Product in a Matrix | maximum-non-negative-product-in-a-matrix | You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix.
Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path.
Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`.
Notice that the modulo is performed after getting the maximum product.
**Example 1:**
**Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\]
**Output:** -1
**Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
**Example 2:**
**Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\]
**Output:** 8
**Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8).
**Example 3:**
**Input:** grid = \[\[1,3\],\[0,-4\]\]
**Output:** 0
**Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0).
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 15`
* `-4 <= grid[i][j] <= 4` | null | null | Medium | null |
813 | hello guys welcome to my youtube channel today I am going to be explaining a question called largest sum of averages let me start off by explaining to you the question so we are given an input array a we have to divide a into at most key groups score is defined as the sum of the averages of each of these groups our task is to return the maximum possible score let's start off with some basics so K is the number of groups basically which is given to us as an input which can be found at most now I am saying that if K is greater than equal to length of a we return sum of a now why do we do so to understand this let us consider a scenario where K is equal to length of a and where each element is taken as a group now let us consider one of such groups the group has only one element so the average of the club is the element itself now the sum of such averages is nothing but the sum of the entire array so the score here is the sum of the array itself so we return this some of the early as the score now one obvious question that comes to mind is why is the maximum possible school so if we give it more thought the question is asking us the maximum sum of averages of the various groups in the array if we give it more thought we will realize that the maximum score across cases is self summer fee therefore we are sure that in this case sum of a is the maximum possible school therefore we return sum of a let us continue with some more basics let me define an array called a prime so we have a recursive function f of I comma K I will explain this recursive function ahead in the video for now there's just keep it in front of us so if let me define a prime now a prime is an array whose elements are the elements of the array a on the index I to the end of the array this is defined as the recursive function f of I comma K so now let us talk about the case k equal to 1 means we can make one group how do we make one group by considering the array that we are considering at this moment of time as a group so what will be the average of this group the average of the array B that we are considering at this moment of time is a prime its average is sum of a prime by line of a prime there has no other group possible therefore our final score is nothing but sum of a prime Ln of a prime and this is returned I would like to explain one more very preliminary concept to you that is of storing cumulative sums at the end of every index let us define an array pre some pre sum is the sum of all the elements until the eyath index including the I attend X in the array G suppose I want to find the sum between I and J both included in the array K I can find it quickly using the Spree some array it will be nothing but P sum of J minus P sub I minus 1 let me explain to you why so if you see 3 sum of J is the sum of all the elements until the eighth index represented by the blue part we sum of I minus 1 is sum of all the elements until the I minus 1 index represented by the red part if I subtract the red part from the blue part and get the green part which is a desired Sun therefore the sum between index is I and J both including the array is 3 sum of J minus P sum of I minus 1 so let's get started with the approach I have a recursive function called F of I comma key what fi f of I comma K signifies F of I comma K signifies the maximum score obtainable by making at most K groups between indexes I and Len of a minus 1 the next slide shows how to compute F of I comma K so before that I've already explained two base cases to you that is if K is 1 and K is equal to n of there is a third base case if I is greater than equal to that no fee return zero this is a very obvious case because when we have covered all the elements there is no other element left so the remaining elements there is no other element left there zero remaining elements contribute to a zero score therefore when if IE is greater than equal to ln of here there are no elements left so we simply return a zero if there are no elements left obviously there will be no remaining score therefore we return a zero now how do we compute F of I comma key FN when I say F of I comma key I am considering in the array a prime all the indexes or instead of say a prime I can also say indexes of I to the end of the array itself both as him a prime and a within a from indexes I to the end as him let me tell this again the array a from indexes ie to the end of the array is same as a prime so now let's say at any GA between high and the end of the array I will show this in the picture so see over here this is I and this the end of the array at any J from I to J minus 1 I'll make a group so see there's a group made over here the score that this group gives is nothing but the average of this group itself which is signified by X now what we left is an array a basically from the j8 index to the end of the array we have to find the maximum score of this Sri by forming at most K minus 1 groups YK minus 1 groups because one group has already been formed here by G because from the J index to the end of the array let me explain how X is computed the CX is the sum of the elements of the array a between indexes I and J minus 1 divided by the number of elements in I comma J minus 1 both included we call it square brackets Texas Exes threesome of J minus 1 minus P sum of I minus 1 this I want explained before divide by a number of elements in I comma J minus 1 when we are given two indexes the number of elements between them is nothing but the subtraction of the two plus 1 and the same logic has been applied here so there's one case that we left out in F of I comma K that is if I just make one group when I just make one group in F of I comma K it is nothing but all the elements from I to the end of the array are in one group the score of such a group would be sum of elements in the array a from I to Ln of a minus 1 both included by a number of elements in I - Ln of a by a number of elements in I - Ln of a by a number of elements in I - Ln of a minus 1 this how to compute this is already been explained before so now here is a pseudo code for this so first comes the base cases then basically from I to learn off a minus 1 I choose a G there's one part where I make the group as I had explained earlier the average of that group is added to the score and that the remaining part is computed using a recursive function with at most K minus 1 groups which is from J to K minus 1 ok so YT minus 1 because one group has been formed over here by J because the previous group first made ending at J minus 1 over here so one of the possibility is f of J comma K minus 1 plus this average let me explain this to you in greater detail let's say from 0 to I have basically from 0 to end of the array I have let's say from I to end of the array now so let's say I have index s from I to the end of the array I'll choose any J in between form a group over here and the average of that roof will be the score of this group that comes over here the remaining from J to end of the array is computed by recursive function by making at most K minus 1 groups so that's my F of J comma K minus 1 let me write this down and show this to show it becomes more clear so let's say if I have AI over here and this is the end of the array so let's say is let off a minus one so I'll choose an intermediate J here form a group over here these Co that this group gives me is basically the average of this group that is basically this and the remaining part that is from J to the end is computed by a recursive function f of J comma K minus 1 because we can now form only at most K minus 1 groups and YJ attend X because the previous group was made ending at the J minus 1 theta X therefore f of J comma K minus 1 plus this average gives us our final score for different values of J will compute the answer this way and take the maximum also the last case that I described where we make only one group we compare our answer with that case are this here the when we make only one group it's something like this so I to again learn off a minus 1 this whole thing is one group so it score will be the average of this whole array itself that is this one here we computer and we compare our answer with this value and return the answer I had already explained all the cases over here before itself in the pseudocode have combined all the cases and given a slightly detailed explanation now I will show you how to add dynamic programming to this one way is to just memorize the results so how do I am my results so basically first have to identify the dependent variables are the variables which can uniquely define subproblems in this case many problem many subproblems are computed again so rather than computing the sub problems again I will compute them once store them and then next time I am going to compute the same subproblem again i will just return the stored answer in this question the dependent variables are I comma K so now let's see how we can store overlapping subproblems before that I would like to give a further detail explanation of this again so because it wasn't so clear earlier so let us say I have indexes I to the end of the array Len of a minus one at any j IJ minus one I will stop I will make a group this code that this the score that this group gives us the average of the array from I to J minus 1 that is signified by this the F of J comma Len of a mine basically then we have in the array from J comma line of a minus 1 now see after do we have to find the maximum score in this array by making at most K minus 1 groups so this will be given by f of J comma K minus 1 so again I found a group here now art how to find the maximum score in the remaining array from J to Len of a minus 1 by forming at most K minus 1 groups that is nothing but F of J comma K minus 1 therefore F of J comma K minus 1 plus this so it is pretty simple I found one group over here to the J minus 1 this Colgate by this group is the average of the group and also I have to find the maximum score on from the g8 index to the end of the array now this is not by forming at most K minus 1 groups here so this is nothing but F of J comma K minus 1 let me is AP this last point I have to find the maximum score from the J index to the end of the array by forming at most K minus 1 groups which is nothing but F of the a comma K minus 1 therefore the addition of this gives us a score the maximum score is chosen this case is when this entire array is taken as one group in that case from I to n to the end so the average of this array is itself the score that is contributed we compare our answer to this that is this and return the final answer I think now this is sufficiently clear let us get back to our memoization so as I told earlier the dependent variables here are I am T hi NK so let us see how I store and return overlapping subproblems let's say if I comma K is in dB it implies for this int I have already solved the problems and store and EP so I can delicately return DP of I comma here at the end of the function Funko iconic a five-week iconic e I store the result a five-week iconic e I store the result a five-week iconic e I store the result with icon Marquis in a say in a dictionary called DP so basically for next time I want a result for I comma key that is in the dictionary I can access it from the dictionary so this last point let me just repeat for every icon my I compute the answer store it in the dictionary next time when I see that this icon McKay is present in a dictionary already it means I've already compared the answer so I return DP of I comma K simply so this part is if the result is already there then return it that is if I comma case and DP then return it at the end of the function based on I come up here I store the answer each time which helps me in this it is basically stored storing the results basically I think it's pretty clear earlier the next approach that we have is the tabulation method approach so basically if you see in this approach we saw in your problems from the results of smaller problems that are stored in a storage structure so the new one is all obviously larger let me define a 2d or 2d DPR a teepee of K comma ki the max for obtainable in he up till the index I by making at most K groups is what D P of K comma is signifies so DP of theta my I signifies the maximum score obtainable in a after the index I by making at most K groups now it is discuss a base case DP of 1 comma is simply pre sum of I by I plus 1 c DB evanka my signifies by making one group until the ayat index the maximum score that you can return now if you're making one group until the earth index it's nothing but the array until they until the I attend its itself so in this case is answer will be the average of the array until the I attend X itself right so that is P sum of I by I plus 1 you can read this for further explanation now for k equal to 2 k c---one with now for k equal to 2 k c---one with now for k equal to 2 k c---one with origin so we'll start off and the number of goes by 2 and go on till K which is given to us in the question I is basically the variable additive so now let me explain to the you're just using a picture so from 0 to Y we have to find the maximum score possible by dividing two by two at most K groups now see if I until let's say I go on til G on J plus 1 2 I gotcha - it's one group on J plus 1 2 I gotcha - it's one group on J plus 1 2 I gotcha - it's one group for me now the score that this group gives me will be simply the average of this group the remaining part 0 2 J is a smaller problem now here I'm allowed to use only K minus 1 groups because one group is formed here so this is a smaller problem which I would have already completed computed in D P of K minus 1 J K minus 1 because one group is computed here and initially that gave groups so K minus 1 J here because initially we were computing until the iights index but now it's only intellij the next clearly this is a smaller problem so it's already stored in an array so we can directly use this result so it's D P of K minus 1 J plus this average the other answer possible is we take this entire thing from 0 to I as one group so obviously the average will be the average of the entire array from 0 to I that is P of I my I plus 1 each time you take the maximum and store it in this case we return D P of K n in the end in the memorization approach we just call f of 0 comma key and return of answer so I think this was pretty much it now I will show you the code for both table ation and memoization approaches there is a memorization approach so submitting it clearly worked out now this is the table ation approach and this also worked out you will see it works thanks for watching | Largest Sum of Averages | all-paths-from-source-to-target | You are given an integer array `nums` and an integer `k`. You can partition the array into **at most** `k` non-empty adjacent subarrays. The **score** of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in `nums`, and that the score is not necessarily an integer.
Return _the maximum **score** you can achieve of all the possible partitions_. Answers within `10-6` of the actual answer will be accepted.
**Example 1:**
**Input:** nums = \[9,1,2,3,9\], k = 3
**Output:** 20.00000
**Explanation:**
The best choice is to partition nums into \[9\], \[1, 2, 3\], \[9\]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned nums into \[9, 1\], \[2\], \[3, 9\], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
**Example 2:**
**Input:** nums = \[1,2,3,4,5,6,7\], k = 4
**Output:** 20.50000
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 104`
* `1 <= k <= nums.length` | null | Backtracking,Depth-First Search,Breadth-First Search,Graph | Medium | 2090 |
347 | So give us gas 68, our top key frequent elements, easy question and a very good question, you will understand it, but we have to see the approach, how are we going to do it, we have to check that we have given the name of the name, hey, this is the input. I have given and I want to tell you the two elements which have come the most number of times. So you can see that A has been given the most number of times. If you want to tell me one more then you will be the second one in it. Okay, that means we know that. Meaning, maximum one A has been kept and two is our second maximum, so if the value of K was three, then we would have outputted only three. You are three, right, because these are the three, maximum three people have kept A, so this thing has to be taken care of. Like there is a van here and the value of the key will not be much, meaning it will not be equal to tu, when the element is one, then we do not have to worry about it, the output will be A. Okay, so we have to understand this, how are we going to do it. So the challenge will be that how much can we optimize, so first they see, then they come to the code, input is given in 100, name is van, you are given three times, key value is given, output is about to come, how did it come? I have already told you how to do it, they think ok so the first thing is if we check it is 150 then we will unlock only 5 after doing that then what if as we know it is 1382 and there are three vans then okay out of this We will keep popping how many times we want you, so we know that the sorting will be done on the basis of this, on the basis of account, okay, if it is of most van, then the van has come out that we can value it, so here, pocket shortcut, we do it bucket. If you haven't heard of the shot, then listen to it will be fun in a very good way. Okay, so we have the index and I have their account, so what will we do, what is basically a bucket shot, if there are 012, how far will it go, that is, 20. How many times has the van come here? If you have written three times then it is three times. How many times have you written twice? It is okay. In all the rest there are zeros. This is just zero. 20 How many times have you placed it once. It is okay. This happens in bucket shots but what is this? What could be the problem? Take it, there used to be 2000 here, so would n't I take space up to 2000? We will do it in buckets but in a little effective way, with some brainstorming, what will we do, we will turn it upside down, this is how our indexes are going to be, isn't that ours? The account will be counted, so now see that I am remaining the same but I am checking zero, one, three, two, color, tell me, its length is 123456, its length is 6, so how much will the account be, maximum can be 6, meaning it can be something like this. If we visit the whole place six times, these six times, then we will keep the van here, it can be all different, then we ultimately understood one thing that here we will check the size of the input area has been given to us. We will check from the back. We will check from the reverse. Okay, if we want to find the top element, then we will come from the back. Got this empty. Got hold of this one. empty. Got this empty. Got hold of this one. Then got hold of this one. Okay, so if I take one, a case comes that one or two. Three, four, punch, six are all different, so when we will create for this, okay, it is like above, then all the things that will be here will be added to one, then the entire list will enter inside it is 12345, otherwise a time off will start coming, traverse. If you check only one thing and then you will be charged an offence, then what is open? And as far as memory complexity is concerned, you are going to do hashmap, why is it to check the account, not our one, how many times, three times, two. How many times did it come, twice did it come three, how many times did it come once, then who will do it, I will count, you will do this count, we will compare the value with it and finally the answer that will come is that if there is two then if If you check the length of our answer key etc. then it is equal. This will also be understood. If we code then it is ok, so if the code has been made easy, then I have understood the explanation, what did we do, what was given to us and what is the value of key, you give Rakhi. So we have created a list of lists with a frequency name. Now what have we done, we have taken its range to the length of n+1 i.e. done, we have taken its range to the length of n+1 i.e. done, we have taken its range to the length of n+1 i.e. one more is fine, now we will show why, initially all these outputs are going to be like this because all these have been created empty at the moment. Right now, we have counted with the name CNT, as I told you, we are going to create one in one go to keep the count and keep it with the name of answer, why have we kept this list, now I will understand first of all. Thing D Thing for i in N I have taken the name of that which is fine which was written here by name I have taken it in N man and now what are we doing is checking the account of each element of the name so we know CNT i = 1 so we know CNT i = 1 so we know CNT i = 1 + 3 I have already + 3 I have already + 3 I have already told about this many times that if you have something about it in the Has Map then it is okay to initialize the character with zero, then we saw that A1 which is A is being initialized the same number of times. If there was no bar, then it was initialized to zero, then additions have been made, otherwise additions will continue like this. This is 1 + CNT. This is where we will know continue like this. This is 1 + CNT. This is where we will know what is the account of each element. So here we will know what is WAN, thrice. You are what you are, that is twice and what you are three is only once, isn't it, let's move ahead for I earn dot items, so we took the value purse, so look carefully at this line, I may be a little confused but I speak softly as if it has entered my mind, then what are we doing? The frequency is fine, so the frequency is there, so the van is visible to me, so the date of the account will be added in this 3, so it is on 3 only. What will be our add here, is n't it? We will keep checking like this and like this, like now our next one is coming, if I take you, then how many times are you here, if you are here, then you will write here, meaning you will come here [ you will write here, meaning you will come here [ you will write here, meaning you will come here We will start you from the back, right? We will move backwards because we want the maximum. If we want to catch the maximum time frequent elements, then we will start from the back. Let it be such that one of the six is gone six times, such that one of the six is gone six times, such that one of the six is gone six times, so this is the one we caught first. So, keeping this thing in mind, we have to move from the back, so what did we do? We went to the length of frequency mines van and you will say, why won't the mines van go here? So like I told you, whenever we go reverse look. Mines vans write two wires, isn't it so? So I asked you to remember a bit, so actually these last ones exclude it, so we don't know whether someone is Aquarius or not, so why would he come in that? Use a little brain here, if Man Lo Three does n't exist then why is mehendi written here, otherwise you wo n't be able to judge, so keeping this thing in mind, start it from behind, then frequency because we know how many totals it is, its length. If there is 6, we made seven because we had made one more, so here the length of frequency is minus one, so this is what it is, which one will be ours, it will be sixth, it is numbered from zero to six, so go here and then check 4G. Inside means we are here now, see if there is any element in the corner then append it was not there in the beginning. = I came because I have to come, so do I have to come or not, because right now our answer is lying empty, poor guy, when we go to the garden, we came here at 6 to 5, here too we are empty, then we ate here as well, will we be done as soon as we come at 3? This is equal to the length, no brother, run it again, inserted two also, appended it, explained why because the back look is going on, finally our answer will be returned, okay, the link will be found in the description, so just give a thumbs up if you understood and then comment. You can give feedback, see you in the next video. | Top K Frequent Elements | top-k-frequent-elements | Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size. | null | Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect | Medium | 192,215,451,659,692,1014,1919 |
47 | okay lit code number 47 permutations two just like the previous task we have a number sequence we have to return all the permutations of it but this time we have two unique permutations and it warns us that there can be repeating numbers so i'm pretty sure that the same code written in the previous one would work but i will write them again for the sake of this video okay again we will use the standard functions first certain numbers initially numbers that end okay so first of all we will use the identity and then while std experimentation begin and if there is no experimentation it will return false then push back the result and return the result oops i had a compiler in the previous task as well okay and we're done | Permutations II | permutations-ii | Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Constraints:**
* `1 <= nums.length <= 8`
* `-10 <= nums[i] <= 10` | null | Array,Backtracking | Medium | 31,46,267,1038 |
408 | uh so this question is about the word abbreviation so uh this is pretty straightforward um you are allowed to like replace an integer to what uh to the charts you have in the uh stream world and then you are you have some constraint like you cannot like replacing a substring on this neighbor uh right after right so 5 is not a lot but 55 is a lot right so imagine you're taking 12 all 12 character in for the substitution right and this is uh this is not a lot of this is because the uh the leading zero and also you cannot replace in a num i mean empty substring so which is leading zero as well so what do we need to figure out this is going to be like using two pointer and then i'm just pointing here and pointing it here right so if there are chars if they are alphabet right if the alpha building computer and if uh if abbreviation pointer is integer right integer pretty much which i need to uh check is the pointer is the leading zero or not if not then i need to just uh traverse until the pointer at this index is not integer and then i will just replacing the charge in the world so probably over here so you'll just get rid of this be honest and reassign the pointer to the new index and then traversing over again and uh in this one i'm going to talk about the inter iteration and recursion solution so uh stay tuned something like this so i have j and i so i represent the word string and j represent abbreviation the string right so i need to just um set a boundary so i and j right so is if they're in a boundary then you have to work right so i'm going to say x and y for words i charlotte and i y equal to what abbreviate our triad aj so if they are equal if they are all char i alphabet right you just continue to next index and then basically right so i'm going to check if where why if this is not the integer and also uh num leading 0 and you need to get roughly right so if this is y is greater than 9 or y which is less than equal to 0 right this is that leaving 0 and num integer so you recompose so uh once i hit a point which is the integer right i need to traverse until a point which is not an integer so i can't i can replace uh the index uh for i right so i'm going to say num index equal to y equal to j right try version so you still traversing will abbreviate our length and also abbreviate our chart at j if you have to say uh you have to say this is in the integer boundary right a j which is less than equal nine and then i'll just increment my j right so i will just have to take the length so uh this is going to be what this is going to be substring as a radar substring and starting from j oh sorry starting from num index to j right j is a point which is increment right and this is a string right so you need to convert to the integer right then you need to replace uh sorry you need to update your index so it's going to be i plus equal to length and just keep going until the point until you break the well loop and then when value is actually the pointer is actually equal to the length of itself then you'll return to right so this is iterative solution so hopefully i don't make a mistake i do a fb all right submit all right this is iteration uh solution so let's talk about the let's using the same idea but i'm going to use a recursion right so i'm going to just comment this out and whatsoever and uh yes so i need a recursion so i need to know like my index right so i need to create helper function so i'm using the same name and then but a different argument right and then i need to create a new helper function so this looks really ugly so i'm going to do it and gonna be like this and this has to be in i this has to be in j all right so what so where's the base case when i is equal to what's the length and also j could uh be able to abbreviate that lens right so your return true and then uh when one of them is like alabama right then you need to resemble so i'm going to copy and just making sure i replace the end to all equal sign to greater equal and then this is false when one of them is invalid then this is false all right so i need to check the chart right if they are the same charge if order charge at a i is if this is equal to abbreviated chart i'm going to just keep traversing until the next so i mean i'm using the recursion so i'm going to recurse the next index right all right so uh this is going to be uh the equal sign right so now i need to check if the j is what if the uh pv br dot chart at j if this is non integer or leading zero right boiler9 or dpr pbr dot which is less equal to zero right now return false all right so um this is going to be something easy and then i need to check the length right length uh length is like starting from zero and then i need to traverse so well j less than abb are the lens and abby out of charge at j if this is about the integer nine and file the integer in the bond with the including the zero then i need to just implement my j and also the length should be what i need to replace uh the value uh to the length right so um i need to know like lens times 10 like if you on the next index so you know times 10 and then plus the conversion right so this is a conversion using the chart notation i mean uh whatever you get one chart one minus chart zero you'll definitely get one right so and then you'll multiply by 10 when you are not on the next index and then this is going to be pretty much it right so when you return right you need to know like the j is going to be go by one and then recursion is going to be from here jumped to here something like this right uh should be i right so it from here i to another i so what do you need to i plus the length and then a dbr and then j so you don't need to increment or j this is because you will break out the weld when this condition is invalid so this is a recursion solution so submit all right so uh let's talk about the time in space so in a recursion solution this is what the time this is definitely all of n and represent the end of the words i mean all the abbreviation dot uh length doesn't matter which one is the worst scale then you pick me and the spaces won't be constant like you don't allocate any space so this is a recursion solution so uh where is my iteration in solution so this is the iteration solution right so the space is gonna be constant right and the time is gonna be all over n and represent the worst case for the string so iteration is actually what iteration you actually need to try verse uh traverse all of all the abbreviation i think right and then you jump yeah so the time is actually all of an unrepresented length of abbreviation right uh you will just skip a lot of like of charge in the stream world so it should be string abbreviation and also the an oscillator and also the recursion so here's it so this should be all of un and represent the end of the abbreviation because you escape a lot of charge in the words so this is a solution so i will talk to you next time bye | Valid Word Abbreviation | valid-word-abbreviation | A string can be **abbreviated** by replacing any number of **non-adjacent**, **non-empty** substrings with their lengths. The lengths **should not** have leading zeros.
For example, a string such as `"substitution "` could be abbreviated as (but not limited to):
* `"s10n "` ( `"s ubstitutio n "`)
* `"sub4u4 "` ( `"sub stit u tion "`)
* `"12 "` ( `"substitution "`)
* `"su3i1u2on "` ( `"su bst i t u ti on "`)
* `"substitution "` (no substrings replaced)
The following are **not valid** abbreviations:
* `"s55n "` ( `"s ubsti tutio n "`, the replaced substrings are adjacent)
* `"s010n "` (has leading zeros)
* `"s0ubstitution "` (replaces an empty substring)
Given a string `word` and an abbreviation `abbr`, return _whether the string **matches** the given abbreviation_.
A **substring** is a contiguous **non-empty** sequence of characters within a string.
**Example 1:**
**Input:** word = "internationalization ", abbr = "i12iz4n "
**Output:** true
**Explanation:** The word "internationalization " can be abbreviated as "i12iz4n " ( "i nternational iz atio n ").
**Example 2:**
**Input:** word = "apple ", abbr = "a2e "
**Output:** false
**Explanation:** The word "apple " cannot be abbreviated as "a2e ".
**Constraints:**
* `1 <= word.length <= 20`
* `word` consists of only lowercase English letters.
* `1 <= abbr.length <= 10`
* `abbr` consists of lowercase English letters and digits.
* All the integers in `abbr` will fit in a 32-bit integer. | null | Two Pointers,String | Easy | 411,527,2184 |
997 | hello everyone welcome back to lead coding today we are solving find the town judge is a basic graph problem and let us go through the description of the problem in a town there are n people labeled from 1 to n there's a rumor that one of the people is secretly down judge so for the town church there are three conditions the first one is the town judge trust nobody everybody trusts town church and there's exactly one person that satisfied the above two properties now we are given an array and each entry of the array is a pair a comma b which represent that the person a is trusting the person b if they taunted x and we can identify it we should return the label of the down charge otherwise we have to written -1 so let otherwise we have to written -1 so let otherwise we have to written -1 so let us see the same through an example here we have an example and there are nodes one two three and four now in this example the first entry is one comma three so it shows that the person one is trusting the person three one comma four so one is trusting four 2 3 denotes that 2 is also trusting 3 then 2 comma 4 denotes 2 is trusting 4 and 4 comma 3 denotes that 4 is trusting 3. now except three all other nodes are trusting three and three is not trusting anyone so three is the only node that satisfy this condition so three is the down judge now there's a concept called in degree and out degree so if this is a node n and if there's an incoming edge to n this is called an in degree and if there's an edge from n to any other node then in this case this edge is called an out degree so in our problem we just have to see the number of in degrees and the number of in degrees should be equal to n minus 1 as there are total end nodes and except the town judge itself all other nodes are going to point towards this down judge so the in degree should be n minus 1 and the out degree of this node should be 0 so we just have to check that uh there exists only one node for which the in degree is n minus one and out degree is zero so we can simply implement this problem using this concept of in degree and out degree first of all let us create a vector for in degree and for out degree so both of them will be of size n now we have to traverse the given vector trust now when uh this a is actually up here and there will be two element in a so these are the two elements one comma three we have to increase the in degree for the element at the first position so if we have one comma three this is zero this is one so we have to increase the in degree at the first index and we have to increase the out degree at the zeroth index in degree of a of 1 this should be incremented and out degree of a of 0 this should be incremented now after this we have to traverse uh we can go through each of the element from one to n and we can check the condition for this node being town judge so if the in degree of this node minus one uh i think we should make this as n plus one so that we can handle the edge cases now we can simply do this in degree of i if it is equal to n minus 1 and our degree of i equal to 0 then we can return this node else we can written minus one also if we have n as one so we won't have any pair so the size of this trust will be zero in that case we have to return if n equal to one we have to return one because there's only one person and that person is the town judge so it is giving us correct answer the space complexity in this case is big o of n because we are using two extra vectors to store the in degree and out degree and the time complexity is the number of edges the size of trust is the number of edges that we have in the graph and in the worst case it could be equal to n square so we can't uh improve the time complexity as we already uh as we have to traverse each of the edge which is given so this is it for the problem if you like the solution please subscribe to the channel thank you | Find the Town Judge | find-the-town-judge | In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **1** and **2**.
You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`. If a trust relationship does not exist in `trust` array, then such a trust relationship does not exist.
Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_.
**Example 1:**
**Input:** n = 2, trust = \[\[1,2\]\]
**Output:** 2
**Example 2:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\]\]
**Output:** 3
**Example 3:**
**Input:** n = 3, trust = \[\[1,3\],\[2,3\],\[3,1\]\]
**Output:** -1
**Constraints:**
* `1 <= n <= 1000`
* `0 <= trust.length <= 104`
* `trust[i].length == 2`
* All the pairs of `trust` are **unique**.
* `ai != bi`
* `1 <= ai, bi <= n` | null | null | Easy | null |
983 | um and also today we are going to do this problem which is part of Fleet code daily challenge minimum cost for tickets so basically you have you plant some travel um some train traveling when you are in advance um in the days of the year in which you will travel are given as an integer array of days right and each day is basically when the year is an integer represented by an integer from 1 to 365 okay and train tickets are sold in different ways right you have one day pass which is sold for cost of zero cost so we have a cost array where the first day one day pass is the first element of the array um in the seven day pass costs the second element of the array in dollars of course and then a 30-day pass dollars of course and then a 30-day pass dollars of course and then a 30-day pass is the last element of the costs array um and the pass is basically represent consecutive days so one day is of course just one day but seven day pass is covers seven consecutive days right um so if you get a seven day pass on day two then you can travel day two day three four five six seven eight right so you get seven days um in the target from this with these possibilities is to return the minimum number of dollars you need to travel every day right in the given list so you get a list of the number of days those are the days you want to travel in and we want to find what is the minimum cost to get that done so let's take a look at the first example here um so with this um you can take on day one you can buy one day pass so that will cover the first day with a cost of two dollars which is the cost for just one day pass and then for the three right just before this day four you can buy a seven day pass and that will cover day three four five six seven eight nine right because it's a seven day pass so that will cover all of these um and so now you have the cost two dollars plus the cost of seven day pass so two plus seven which is nine okay and then now the only remaining one is this 20 day so you can just buy one day pass for it and that will give you nine plus the cost of one day pass which is two so that will give you eleven and that will put here so that's sort of the idea and this is if you're able to try other possibilities this is actually the minimum so that's the idea um now a couple of constraints here that are relevant to us so the days are of course just between one and 365. that makes sense but the also days array here is sorted already in increasing order right um and we have only three passes so we have only three type of passes so we have only um three values for costs right okay so that's the idea now how do we solve this um okay so how can we talk of this so the first idea is um let's think about the choices we have at any given point right so the choices at any given point right at some day I right so we have the days right so for example the first example is one four six seven uh okay let me just make this a little bit better um so the days are uh one uh four six seven eight twenty all right okay and then we have the costs which are uh to 715 right and so if we think about choices at any given point let's say at six right well it depends if you have some remaining uh some remaining like values or the remaining days in your in the previous past you bought or not right so let's say if you bought in day for example if you bought in the um so let's say if you bought in day four if you bought a seven day pass right then for this six there is pro there is no cost because it's covered right so if you did buy seven day pass here then this six is covered if you did buy like a 30 day pass here then this six is covered right if you just bought one pass then the six is not covered so you would have to buy a new one right so one choice is that if basically if there is still a remaining pass right we will need to keep track of it that covers the six then we should be good but be careful here a little bit right it's let's say for example if we bought some time before right and maybe we have only two days past remaining at four so one will cover four so we have only one day pass remaining well that one can't cover six that one covers the next day which is five right so we actually can't cover six with the pre with this pass right and so it only covers it is if the difference is actually smaller than the remaining pass right so only if so the difference is two so how many days you need to be able to cover the six you need two right so only if the remaining pass after at this point at six is actually uh it's actually bigger than the days here minus the previous one right so let's say so it's only if the remaining pass right is bigger or equal to the current days right so called days I minus What minus the previous day right because we need the difference is how many days you need to cover to be able to cover this day if that makes sense and so it's minus previous day okay so only if this is the case that you can so if this is the case you don't need to buy a pass because it's covered right so this is the covered case and then in that case we can just recurse let's call our function maybe some sort of helper function what state do we need well we need to know the remaining paths already whatever is remaining from the previous state and then we need I which is at what point we are looking right now and then we need the previous day because we need to follow this check so these are the states of our function and so what is the next case here that we need to return well it's going to the next step so after covering the six value here we need to go to seven so the next I plus one now how many what's the remaining paths right well it's just let's say for example here at four you had remaining three right and so 6 minus 3 is equal to 3 and 3 is equal to three so it's cover you can cover it but once you cover it you are done you can't cover the seven so how do we pass that value well exactly what we did here how many days you needed to cover those get taken from your past and what's remaining is what gets passed to the next so here is just the remaining pass right minus these two right what you need to cover so these are basically the days you need to cover uh to cover okay and so this would be minus basically days I minus previous day okay now if this is not the case right so in this case this means there is no valid pass from it from previous days right and so it means we need to buy one of the passes right now okay and so we just try all of them and see which one is the smallest one so we just take the Min this is what would a turn of taking first just the one day pass so that would be just the cost of one day right Plus uh one day is zero plus going to then again the next state what's the remaining path well when we buy one day pass remaining is nothing right so they and then the previous day is actually just days at eye right and then the second option is to buy the seven day pass right and then in that case we go to I plus one with how many remaining past days well it's seven days we just bought one in and used it one day so remaining sixth day is sixth day in the past and then we the previous day is days of I and then the third option is to buy a 30-day pass right so that's cost two a 30-day pass right so that's cost two a 30-day pass right so that's cost two in that case while we go to the next how many days are remaining well we bought 30 day pass we just used one for day I and so remaining is 29 and then the previous day is just days I and that's pretty much it so these are the only choices we have either we have some days remaining in our past from the previous days that we bought it in that case we just do that because it's always better to use it than buying a new one because using it has costed zero but buying a new one has always a cost right a positive cost right so it's always better to use it if it's there if it's not there we need to buy one of the passes we don't know which so we just try all of them and pick the minimum so that's sort of the idea of this first approach um a lot implemented first make sure it passes and go from there um okay so let's implement the solution we just saw in the overview so what we need is we need a helper function that has the three states that we need the index of days remaining pass in the previous day um so this is the actual value of the previous day okay and now what is our base case well our base case when we finish for all the days right so it's just when the eye length of days is equal to length of this that means we are done we return just zero right no cost anymore because we are done and now the two chases we have so either we have remaining pass days that cover the days that covers up today's eye and so how do we check that basically it's if the difference between day I in the previous day is actually smaller than the remaining pass so that means there is enough in the past to cover up to the days I that's what this means so if that's the case then what we can do is just use it because it's always better to use it and so we just use it we go to I plus one and remaining pass is going to be just um just to make this easier for us let's call this um to cover um and so that we can make this easier to write okay and so this is going to be the remaining passage just minus what we need to cover with that pass for this eye and that's what's left for I plus one and what's the previous day now it's the current day right so for the next iteration it's the date at position I is the previous day okay so this is basically the previous travel day okay and then the next otherwise right we just try all of them so we try all the different possible passes okay so we try one day pass seven day pass and 30-day pass okay pass and 30-day pass okay pass and 30-day pass okay and then we return it and now we call Harper function on the starting with zero and remaining pass initially it's a zero nothing the previous day initially also we can call it zero because the days are from 1 to 30 365 so zero is really not a valid day which works for us um for this case and so we just return this because it works because the remaining paths here won't be available so we'll just fry all these three and that's what we should do initially right initially we should we have to buy a pass okay so this is good it will probably tle because from these cases we are doing some we are calculating some specific tests some specific States multiple time multiple times and so if I run this should give us it should mostly pass but give us time limit exceeded um and So to avoid getting time limit exceeded we can just cache uh do some caching right in Python the easiest way to do it is with just using lru cache annotation you can of course use table2 to store these values using a hash table but let me first show that this works um we'll probably need to not limit the size here so that can be done with just saying that there is no Max size um and that passes um but if you want to do it without this lru cache thing you can use a memo table right with some keys so that would be memo um and then we will just say if here if in memo if you have a combination of all the states of the function we need right and previous day if all of these are in memo then we return them okay and then otherwise we want to set them so let's call it like this okay otherwise else here it's going to be this equal to this right and then at the end we want to return it wanna return this that should be it so let's run it and that passes let's submit and that passes as well okay so we can memorize it as well um yeah so that's pretty much it this should work um okay so that was the first approach now a second approach we can do actually instead of going forward we can sort of Look Backwards what do I mean by that um so let's say if days day I is the last um is the last day of your travel pass right okay so when it's the best time to buy that pass right it's always best to buy it as early as possible so that it covers the maximum amount of days right so let's say if you are buying a seven day pass and you want to use it at day I it's always better right to buy it in day I minus six right so buy it in the I minus six because then you will get to cover six days plus day I similarly for a 30-day pass similarly for a 30-day pass similarly for a 30-day pass right that you want to use at the I the latest the last usage of it you want AI it's always better to buy it 29 days ago so that you can use it basically a day um I minus 30 because in that case you will cover so this would be I minus 30 and this would be I so you buy it in this day just I minus 29 similarly here I minus 6. so that you can use it for 29 days and then the last day I you will use it and it will be expired at that point now what about day what about one day pass well one day pass you just buy today right so that it covers I right so with this knowledge it's always optimal to buy it if you want to use it on day I as the last day it's always better to buy it as early as possible um and so with this basically what this tells us is if we want to do the choices then let's say we are using still the same function helper of I right so then it's going to be the Min of course cost of pay of paying just to use of paying for a one day pass right plus helper of I minus 1 because you bought one day pass for I and so you want to go back and see how much did it take you to get to I minus one now otherwise you buy a seven day pass but then since we want this right we want this case so that we want to buy it on day I minus six that means what's the previous state well the previous state is just before I minus six it's I minus seven so we want to know how much it did cost us to um to get to i-7 and then for the to um to get to i-7 and then for the to um to get to i-7 and then for the rest it's covered by the one that we are just buying right so this is going to be plus helper of I minus 7. and a smaller Logic for buying a 30-day and a smaller Logic for buying a 30-day and a smaller Logic for buying a 30-day pass right so it's going to be cost of two plus helper here for I minus 30. so that's the idea now we return this but um we can of course um now one other idea to make this also simpler is that what if so let's say what if you let's say here for example right let's say if we look at the initial example we had one four six seven eight right so let's say on day six right we call it then this helper function will get called on day five but the list of days we have are just one four six eight twenty right there is no five in there right so if the day is not there that means we don't need to travel on that day so we don't need to buy anything and so we just say how much did it cost to buy on day four from here okay so basically if I is not in the days we need to travel in then we just return immediately helper of I minus 1 because in that day we don't need to buy any ticket right and that's pretty much it now we can optimize of course by making this become a set so that checking is over one but this is sort of the recursion idea and what's nice about this approach instead of the first one is that this is a lot easier to convert to a DP instead of a recursion to convert to a DP approach dynamic programming approach right okay so let's implement this and check if it passes um okay so let's implement this idea so first we need um here we only need I now right and since we are going backwards it's no longer reaching the end it's reaching the beginning because we start from the end and go back so if it's smaller than zero would return zero because that means we are done and now we are we have only two cases either it's one of the days so either I is in day is not in days right so this means it's we don't need to travel on this day so in that case we just go and see how much did it cost us to get to I minus 1. because we don't need to pay for any tickets here now if it is we need to pay but we don't know which one so we try all of them okay so we try all of them as we said in the overview it's just the mean of trying all of them so first one day pass and so we just we need to know how much did it take cost us to get to I minus one and then for day I we buy one day pass or we buy a seven day pass right but we want to use it as much as possible and so it will cover six days and day I six days before I and day I and so we want to know how much did it cost us to get to the day just before that which is day I minus one and similarly for buying a 30-day pass also similarly for buying a 30-day pass also similarly for buying a 30-day pass also um right so that's the idea the same logic for buying a 30-day pass and now logic for buying a 30-day pass and now logic for buying a 30-day pass and now what should we pass just since we want to go from the end and go backwards we can start from the end of the number of days now days is sorted so that's why we are able we know that the last day element this element is the largest one is the latest day that's why we can pass it here um now if it wasn't sorted we could just sort it now this is also a list so searching on it is going to be of the length of days list so we can convert to a set just to make that faster in case the days array was a little big in that case and then we can use this like this and that should be it so if we're on this and submit it should pass now um it may get time from it exceeded again because we didn't cache this yet so let's cache it quickly here so we just need a memo table and similarly like what we did earlier so if I is in the memorization table then when I return it right otherwise we just want to calculate it and here we want to do else because we are no longer returning immediately so that would be like this that will be like that and we want to return it at the end so we'll return memo of I okay and now for on this and submit it should pass and that passes correctly um okay so now the last piece is how do we convert this to a small to a DP array okay so the easiest way is just create a DP table um and so it's going to be we only need up to the last day because that's the only values we need right and so this is going to be in range of up to last name plus one just because python range right and so we just do a loop right from one to days minus one plus one okay and now for DP of I we can just replace it with this except here instead of using the function we use I minus 1. and same thing here um like that and then similarly here as well so this is going to be DP of the same logic right we buy if we buy a seven day pass then we want to use it as much as possible and so it covers all the way back to I minus 6 day and so we want to know how much cost it took us to just get to the day before I minus six which is I'm minus seven right and then here if it's not in day set then DP of I is just going to be equal to DP of I minus one right so exactly the same except we are using an array that we fill right and so here instead of it being function it's just that for Loop um and this is no longer returning right and then the last thing is we want to hear just return instead of returning helper it's in the uh in this GP array so we just get it from it um and that should be it so let's run it um this set needs to be before right so somewhere here and let's run this um so it looks like I minus 30 maybe out of range so here we just need to make sure we don't exceed the range so let's just say Max of zero and DP of 0 would be zero anyway so it should be fine um to add zero right so here just want to make sure we don't exceed and then for this one we don't need it because we start at one okay so that looks good let's submit and that passes as well right so this approach starting from the end and going back is easier to convert to a DPO format um yeah so I think that's pretty much it so this one is more straightforward and easier to analyze this for Loop here is of the max of days right the last day so it's sort of um almost constant time here um and yeah it's actually pretty it's constant value here right um because we have at most 3 365 days right and then in terms of space we are using this DP array which is also at most 365 so it's constant as well and so it should be pretty fast um yeah so that's pretty much it for this problem please like And subscribe and see you on the next one bye | Minimum Cost For Tickets | validate-stack-sequences | You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000` | null | Array,Stack,Simulation | Medium | null |
130 | Hey how's it hangin guys so in this video we'll discuss about this problem surrounded regions so in this problem we will be given a two-dimensional array will be given a two-dimensional array will be given a two-dimensional array consisting of X and O's so something like this now in this problem x will capture oh now there are certain types of oh that is two types of Oh which won't get captured the first type being the O's which are lying on the boundary of this two-dimensional array those of this two-dimensional array those of this two-dimensional array those won't get captured so in case and oh is lying on this zero a true or this last column or this last row or this zero at column those won't get captured so if you see carefully this is lying on the boundary so this ovum won't get captured the other types of O's which boon get captured are the ones which are connected to the boundary O's either by a horizontal or vertical path so let me take an example to show you guys that thing so consider this already given to us now the horse which are lying on the boundary that is this oh and this oh these are safe and rest of the arrays are in danger so basically I have marked the rest of the O's as in red and these are in green now the O's ways are connected to these boundary goes via horizontal or vertical path are also safe so if you see this o is connected to this o via this vertical paths so this is also safe similarly this is connected to this o via this path so this o is also saved similarly this o is also saved but we cannot say in the same thing for this because this is diagonally nation this is not a horizontal or vertical connection so how does all this problem so it's a very simple question so what we can do is we can simply iterate over this boundary indices correct and whenever we are hitting up o what we can do a DFS traversal starting from this point and vedyam and in case and wherever we are hitting a zero or at o you will simply mark this as e that is escaped so what I'm saying is so suppose for this array I am doing a DFS for this point now what I'm saying is so from here I will move to this one then this one so all these O's will be converted to e stands for escaped so we will have something like this so what I'm saying is these OHS won't get captured and similarly for this these two will get converted to these II that is escaped once we have this array what we can do is we can simply iterate over this array of one more time and whenever we are hitting up oh we can say that these hoes will get captured by X so we will convert these o's into X and whenever we are finding a e we will say that these hoes got escaped so we'll convert them into o so we will have something like this correct so I would enjoy them over here you can read the algorithm as well so now I'll write the code for this question and then things will be more clear okay so let me define the two variables that is int rows and calls now first we'll write the base case over here in case both equal null or Bo dot length equal 0 very simply better next what we do is so see what we are going to do is we are going to simply treat over these boundary indices and whenever we are hitting up ooh we are going to call the DFS so suppose over here it will call the DFS and it will mark all the adjacent horizontal and vertically connected goes to be e so that is d scott escaped so let me do this thing so for int I equals 0 I less then Rose I plus so in case if bowl of i0 equal oh then we'll call DFS ball board i0 so basically this is for the 0th column next for the last column that is in case board I this is calls minus one in case this is equals to Oh we'll call DFS for board i calls minus one so this is for the last column next we will trade for the 0th row and the last row so far end J equals 0 J lies then calls j plus if board off so you need to consider the zeroth row and the last row so in case mode of 0 J in this in case this is equals to oh we can call DFS 4 volt 0 G and we have to consider the last twice well that is board off this is Rose minus 1 J in case this is equals to Oh we'll call DFS for board Rose minus 1 J so let me add this DFS method as well so this method only done anything so it will take this character this board that it will take I and G so first you will mock this board of I J s e there is this cell has been escaped next you will call DFS for the four directions so in case you are over here you will call it for this then for this cell and that for this cell that is the full edges in cells so let me call the DFS for these four edges and cells so this is I minus one J so let me just copy this thing four times so this will be I J minus 1 this will be I J plus 1 and this will be I plus 1 J one more thing we need to consider the base pin as well in case I is less than 0 4 is greater than equals rows or J is less than 0 or J is greater than equals calls or Board of IJ is not equals to Oh in that case we can simply read Oh so after this thing is done what we will have is so from here we will be somewhere over here now you have to simply iterate over this area and we have to mark all rows as X and all eases pose so let's do that thing as going so far and I equals 0 I less 10 rows I plus 4 and J equals 0 J less than calls J plus will simply say if bored of IJ equal oh then we will mark bored of IJ as X and F bored of IJ equal e then it means this that has been escaped so we will mark it as oh so I guess that's it so let me submit this code much so it's giving the wrong result okay so the mistake that I was doing in this question is actually I have not initialized this toys and goals so let me initialize this as those is equals to poor dot length and cause equals bored 0 dot length so let me submit this code once all right got accepted so I guess that's it from this video in case you have learned anything from the video you can hit that like button and in order to support my work you may consider subscribing to my channel | Surrounded Regions | surrounded-regions | Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`. | null | Array,Depth-First Search,Breadth-First Search,Union Find,Matrix | Medium | 200,286 |
135 | Hello Everyone Suggestion Question List Candidates And Acidity Change Font Saudi Arabia And Children Standing In A Line In Children Insider Trading Value In Teachers Day Greetings And Your Given You All Giving And To Children Subject The Video then subscribe to The Amazing Candidate Twitter The Video then subscribe to the Difference child and return the number of minimum number of candidates needed to distribute among the country and subscribe and died with her neighbors that slapstick evening 102 understand how they can go to word is sorry for the first we can give one Can Do the Thing 12012 Need to Give One Can Give Me to the Child with One to Two to the Tarzan Will Go to the subscribe this Video Give subscribe the Channel Thanks That Sui Can Give Best 210 Haval Solution Visit to Build Up So Let's Again Taken Example If Little Big Temple To Understand How They Can Us Them After Approach So Let's Study-Teaching To Give One To The So Let's Study-Teaching To Give One To The So Let's Study-Teaching To Give One To The First But After 10 To Give Me Two To Two Subscribe 502 Candy That Aap To Dekh Not Even Greater Than Five Minutes To Give You Can Destroy This Child Will Not Give Three Candidates Will Be Born In A Number Of Candidates Will Be Amazed 4499 Will Give One And Only You Can Children Like Rating Get More But Not Give The Giver 125 Will Give The Problem Subscribe Now To Receive New Updates Value To Know This Point Notified In Half Dispute With Total Number Of Candidates Need To Give This Channel Subscribe Button More Little Angel Will Know What So Know One Thing I Can See Clearly Is That is that nine ten pip and for both are Ashwin equal to two Candice Ashwini Swar Liye Winter and Various Countries for 2102 Entertainment Value to Three Loot Side What is the Use in Adhik Singh Continues in the Simply Improvement of Subscribe Per 570 Amazing subscribe The Channel and subscribe the Thanks I Can Always Give One Candy But Problem Arises When I Will Get Another Difficult 30 Minutes To Give One To Three And Improvements Swayam Ki Bigg Boss Ko Start With An International Give And Increasing Every One Can Enter Your Life Will Give What Is The Position Subscribe 9th She Will Celebrate 35th Husband Bill Clinton Malook To Be Observed On Front Blouse 4361 Cigarettes Up For 60 Video Subscribe Amir West's Need To Think Of A Better And Subscribe Enough Evidence Of Clans The Point When Is The Instinct Of Doing For Everyone Difficulty Giver Can Give Values in What They Can They Will Give One Adhikari Laut I Will Give One to Three Take Tomato with the Element That I Will Dandruff Bird Flu Surinder Reverse to I Will Check Davison Adheen Start with This at the Three Yasmin Adheen The To Have Great Evaluate 6 Printed To 9 Of It's Something For The Benefits Of Asbestos To Three Layer subscribe The Channel Please subscribe And subscribe The Amazing Porn Clippings Subscribe 2014 List 500 People Dipping Hair Oil With One Ide Yes Say They Will Check The Fast against first subscribe will start to start from the prime minister to give what is the value is the great Khali way raw to the volume to subscribe quintal solution ka two parts of the contour this so let's talk or for this and understand how we can Do it as that so let's start the calling part so initially I will take glands and visiting this to start size and account virval 2008 sexuality to the number of candidates for particular is child will result in that chor nine to runway left pass sonth left pass Start Now with One Zero Race of Yours Always One Where to Discuss the First Year Will Gather at Least One Candy Oil Electronic Plus Subscribe - One Electronic Plus Subscribe - One Electronic Plus Subscribe - One is the Value of the Self I will be a Result of - Way subscribe Channel Result of - Way subscribe Channel Result of - Way subscribe Channel Please subscribe our Simply This rumor combined vision simply that time two in one left 510 left after this point to right first need to check which will start from - 20 - - festival and rating of this great - 20 - - festival and rating of this great - 20 - - festival and rating of this great and a plus one subscribe and subscribe this Video give What is The value of something is the q website first so I need for the value of birth result of this one plus way the result of this lesson result of - one plus result of this lesson result of - one plus result of this lesson result of - one plus two result of - way all subscribe thank two result of - way all subscribe thank two result of - way all subscribe thank you just need to finally Bigg Boss Ne channel subscribe bhi ki and at last they can return discount role si ajay ko ki ab desh no song my love oo main mukesh we are going out of bounds long and this decide plus one not - do long and this decide plus one not - do long and this decide plus one not - do subscribe plus one and here bring a Smile Once OK Address Primary Should Strive To Submit A How To Get Good Accepted For This Point To Defective Who Have A Nice Day Ego | Candy | candy | There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.
You are giving candies to these children subjected to the following requirements:
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
Return _the minimum number of candies you need to have to distribute the candies to the children_.
**Example 1:**
**Input:** ratings = \[1,0,2\]
**Output:** 5
**Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
**Example 2:**
**Input:** ratings = \[1,2,2\]
**Output:** 4
**Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
**Constraints:**
* `n == ratings.length`
* `1 <= n <= 2 * 104`
* `0 <= ratings[i] <= 2 * 104` | null | Array,Greedy | Hard | null |
1,713 | hello welcome today let's try to solve another lyrical problem 1713 minimum of reasons to make a subsequence so we are giving a Target array at our array so the target is a 513 and the other array is nine four two three and four so we just need to like add some numbers inside of the Ring to make this target array is the subsequence of this survey so for example there's an already has a number three it means it has a three we just need to insert a number five and one to this array so 5 and 1 inserted here or anywhere just makes the sequence the same you're gonna get the right result so yeah put the five here and one here it is okay so it means we need to insert two positions we need two insertions so we're gonna return two yes so for such things it's very clear it's a the longest common subsequence problem because if this is three this is the longest common subsequence here we have a three so the length of the target minus this number three because we find one it is a two so it is the result so this is actually the template code for the longest common subsequence so here is the template code if you solve the longest common subsequence it should not be difficult yeah so here is just the length of the target minus the longest common subsequence with those two arrays Target and early let's check the values length of the array it is the 10 to the power of 5 and it will not pass now let me just to run it and submit it to tag if it is okay because for lead code if it is more than 10 to the power of four normally it cannot pass for a o n Square time complexity algorithm now let me submit it you can see that it will not pass yeah just wait for a few seconds and let's check the result because this is the on Square 10 to the power of 10 of course it will not pass yeah but our idea is the same if this number is a 10 to the power of 3 of course we can pass yes so there is a time limit exceeded error so it means our algorithm is okay but the time complexity is not okay so we need to yeah increase our time increases the speed and reduces the time so how should we do that let me uncomment let me just to delete this one and let me uncomment this one maybe you will talk something yeah so let me just to comment to this one now we are going to use another method it is called the longest increasing subsequence yeah so sometimes it's the longest increasing and the longest common subsequence can be yeah can be converted to each other to sub differential difficult problems because they are really similar now we are going to talk so in the Target array let me prepare to at least Target an array for this example so let me put it here yeah actually let me just delete this one to make it clear so we have a Target and array so here is this is three so the index of this is three is two and here we also have a three we don't care about this index with us to take care of this index yeah because we're going to use o and logo and time to solve this problem can we use the index to mix the index longest increasing to mix the index be our longest increase in sub array to solve the problem yes we can because for this 3 as the index for the Target is two so we're gonna name it a index as 2. put it inside our array yeah if we have another number maybe 5 here so for five our index is what so the index for 5 is 0. yeah so for such a race the longest increasing separate is one because two is more than zero so it is a one but for example we have another array maybe here we have a five so the index of the five let me prepare the index so our Target forward we have a number with index so five index with zero one with index of one and three with index of two so this is what we need to prepare we needed to prepare basically uh dictionary so this dictionary have K value pairs so K is the number inside the Target and the value actually is the index because we're going to use the in we're going to check the index to text inside of this array and these numbers we're going to check each index of them if the index is in increasing order and we're gonna check the long distance longest increasing subsequence of the index if it is a 3 it means we're gonna yeah get a result of zero because less of Target minus three it is zero now we are going to Circuit so for this example now for the first one yeah we are not going to tax numbers which are not inside of the Target because we're only considering with the five one and three so if this is a 5 we got a index it is a zero so from the beginning we have a zero now we have another number is here three so the index for three is two we have another number it is a two now we are going to check this array what is the longest subject longest increase in subsequence it is a two yeah so this is why we're going to use the length of the target 3 minus two it is one so for here it is a five three this is for 5 3 and here we have another 5 and 3. yeah this is why we can solve it in all and log in time because longest increase in subsequences there is a patient's thought algorithm can be solved in or in login time so actually this is the template code for the strictly increasing it is a software but you need to use the biceps left if it is not flux strictly increasing it is a non-decretion you can use the bisector non-decretion you can use the bisector non-decretion you can use the bisector left and for our problem it is a strictly increasing so I'm going to use a bisector left now the second step is to so this is the template the second step is to prepare this dictionary so how should we prepare this dictionary so for the dictionary it's going to be a k value pair so the T will be the number and the value will be the index of n with index for IL in enumer with Target so this for this one we've already prepared the dictionary now inside our longest increase in subsequent function we just need to change this number L with DN because we need to check the index as the result because for the this array longest increasing subsequence actually we are just detecting the index inside actually it is the index the setting the longest increasing subsequence of the index inside the ring yeah now for here it's also the same we just need to change it to DL and this one also the same yeah because we just needed to append or insert put the index inside not to the number itself yeah now let's attack yeah and for this inside of the rate before that before we use the bisect left because we used to tax this DN so for this DL this Earl must inside the dictionary so if this earn inside this Dictionary d so we're gonna tap yeah we just need two things a little bit for the template of the longest increasing subsequence for this o and Logan time template now let's say what we needed to do we just needed to return the result so let me yeah delete to empty line we just needed to return the length of the target and manners let's say l yes so this is a yeah l i s and with the ugly yeah basically this is a the longest increase in subsequence for those indexes if this is a write which was needed to use the length of the target minus the longest increasing subsequence for the those indexes like the low end too now let me just run it to check if it works yeah as you can see it works now let me submit it to Zack if it can pass for all the testing cases yeah as you can see let's start with for a few seconds as you can see it passed all the testing phases and it's pretty fast and by the way the time complexity is just all in login now let us just check why I use left because the numbers inside of the target as you can see that there are numbers inside of the Target and with these numbers the index is always being unique if the index is unique so it means for the index it is strictly increasing thank you for watching if you think this is helpful please like And subscribe I will prepare more lead code problems like this see you next | Minimum Operations to Make a Subsequence | dot-product-of-two-sparse-vectors | You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates.
In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array.
Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._
A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not.
**Example 1:**
**Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\]
**Output:** 2
**Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`.
**Example 2:**
**Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\]
**Output:** 3
**Constraints:**
* `1 <= target.length, arr.length <= 105`
* `1 <= target[i], arr[i] <= 109`
* `target` contains no duplicates. | Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero. | Array,Hash Table,Two Pointers,Design | Medium | null |
1,927 | hey everybody this is larry this is me going with q33 of the bi-weekly contest 56 sum game so of the bi-weekly contest 56 sum game so of the bi-weekly contest 56 sum game so i actually did not solve this during the contest though a lot of it's because i spent too long on q4 i actually got this near the end after i kind of went skip to q4 and then i came back and then i would refresh mine and with that mind i was like oh yeah um there's this observation that you have to make and that's what i did um hit the like button hit the subscribe button join me on discord give me some support give me some love um and if you like discussing these problems right after the contest join me on discord because that's what we do um so this one um it's a game theory problem i to be honest i think if you do not have to gain free background it's going to be very tricky maybe you could guess the solution or ideas but it's still a very tricky problem um and i saw this actually a couple minutes after the contest so you so yeah it is what it is like i said uh mistakes were made but the idea here is you have to kind of think about okay let's reduce the there's a couple of observations to make let's reduce this problem um as much as we can right so number one observation is that okay if the question marks on both sides and bob wants to keep it the same it doesn't change the answer because and what i mean is that you can remove the question marks on both sides because if it is already the same then bob can just choose the same number that you choose right so if you choose x then bob will choose to on the other side x uh x as well so they cancel each other about it out in that way because bob wants to keep it the same and so then he and so then the second part is that okay so you have question marks and a number that you're trying a target number that you're trying to reach right and here of course if it's neg um depending on how you want to count it but there is an impossible situation um where basically if it is if you cannot get to that number then it's true just because you know for example i think this is on example two which is that here you're trying to get to seven um if you try if you just go to nine then like you know you'll make it possible or also if you have the other case where if you have a question mark on the left um yeah um so it's not gonna be possible um for example if they're numbers on both sides and you already have a bigger number on the side of the question marks then it's not gonna be possible because you already have bigger numbers than the other side so you can make it easier true right one more observation is that um and i keep right because i keep mixing this up one more thing is keeping in mind that if the number of question mark is odd uh after you remove them from both sides though you can only remove even numbers anyway so if the number of question marks is odd then alice always wins because if you have the last move you're not going to change it so that is the same and so you have to choose literally any number that isn't than one that gets you the uh to lose and you win right so that's basically what i have here and then the rest depends on this idea of a nims game and the nims game is that you could choose any number from zero to nine um and you can kind of the reason why i had a lot of issues during the contest with this one was that i was off by one because i forgot about the zero um so i was just choosing between one to nine so i was subtracting 10 for whatever reason um and we can look at some of my wrong solutions hang on but yeah so but if you were to google i would look up nim's game or nimbus i know it looks like a typo but it is not a typo um but basically the idea is that because you can choose between every number from zero to nine you can think about the saved states right um in terms of the states that because bob goes second if we are able to get back to a safe state and um if equivalent quote a winnable state on bob if bob is able to be on a winnable state and you're in that state then bob can get it to the next winnable state and it turns out that for every round which is two times the number of turns um if you're on a multiple of nine you can always get to the previous number of nine so you can kind of look at this deductively or inductively where okay if the zero turns left you want the sum to be zero right that means that the two turns left bob wants the number to be nine because why because if it is on any number let's say 10 or maybe a smaller number let's say eight well if it's eight or smaller you just choose nine and you're it's not going to be even if it's 10 or more you could just choose this to be um you can choose this to be say two and then you have eight and then bob goes um oh wait no if it's 10 or higher you choose the number zero and then bob cannot win because if bob just choose nine you cannot win right so the only number that bob can win is nine and if it is at nine you could choose any number and then bob wins right so that's basically the idea and these are i believe called winnable states for bob and once you get that you can kind of inductively choose okay the four turns left it's 18 and so forth dot and the rest is basically just an implementation of this i wrote a lot of use this code to be frank but that's basically the idea is that okay i mean the count delta is the number of turns basically the number of question marks um and of course you can just choose this as distorted by two but then of course i just multiply two on the other side and that's basically the idea um i should have been able to solve this during the contest but i if you look at me salvage live you'll also see that i actually confused it with um because i thought that for whatever reason i thought that it um the lowest number is one so then i had 10 on both sides but as i came toward the end i was able to come toward this but i just ran out of time to be honest because uh because i saw q4 with five minutes left and i wasn't able to solve this quite well this is my last attempt before i ac i was able to see it right after the contest but yeah i had some while loop and i think if i had this he goes to nine then i would have been able to be right um with if i changed some other things because i was just i think i saw i submitted this with like 20 seconds left or something so i was just it looks very awkward right but yeah so what's the complexity here well it's gonna be linear time because you have to go through the way to you have to go for the string to kind of do all these counting but after that it is just over one um that's all i have for this one let me know what you think uh hit the like button hit the subscribe button join me on discord um watch me sub it live during the contest and then after the contest um next okay so bob is trying to get them to be eco and alice is trying to get them not to be equal that's really weird okay it's judging oh man yeah well okay fine silly mistakes again i knew that one but oh man wow larry this is going to be rough two penalties already on silliness uh okay um some of the digital can return truth alice wins hmm seems like a hard one to be honest but that's going to be hard if only i didn't make silly mistakes on the con in this contest okay i don't kind of do this one i wish i got do the other two without silly mistakes then um it would have been probably two problems would have been a good score um how do i even face this bob always wins hmm that this is a hard problem actually okay so the first thing is that the two question marks they cancel each other out so then it's just fun and it's just is it possible to do one side more than the other something like that maybe that's maybe that sounds right um okay i don't know why they don't just give us two strings though it's a little bit weird but maybe that's fine okay um i was thinking about writing a helper function but it's fine okay is it always possible um let's see and they're the same then we return whether the sum is the same is that true oh yeah opposite of it because if you're the same then bob will just do your move oh that's not true and if the sum is different what happens let me think about this they're the same and the sum is the same let's just type it out and return true because bob can always move it otherwise can bob make it the same oh alice has to make it magical okay whoops so if they're the same then alice then bob always wins because bob will just keep it the same okay otherwise how many people have countess this is pretty hard one only three people got it so far every time of course i am very sloppy bob is trying to keep it the same but we can actually just subtract them because if it helps we probably just because for atlas it makes sense for it to just choose whatever number so then you get the delta right and you always get fives so i keep forgetting about once you're not the same so if this is if the sum is equal then this is force because bob can always do it otherwise for every number that you do no then it's just returned true because they cannot match you because you just choose the side for which yeah because you just choose the side in which it is lower and then you just or higher and then just choose a nine and then they can't really match okay i believe in that then um countdown okay so now count has more than so right what happens if you've got more on the count side then all right and then basically for count hopeful i think you could do this in with actual math but i am trying to figure out right now right um because i'm a little bit dumb and it doesn't really matter um so for each different number because bob will always just match you so for here whatever you do there's a five different delta for everyone okay i phrase that so that's 10 for two numbers okay ugh this is so hot i'm so bad okay man there's a mosquito flying around maybe just a little fly but still annoying no that's not it they say they could catch up five at a time for every two numbers and it doesn't really matter what you do okay and then if something is greater than zero return true you win otherwise you turn for something like that i don't know this is right i have to figure it out force 4 seems a little bit wrong let's basically okay this is there's two numbers w2 is seven maybe this one is wrong actually okay so the directions matter i was thinking that it doesn't but how'd i think how did one do this maybe i optimize a little bit too early okay fine let's do that one okay and now we can do the thing of count delta is equal to this thing and then sum delta the absolute value of this okay and then now we can do something with the signs if some doubter is so this is negative what happens that means that we can go over when because it's our turn okay i mean it's good that we have one more thing but so now we have two okay so we have two extra on the right side not negative nine on the left or plus nine on enough so i so two of these cancels out so i have this essentially let's subtract this so then i have nine and two question marks so whatever i do the other person will get it how do i um simulate that i have some filter solved okay if count delta is equal to so now it could be either two one or zero now it could only be going to be two or one so this is two and it's our turn then what happens if it is between am i is that right did i mess up the math because basically if i go cancel but then i could just choose nine right maybe my math is wrong or my assumption is wrong basically if the two numbers left i can choose any number they could choose free zero okay so if it's nine it's we are good it only if it's nine because if it's eight then we choose nine and we're over i think that's the problem if it's ten we can choose zero and it's over so it's only if it's nine huh if some delta is equal to nine return true return force if there's one number left we're done so if there's only one number left we can always choose a number so okay so we return true here as well is that true that's such an awkward um such an awkward thing well would be better if this was actually right though but so okay so force true force i mean i have force on the last one but why is this true so okay so we have two left and the answer is negative seven so this should be oh i mixed it up again if it's nine then we cannot win otherwise we win otherwise if this one digit we win again okay well how is this working again come on did i get the signs well is it negative nine okay so it's negative nine i don't know if this is right but i'm spending a lot of time so i hope i get one uh i was hoping to get an answer to kind of help me figure it out i was hoping to get a shorter answer to be honest as well but okay i am very bad today so i returned true too early time oh i mixed up the signs here so okay is that true okay because we have 12 numbers left with 54. i don't know this is necessary is this necessary let's try again oh wait did i not this is the same case so i'm just being sloppy as well but we expect it to be false okay why do we expect this to be false i am really bad today friends oh whoops i got all my signs wrong essentially basically to be honest but okay so we have five of these so it goes to negative four um so basically did anyone skip ahead enough well you read that q4 really quickly so this is not looking good for me a lot of people did q4 first so maybe i should have done that way but okay two numbers left negative one so it is definitely true that you would win but according to this you're not supposed to and i gave two wrong answers because i'm dumb but wouldn't you just do 919191 hmm you have 12 numbers on the left or the right whatever and you have 54 numbers to make up right so you do one and the other person will do nine right trying to catch up oh but then on the last one you may not do nine you try to get it to five so okay so we have four left we have four is 14 so then what does that mean when we have four numbers left then what are the possibilities if we have four numbers left then i will do a nine if i'm alice i do a 9 14 we go nine so then and then we have five and we're already not possible right so oh no because if i do a 9 then no i don't get it did i miss do the math it is four numbers left and it is 14 what happens oh maybe i'm too aggressive on them because it is true that 14 is not good but you will not go to 14 because it would be more earlier recursively huh okay let's skip ahead painful but um i thought it didn't matter that's why i didn't do it that way but this one i think this is close but i quit it is not basically you want to get to nine here can you are you able to do it okay that's what bob is trying to do right and the question is how do i do it so this uh i mean you have to do it recursively right so if 2 is negative 9 can we get to negative 9 to whatever right if count doubter is odd then we return force or return true because we always do it otherwise this is even right even then it means that whatever we do they're going to just do 9 until okay there's four speakers here i don't think this is right but yeah i don't think i didn't think it was right i just yelled out because there's a minute left but so i just that was definitely yellow it's something weird like this though um basically it's just game free of okay so there's nine is a stable point and then okay i gotta stop talking basically they their first fingers and can we get to nine right if something um i think this is close to be honest i feel like this is close but uh it's but it is not quite um all right okay uh i'm gonna set up streaming this live i mean i don't know i should have gotten q4 much faster i was dumb on i was stubborn on it um this was a tough contest i don't have to cute three because it's one of those game theory ones what the hey but um that's basically what i was trying to do but i think i messed up a few things um i think i was gross i was pretty close but uh um okay uh that's all i have stay good stay cool thanks for watching uh hit the like button hit the subscribe button join me on discord thanks for your support and i will see you next contest bye uh actually i'm gonna finish doing this first because yeah um because i was close but i spent too long on q4 so i didn't have time to come back to it i think i got to the point where um yeah like we like look at everything um that's the idea uh yeah and i had something like that but i wasn't able to do it um well oh i think if this was nine maybe this is right i think i wasn't um okay maybe not there's still quite a few things wrong but um something like that i think i mixed up the signs but the idea there is that it gets back to a stable point um yeah i got it right after the contest yeah thanks for watching thanks for the support hit the like button to subscribe and join me on discord let me know what you think about this contest and this problem and this explanation i will see you later stay good stay healthy stay cool and a good mental health bye | Sum Game | maximum-ascending-subarray-sum | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace `num[i]` with any digit between `'0'` and `'9'`.
The game ends when there are no more `'?'` characters in `num`.
For Bob to win, the sum of the digits in the first half of `num` must be **equal** to the sum of the digits in the second half. For Alice to win, the sums must **not be equal**.
* For example, if the game ended with `num = "243801 "`, then Bob wins because `2+4+3 = 8+0+1`. If the game ended with `num = "243803 "`, then Alice wins because `2+4+3 != 8+0+3`.
Assuming Alice and Bob play **optimally**, return `true` _if Alice will win and_ `false` _if Bob will win_.
**Example 1:**
**Input:** num = "5023 "
**Output:** false
**Explanation:** There are no moves to be made.
The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.
**Example 2:**
**Input:** num = "25?? "
**Output:** true
**Explanation:** Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.
**Example 3:**
**Input:** num = "?3295??? "
**Output:** false
**Explanation:** It can be proven that Bob will always win. One possible outcome is:
- Alice replaces the first '?' with '9'. num = "93295??? ".
- Bob replaces one of the '?' in the right half with '9'. num = "932959?? ".
- Alice replaces one of the '?' in the right half with '2'. num = "9329592? ".
- Bob replaces the last '?' in the right half with '7'. num = "93295927 ".
Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.
**Constraints:**
* `2 <= num.length <= 105`
* `num.length` is **even**.
* `num` consists of only digits and `'?'`. | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next | Array | Easy | 2205 |
210 | to solve legal question 210 course schedule number two and it's a median legal question so there are tons a total of number of courses that you have to take let's say look at this example the number of courses equals two and labeled from zero to number of courses minus one so basically if number of courses equals two then you start from zero is you have course zero and the course one right and let's just do this and then you're giving array prerequisites where prerequisites i equals to a i b i indicates that you must take course b first if you want to take course a so the course b is the prerequisite here for example like the pair 0 1 indicates that take course 0 you have to first take course one um and then return the ordering of the course you should to you should take to finish all courses if there are many valid answers returning any of them if it's pause if it is possible to finish uh it is impossible to finish all courses return the empty array so let's take a look at the example here the number of courses is two prerequisite is one zero basically means that in order to take one you must take zero so the one the second one is the prerequisites so if you first you have to take zero first and then the correct sequence is zero and then you take one is it possible to finish this uh both courses it's possible so then you return the order zero one right and then if you take a look at the second example here number of courses equals two so basically zero one two three right prerequisites is in order to take one you must take zero you in order to take two you must take zero first so you have to take zero first and in order to take three you must take one and in order oh in order to take uh three you must take one and then in order to take three you must take two so there are total of four course to take three you should have finished both course one and two and both course one or two should be taken after you finish course zero right so one of the correct ordering is zero one two three and then if you take a zero one two three and it meets all the requirement another correct ordering is zero two one three and you return any of them they will consider this is a correct answer and a number of courses equal one and the prerequisite equals um empty so then the output is zero and there's the constraint here and number of courses and the prerequisites and if you take a look at here and this is a highly asked a frequently asked question in the interview and amazon asked this question six 31 times in the last six months so this is a question that you should absolutely be focusing on um let's take a look at the question here and by looking at this problem it's um it's basically or um our graph problem if it's if there's a cycle in the graph then it's impossible for you to finish all the courses at all because if you if let's say if the prerequisite is one zero and another pair is zero one if they give you some prerequisite like this that means in order to take um one you must take zero and this one is in order to take zero you must take one how is that even possible right this is totally impossible but in graph that means like there is a cycle between 0 and 1. in this case then you have to return minus 1. so if you think of a graph perspective this question will be easier to solve so you basically write the prerequisites to a graph first and once you do that you want to um do that for search on all the courses right and also it's prerequisites how it works is that how do you mark that the things are um or are psycho is that you can totally use uh a right to um to set all the number of courses for example like course zero and you can set to zero and course one you set it to zero so basically all the courses that you set a value as zero first and then you run that for search and when you go through each of the list and then when you visit a node and let's say you visit no zero right you first want to set it to uh minus one is just an example you don't have to um uh say that it's minus one i'm just using this as an example so if you um say minus one that means i mark this node zero basically zero course as um as visited and then after the xero course is visited i wanna before we do that what we can do is write the prerequisites to a default act and when i do that is zero is basically um empty right and if i write uh one has a prerequisites as zero it would be something like this so it's easier for you to look at it when we run it um so once prerequisites is a zero and when you visit it you want to set it to -1 you visit it you want to set it to -1 you visit it you want to set it to -1 and after i visit it right i want to continue to run that for search let me write this so it's easier for you and this is courses and this is zero course and this is one course at the beginning you want to you said in the uh array you set both uh value to zero for each courses and then when you visit the course zero and you set it to minus one and then you wanna go through no uh course zeros neighbor course zero if you look at the default director here and there's no neighbor at all and um if and you want to run if there is a neighbor you want to run that for search on course xero's neighbor to check the value and then after you finish visiting course 0 you want to mark it to something like one so just a indication that course zero is visited and after you add change the value to zero what you want to do is um this is the result right you want to append the result to course zero to the result and then the next step what you're going to do is you want to run the different search on the second node which is node one and when you run developer search on node one you first wanna um check if it's already visited there's some base condition but when we visit it i wanna change it to minus one basically meaning that i this i visit this node right and then after i visit this node i want to visit one's neighbor which is the prerequisite which is course zero in this case and then after i wonder i want to visit zero course zero and you can see course zero is true in this case it's empty right um i wanna change the node to so that means that if the course zero is true and then that means i can visit course one as well and then after that i'm gonna change the value of the array to for course one to one that means i visit it and i wanna append the result to the um end result so then you get the output at zero one that's basically the dollar process and i'm gonna show you how to do this in code so let's write this as a graph and um i want to write it as a default act and it's a list so then i will set result as an empty uh array here and for courses and the prerequisites basically i'm going to write this prerequisites uh array that into the default diet so for courses and the prerequisites basically this pair in pre-requisites in prerequisites what i'm going to do is in the graphs um courses i'm going to append the prerequisites it's a directional graph so you want to append the prerequisites to the courses so basically it will be something look like this the ones uh prerequisites is zero in this case after you write it right and then for this uh visit array that we mentioned that i want to use our array so basically in python you can do list comprehension i am range um number of courses so after you doing this the array will look like the array will basically look like um this like zero so this is for course zero this is for course one that's how it looks before you visit the next part i'm going to write the data search function and the default search i want to run on the courses every time right so if we want to think about the base condition is that if uh the visit uh course the course that i visited if it's equals to minus one um like i mentioned every time after i visit it's minus one that means it's already visited if we are visited again then i'm gonna have to return fourth because there's basically a cycle in the graph and then if a visit i want to say the course equals 1 that means the course has been visited in the end remember i change this value to 1 that means i want to return true in this case so that's when the things is done and this is the base condition then if not then the first thing i'm going to do when i start visiting a node basically the when i start visiting a course is that i want to set the course to minus one the first thing i'm gonna do is change it to minus one right so basically meaning i am visiting this node and now i'm gonna say for um i in uh it's actually pre in um graph uh and graphs um courses so basically this is the neighbor for the prerequisite in the graph neighbors i'm going to visit the name neighbor do the debt for search on the pre do that for search on the pre so if the that research on the prerequisites is false then i'm going to return false otherwise i'm gonna add the visit courses after a visit if it's true then i'm going to mark the node to 1 change the node value to 1 in the list and indicate the node has already been visited after i visit this node what i'm going to do is i'm also going to have to append the result basically which is the courses append the courses to the result right and in the end i want to return true that means that the deaf research runs through and that there is no cycle and that the course can be visited and then that's it for the def search function so the next step i'm gonna call the developer search function so basically for courses in range number of courses so basically for every course in this number of courses what i'm gonna do is i'm gonna run that first search on the courses and if not basically the uh result is false then i'm gonna return just an empty array basically indicate that we can't take this course and then if it's true then i'm going to return the result let's see oh sorry i forgot if -1 yep it went through so i hope this is helpful and let me know if you have any questions and please like my video and subscribe to my channel and i'll see you soon bye | Course Schedule II | course-schedule-ii | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** \[0,1\]
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\].
**Example 2:**
**Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\]
**Output:** \[0,2,1,3\]
**Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\].
**Example 3:**
**Input:** numCourses = 1, prerequisites = \[\]
**Output:** \[0\]
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* `ai != bi`
* All the pairs `[ai, bi]` are **distinct**. | This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS. | Depth-First Search,Breadth-First Search,Graph,Topological Sort | Medium | 207,269,310,444,630,1101,2220 |
112 | hi everyone welcome to my YouTube channel and in this video we will look at problem 112 from the code so this is the continuation from my previous video there are four problems in this you know in this series path sum so this is the second iteration of the problem series so here is the problem statement and post this video for a second try to come up with your own solution and yeah let's look at my solution together so this problem is very similar to the previous one but then we just have to find the existence of you know the path from the root node all the way to the leaf node we do not have to return like the exact path we just have to find if such path exist then we have to return true if not we do not return you know we don't return anything so in this case uh in this if there is no such path then we return Force so we in the in this case we have no typically we have what when we run TFS we have to run we have to look at his left child and then we also have to look at the right child right and then we look so left child for this node you will be looking at this four and so we will basically Traverse all this like you know left sub tree and if there is a path such that the root node all the way to the you know the leaf node and that's the sum of the paths equals to the Target sum then we return true so visited left this will be returned true in this case 5 4 11 and 2 this is a belly path so this one will be true and then if this one is false then it doesn't really matter because we will be taking visited left or visited right so in this case you know we will have true or false so or in the case we will get through that's what we will return and vice versa if this part is false and if this the President right is true that means we have a value path in this right subtree then we in this part will return true so that one works and if both if no such paths exist then we will just return Force right so that's for this problem and let's look at the code and see what we get okay so here is the code and let's run this and see what we get yeah so that's for this video and if my video helps please give me Thumbs Up And subscribe to my channel and I will see you guys next time bye | Path Sum | path-sum | Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | 113,124,129,437,666 |
236 | we are given a root of the tree and also two random nodes of that tree we need to find out the lowest common ancestor of these two random nodes for example if P equal to 5 and Q equal to 1 are the two nodes given then the node 3 will be the lowest ancestor common to both these nodes 5 and 1. an important thing to note here is that a node can be an ancestor of itself that is if P equal to 5 and Q equal to 7 are the nodes in that case the Note 5 will be the lowest common ancestor of both 5 and 7. to find out the lowest common ancestor what we can do is run a DFS we are required to find two nodes p and Q so let's look at different scenarios of occurrences of these two nodes the first scenario is we found one node on the left subtree and the other one on the right subtree in this case we have found out a total of two nodes at the current node and therefore the current node will be the lowest common ancestor of those two nodes the second scenario is we found one node on the current node itself and the other node on the left subtree in this case we have found a total of two nodes at the current node and therefore the current node will be the lowest common ancestor of those two nodes the third scenario is we found one node on the current node itself and another node on the right subtree in this case also we have found a total of two nodes at the current node and therefore the lowest common ancestor of those two nodes is the current node in all the three scenarios the nearest node at which we are getting a total of two found out nodes is the lowest common ancestor So based on this observation let's take an example and solve the problem in this example PS5 and Q is 1. we found zero required nodes at six seven four and two so let's return the result to the respective parent nodes at node 5 we have found one required node on continuing the traversal we have found one more required node so at node 3 we have found a total of two required nodes so this is the last common ancestor now let's take another example here PS5 and Q is 4. this is the lowest common ancestor now let's call the solution let's have a variable initially set to none for storing the result we'll be returning it we will write a separate function for traversing through each nodes recursively we will start the function call with the root node of the tree we will recursively Traverse through the left and right nodes in the beginning in this function we need to check whether the current node is one of the node we are looking for if yes then we will set this variable to 1 l0 we will then check whether the total number of nodes found out at this current node is equal to 2. if yes that means we have found out the lowest common ancestor and hence we will be storing the result in this variable since we are accessing an outer variable from this function we must specify it using the non-local keyword so at last if we have found any node from the left right or the current node we will be returning 1 to the current nodes parent if nothing found then we will be returning 0 to the current node's parent node also we need to put some checks at the beginning of the function if we have reached the end of the tree or if we have already found out the result then we need not continue the recursion and we can return zero let's try running the program it's working see you in the next video | Lowest Common Ancestor of a Binary Tree | lowest-common-ancestor-of-a-binary-tree | Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the tree. | null | Tree,Depth-First Search,Binary Tree | Medium | 235,1190,1354,1780,1790,1816,2217 |
850 | Hey hello there today I'm looking at the question 850 rectangle - so the question 850 rectangle - so the question 850 rectangle - so the question can be pretty much the summarized with a single image here that's the question provides we have a 2d plan and we've got a bunch of different rectangles we can off different size they can appear to different places and they can have overlap which is with each other the question is asking us to calculate the total areas that are not captured by those rectangles in inside this 2d plane so that's that question so as a input what we have is a list of tuples where each topo contains four numbers x1 y1 x2 y2 and x1 y1 is the coordinates for the bottom left and x2 y2 is the coordinate for the top right corner for the rectangles because it's rectangle given two numbers we can figure out the every edges kind of a parallel to each other so two to the other two like this to the other edge and perpendicular to the other two edges so you get the idea be having those four numbers we can figure out the area and location for that rectangle in the 2d plane so now our question is to calculate the total area obviously we want to remove all the duplicate we don't want to double count to the dippity that's where the challenge is so Coleco about and solve this so let me try to illustrate this with a thought here so we have a three different rectangle here to make the problem a little bit more complicated I have that to be separate and also have some no and also the rectangle not in the same quadrant so making problem slightly more generic so that's just imagine that we have a line that we can use to swipe through this 2d problem space and the we were triggered this invent when we add to the left hand side left edge left I call it side I don't know of this first rectangle that we have you are triggering land saying that he from here I have openings and then during the process I'm swiping through this space depends on how many how far away I'm swiping from the prior invent triggering exposition I can basically say that the opening the size of the opening interval are multiplied by the lens that I have traversed doing this line swiping that area basically I can say was I passed that the area here sorry why is that let me do black so once my line is as long where's my line swiping through this 2d space I can say that the current opening multiplied by the lens so the last event has been realized I can add that to some kind of total and then here I'm triggering two more events because my opening has become a little bit more complex I have 0 to 2 and 1 to 3 and also negative 1 to negative 2 that doesn't matter we can just we just remember those openings and keep swiping now at this position we will trigger another event at this time so we can say that through the time between this event and the previous event I'm just gonna realize all the openings that I had and calculating the areas and add that to the total so we basically gonna mark those little opening multiplied by the past I worked as well since last the event you know adding those to the total and then just keep moving you get the idea once I pass the very last rectangle if I do this according to the way of describing I pretty much added all the areas together I know there is no double counting the slightly difficult part is basically when I were so that will be the case here let me try to show it when my line is triggered by inventor at x-value to hear my opening is looking x-value to hear my opening is looking x-value to hear my opening is looking like the lines on the right hand side so for the openings we have a sweet different line segment and so I need to know how long it is you know how much I can multiply the by the you know horizontal lens I have worked too soon from the last event triggering so I have to basically find something to multiply one to mark the four little you know the one area here and the other area here add the number to the total area so how do I get this if we if I transpose this kind of opening you know from 0 to 2 from 1 to 3 and negative 1 to negative 2 flip that over to be horizontal it seems like it becomes another line squeaking problem so we're basically just gonna swipe this from the bottom minimum you know deep down in the axis and swiping towards the high end and see we have a line segment of lines last one and then we have another line to line segment but the overlap so they can combine to be of size 3 you know that's pretty much by moving this time so that collapsed those two intervals into one longer one so the lens for that longer one is three so in total I have four units and how far I have moved in horizontal that is one so I multiply 1 by 4 and add that to the total that's equivalent to say that I basically are marking those things adding those areas to the total so now we see that this problem basically it becomes a combination to a nested a swipe line a line sweeping problem the parent line sweeping is one direction the other one you see in the you know perpendicular direction the other direction so it's those two combined and the investigator basically as we encountered the left-hand side of the encountered the left-hand side of the encountered the left-hand side of the rectangular that's when we add this you know y1 y2 to the current open and the other type of invent is when we swipe the line through the end of that rectangular we want to remove the open 0 to 2 in this case I'm showing here from the current open yeah so that's pretty much the solution just trying to code it up by really quickly yeah so we convert this rectangle into two types of humans so that's the first part third list of rectangles to invent and then we have a helper function to do total interval Landis calculation I not to count duplicate but you know just return the total as the right hand side line so I being a showing you what we're shows by that the third thing is to do the bigger sweep line to calculate the area so that's these three sections basically so let's just do this to this conversion first so what are we going to put on this here is going to be you know that when we do the line sweeping in to trigger the events its triggered by the exposition in my illustration here and there are two types open and close so that's what we need for the invent and for every event there are two type of information y1 and y2 so that's going to be either add to the current open or remove on the current open so we have to put four elements on as I invent the exposition where this invent is triggered the type of invent and also the size of the open that should be added or removed so that's four elements X 1 is going to be open let's just put open s1 just comment what's up and be on there a couple of X type y1 and y2 the closing event is that it's indicated by one because we won't sort them we want to sort this based on the exposition and then by open a close yes we want to do by open and close does it matter no try that but here for simplicity I would I was sort first by exposition then always deal was open first I will figure out does it matter if we do the closing matters so the reason we sort is basically we want enumerate over all the events so that would basically simulate this actual Lange sliding otherwise if we don't sort that then it's not guaranteed that we are processing those events in the order if as the line swipe so that's this invent processing then we're just going to do this area is zero in the beginning and the previous triggering is going to be in a variable here initially to be in minimum so that's where the line coming from it's from the far left you know super negative number just gonna put the two things modular which is going to be 10 to the power from 9 plus 7 or the question requirement and we have our inter minimum so initially the previous invent triggering position is the inter minimum and then we have a list of opening bands open into intervals gonna be initially empty as well so we're just going to do invent in humans when the event is triggered the first thing we do is to you know try to paint the past by rectangles portion to be black add the number to the total so we're gonna do a helper function called maybe some kind of by what do we need the previous in bang trigger and the current inventory green position that's going to give us the one of the multiplier we do and the other thing is the current opening if we define the function here then the we has direct access to this but we still need to pass in two numbers to it so let's just call this getting earlier you will need to those previous and current and if you will return the area we want out so just an ADD area to this function call to the area previous and color so let's just unpack this every event the first element is the current position so to current tight close because close is one and why one night you unpackage from this event adding that to the area then we deal with this embed if closed if it's closing we will remove a y1 y2 pair from the open intervals otherwise we would do is to add this to the interval and we will want to sort of the open intervals the reason being that the helper function would be silicone until this line sweeping - - calculating the this line sweeping - - calculating the this line sweeping - - calculating the total area so we're given the multiplier basically as primary - this multiplier basically as primary - this multiplier basically as primary - this another smaller line swiping whenever we swipe through a line segment we want to multiply the length of the line segment with the multiplier so let's go back and cut this off its gonna be very rare to be zero and the previous is gonna be in to minimum that's when we swipes through you know after flipping it looks like from left hand side but actually this will be from water from negative on the by volume and off in my example I'm just gonna do this left right this open intervals we're gonna update this previous position to be the maximum between the current one and the previous and whatever the difference between the right hand side at the right and the left of the current the previous left you know it's gonna be you know if we swipe so here we update previous to be the left point I have here and we look at the right hand side the difference can be multiplied by the multiplier and add to the area so that's going to be right subtract previous and multiplied by the this current let's put X here so that I've done or I can just put a multiplied here so instead of passing this to I will pass the difference and then after I swipes through this I might encounter the smaller special case I guess as to I need to sink handle the special case when one line is longer cheese and then the other line basically is embedded in there and we're gonna trigger an event after the area has already been multiplied we need to avoid that so after we triggered the embed front left-hand side we're gonna update to the left-hand side we're gonna update to the left-hand side we're gonna update to the previous to be equal to the minimum equal to this maximum at the right-hand equal to this maximum at the right-hand equal to this maximum at the right-hand side so that when we trigger the event from the inner line segment we not going to be doing this addition so that's handled by after we do this area realization we move this to the maximum between R and the previous so when we do when we encounter the inner line segment here this line doesn't change the previous value but we want to have this to be zero so this will be negative if we because the right-hand side of the if we because the right-hand side of the if we because the right-hand side of the inner line segment interval it's less than previous so that's the difference between here and here that's negative so we're just going to max it to take a max between zero and that so that effectively cancel out the avoided the duplicate duplicated a calculation for the area so that's that yeah that's pretty much it we're just going to return this area and after we processed so back to the men sweep lying on reason I have to be processed those two events what are we going to do is to updating this previous so that's pretty much it let me quickly check for problems I shouldn't initialize this to the intr minimum I have a better prior like a sneak peek into the first interval and just grab the left hand stuff on there because otherwise this will be crazy this difference would be quieter but it's not but you should be it shouldn't be realized like I see a wouldn't because the open interval at the time the first thing bandit will be zero so it would be a zero do I need to lets justify this I'm so bad to buy the first there and also my kid seemed so carried this for this example question yeah let me try to sort this by the negative order to see if that changed things not really okay does it matter really if we handle open first then closed or closed first and then open the area realization adding you swipe the area to the total doesn't really matter but if we have situation like it just opened and the close at the same time we would definitely want to do close first and open second otherwise does that remove one more occurrence with just one if it's removed one occurrence is fine but if they remove all that currency will be problematic but safeties to be safe we can just do the remove first and then to the add so if we want to do the remove first we once sort this by have the close to be first so since closes one larger than the open we can actually sort this by the inverse for that's what that makes sense let's try it's mainly no it's not working I got a really big number but here it is 49 and it just though I need a little modular I really have to run anyway let's try this time yeah okay it's accepting so that's this question is too long sweeping approach pieced it together we have the bigger line swiping to you know to try to color the rectangle parts mark those as areas we have already visited so we added that number to the total and each individual invent before each leader each individual open and close event has been triggered we have a smaller line sweeping problem to you know add the calculating area it's the multiplied by the horizontal diff lens we worked through with this man line swiping and the you know the total lines for the can potentially overlapping opening intervals that we have so it's a as two line sweeping problem fused into one and in the line sweeping even a smaller line sweeping is actually more challenging because they have this there's a special case you want to hand them and I guess the order here I need to figure out that does the remove one or remove all but for safety we always do the remove first then to the add so that case the order if we process the invents in the order will always be able to have the correct opening intervals on the solicitor here yeah so that's the question I have to oh sorry the time and the space analysis how to do that so let's say that we have n different rectangles so the size of the invents will be 2 n so this loop here is two men and each of those loop here we can see that we want to go over all the intervals in this gain area call that's another for loop so it's n squared and so it's N squared but we also have a log and sorting here so how much is that really is it and multiplied by n plus log N that seems to so we have an this bigger parent loop inside each loop we have this function call which is another end and then after the function call we can potentially have a sort of--sort is can potentially have a sort of--sort is can potentially have a sort of--sort is n log n sorry so it's an N squared log n in time that's so the two multiplied together we got the total run time to be an N square root of e n so that's a run time I have to go | Rectangle Area II | insert-into-a-sorted-circular-linked-list | You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**.
Calculate the **total area** covered by all `rectangles` in the plane. Any area covered by two or more rectangles should only be counted **once**.
Return _the **total area**_. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** rectangles = \[\[0,0,2,2\],\[1,0,2,3\],\[1,0,3,1\]\]
**Output:** 6
**Explanation:** A total area of 6 is covered by all three rectangles, as illustrated in the picture.
From (1,1) to (2,2), the green and red rectangles overlap.
From (1,0) to (2,3), all three rectangles overlap.
**Example 2:**
**Input:** rectangles = \[\[0,0,1000000000,1000000000\]\]
**Output:** 49
**Explanation:** The answer is 1018 modulo (109 + 7), which is 49.
**Constraints:**
* `1 <= rectangles.length <= 200`
* `rectanges[i].length == 4`
* `0 <= xi1, yi1, xi2, yi2 <= 109`
* `xi1 <= xi2`
* `yi1 <= yi2` | null | Linked List | Medium | 147 |
1,673 | hey what's up guys this is jung so this time 1673 find the most competitive subsequence so this is today's daily challenge so you're given like integer arrays nums and a positive integer k and you need to return the most competitive subsequence of numbers of size k and an array okay so that's the definition of subsequence i think everyone already knows that and then the definition of comparative is the basically it's the it's a lexical graphically uh smaller subsequence for example if this one three four and this one three five since this one uh one three four is smaller than one three five right compared compare the values one uh one by one and then the smaller one we call it uh more competitive so actually so the uh and the example uh we're given here is like that with all the uh the possible like subsequences we just need to find the uh the smallest right the that's what it's called uh most competitive which in this case is 2 6 is the smallest among all of kind of subsequence so and now so then the problem comes down converts to which we need to find the smallest subsequence whose length is equal to k right um yep so and that's basically the idea and if we take a look at this example here right the uh let's say we have example two here and the uh the answer right so the answer is like uh two three four so we have two first and then we have four uh we have four but then the next one is three but which means okay so three smaller than four which means that we can replace this four with three and then we have another three five and then four smaller four is smaller than five that's why we can just replace this five is a four and then we have a nine but nine is greater than four and six is also greater than four that's why we have this answer two three four and similar effort for this one right so we have three five and then we have two smaller than five so we can just move this two basically we can replace this these two to all to both five and three and then we have six so by looking at this one actually so this is like the very similar to like a monotonic q right so basically we're trying to maintain like an increasing q and every time when we have like a greater numbers a bigger numbers here and if we have if we saw like a smaller numbers basically we're trying to pop that greater number out because remember our purpose is to find the uh the biggest sorry the smallest subsequence okay but we cannot just blindly pop all the uh odd numbers that's uh who is greater than the current number because we also have like this kind of uh k uh limits so for example if we have like what if we have like uh let's say 9 8 seven uh one and three let's see if this isn't the numbers and the k is equal to four right so we have eight right uh sorry we have nine uh so yeah so we can use this example so we have nine here right so and then the next one is eight so eight is smaller than nine that's why uh let's say we have an answer here right at the beginning we have nine but the next one is eight so we can just remove eight uh replace pop this knight and we push this eighteen but then the next one is seven but can we uh can we pop eight and then push seven we can't because if we pop eight out from the answers then we only have three numbers left it won't be even be able to make like a the substring of k length so that's why you know in this case we can we have to just uh append everything in the end so that's why the answer for this one is going to be a 8 one uh eight seven one three so now we have our i guess we have our complete uh algorithm so the algorithm is gonna be uh you know i read uh isilon so let's the first one is that let's say the current one the current number is smaller than the top one in our stack and the remaining numbers of is enough to make this uh length k uh sub uh subsequence then we can pop the current one the cut we can pop the top element from the stack else we just need to stop um yep and another like condition we need to consider is that let's say we have like this one two three four five six and then so for this one case let's say it's also equal to four so for this case you know we basically keep uh pushing into this uh answer we have one two three and a four right now the next one is five but we cannot push it into the file into the answer anymore because the uh the limit is k so we only push into the answer when the length of the answer is smaller than k yep and right but let's say we have like the uh the next one let's see the last one instead of six is two right so then our algorithm will be like this so we have one two three four and then the five is greater and uh so we will not uh try to pop this one and uh and since the uh the length of the answer or has already reached four and then we basically will skip this five now the last one is two right so the last one is two and two is smaller than four and that's why you know and the two is enough to pop only one number out that's why we're gonna replace this which is 2 here and our final answer is going to be 1 2 3 2 and we cannot keep popping because we don't have any numbers left that's why we can only pop one number out and yeah so basically this is like a greedy uh plaster even called increasing q uh algorithm and yeah i think let's start coding so the code is pretty short you know the uh we have a length of numbers right so for i dot num in enumerate and nums so while the answer is not empty and the card number is smaller than the then the top one in the answer and then we'll try to pop and but before doing the pop we have to check if the n minus i is greater than the k minus length of answer so here n minus i gives us the remaining numbers including the current number right that's going to be the total numbers if the remaining number including the current number is greater than the remaining uh then the remaining slot in the uh in the final answer right comparing to make the uh to make a length k uh subsequence then we can pop the answer the first one right else we simply break okay and then we just need to do a append right the numbers but like i said you know before doing the pen we also need to check we only append if the length uh of the answer is smaller than k then we do the append so and in the end we simply return the answer yeah i think that's it okay if i run the code accept it yeah so for the time complies complexity right the uh so we have a for loop here and then there's a while loop here but you know since we're only be pushing uh and pop the each num each number at most two times that's why the uh so this while loop will not count add another layer uh dimension of time complexity so the uh actually the total time complex is the o of n right then the space is also often space and time yep yeah i think that's it right i mean i think for this one for this problem it's not that hard right that you know we can just we can start with the uh with the gener generic case which is like the example two here right then we just uh we just basically uh process num numbers one by one and every time when we can we find uh the card number is smaller than the previous one then we'll just try to replace that uh give uh also we need to check the condition if there are like enough numbers left uh if we basically if we can afford to pop the card number if we can then we would will of course pop the number because we're looking for the smaller smallest number otherwise we break and here is the uh do the append uh cool i think that's everything i want to talk about for this problem and i'll stop here thank you for watching this video guys stay tuned and see you guys soon bye | Find the Most Competitive Subsequence | find-the-most-competitive-subsequence | Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`.
**Example 1:**
**Input:** nums = \[3,5,2,6\], k = 2
**Output:** \[2,6\]
**Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive.
**Example 2:**
**Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4
**Output:** \[2,3,3,4\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `1 <= k <= nums.length` | null | null | Medium | null |
41 | Hello hi and welcome to line repeat status problem is first in singh positive like date 30th september light co challenge electronics available proven problem status given unsupported all points polished missing positive in teacher 's request scientific example 120 jaunpur 's request scientific example 120 jaunpur 's request scientific example 120 jaunpur dot sector-23 dahez - 10 - 5 September Give dot sector-23 dahez - 10 - 5 September Give dot sector-23 dahez - 10 - 5 September Give One 2nd Year After Tours Number 10 Minutes You Can See The Question Person In Time And Subscribe To That Semester's Exam Problem So Let's Say I Are The Volume To MP3 That Your Judge Hare Which Is In Ascending Order Dr's Right Earth And Surface Than At The Length Of The Race Is 3 So In This Case What Should Be Seen Flight In The Morning - Missing Number Hair Will Be Flight In The Morning - Missing Number Hair Will Be Flight In The Morning - Missing Number Hair Will Be Science Model Positive Number Is Descent 20 Days To The Greatest Treasure Of The Series Loss Of The 16.0 Leo Number Dial Hair B 480 That will be 16.0 Leo Number Dial Hair B 480 That will be two words in both cases the right of way are having all elements which is the length of the Stree leather and having all elements from one to three layer pendant ise subscribe number which is the best inko 2008 mein singh number will always listen And Light Show The Second Cases Were Missing Number Is Present And Sudhir Vighna Na Dhan Tiffin Don't Take Into Consideration Obligation 210 In We Fight For The Normal Approach To Life In The Good Road Values In Her Approach To Life In The Good Road Values In Her Approach To Life In The Good Road Values In Her In This Can Go From One Plus One Can Be Quite Difficult To All Boys And Solve One Can Check The Number Three That Hit And Want It Is Not Interested If It Is Set And 15 Number 19 York 120 Not Know What Time Does Vacancy Cloud Computing Smallest Number S2 OK And K Member Election Approach Which They Can Do It Turn Off And Time That Your Pure Time Will Be Open Butter Space Will Observe Your Pan Vikas Wilson And Others Set Them So Let's See How They Can Not Live Without You Subscribe Will Go Back To The Condition And This Dry district condition will see you can play list number 138 subscribe And subscribe The Amazing The condition of that they are 91 one plus one to value and 1 MB plu generate so in this case for this to condition right Vinod the range of the number at In The Amazing And Vitamin One Does One Right That's All The Numbers Of Presenting A Vitamin B12 And What We Can Do Yes We Can Go Through Their Lineage And Died And Discover The Numbers Chapter Note Between The Avengers Mukesh How Can They Discuss Some Water And They Can Update The Amazing Voting Is Particular Inch Plus 2 And The Number Subscribe Button Number Two Guys Check Subscribe The Amazing 12512 Doing Everything You Want To Draw A Heritage Center In Joe Point Measure 900 Politics Update 1010 Adult Hidden Checking His One Five Plus to Native place but you can oo the saddest pocket watch the finance not in french that and kill today's super marking also updated with a seven eight nine ten second step on second step daughter numbers in one two and great numbers of president of the number At this can be in unauthorized sexual fennel how can we market in vaidya vinod ka number 154 option is that vinod arya indexes desperate 0234 the light for this elements present and aviation number recharge not great dan android are butter present in the story the number chapter In rich right since 2003 rah jatni jaat numbers of present from one to m ok so e can very well person whose numbers are intact value mukesh dhund from this lineage president according to dhok respond index oy give the first element correspondingly and activities in short and order and favorite One to and inspire should be expected numbers was desperate 1234 52806 bean present in the day shyam bin present in the day celebrate from this z1000 data hydride number which is the current tax its data points number ok so one [ __ ] seven from present its data points number ok so one [ __ ] seven from present its data points number ok so one [ __ ] seven from present acid ok pandava dynasty simran Relentless Husband Should Be Too Right So Smart Flow Rate 154 Sham Todd The Number Seven Is Great And So They Can't Make Any Sense Organs In Reach With Only Marg Friend Number Suman Sharma And Index No Way Can Simply Gotra One More Time Together In Third Step And C For Which Index Of Not Anything In Return More Return Of The Day Keeps Writing With Human Rights And 1000 Of Plus 7000 Number Positive Number Minimum Maa Vaishnavi Find Number Of The Match That They Can Go To The Corresponding Index Value And Update The Value Of Birth is negative update number abe improvement par inner third step vacancy please check the number is not negative involved tour of wick and gaunt check weather number smart demise number is not negative i plus one would be induced in threads part plus sexual gurudev particular 202 First and have one a balloon some will go to the key value - one in tax rates one - 110 value - one in tax rates one - 110 value - one in tax rates one - 110 003 from others tongue under the land second * - 003 from others tongue under the land second * - 003 from others tongue under the land second * - 52 days it was the conductor second wali louis 300 will go to three minus one witch from contacts 0213 Taxes - 7 0213 Taxes - 7 0213 Taxes - 7 Member Raman Puri And Thes Will Be - Of 7 Has Been Done On Member Raman Puri And Thes Will Be - Of 7 Has Been Done On 19 Current Mother Is Here Right O My Dear Friend Officially Updated This Particular They Will Come In His Name Increment To The Nine Ten Business Sit - 700 Sharing A To The Nine Ten Business Sit - 700 Sharing A To The Nine Ten Business Sit - 700 Sharing A This Person Check With Us Loop The Video then subscribe to subscribe And Don't Know The Third Step What Do You Mean By Check The First Number Subscribe Who Is The First Number That Is Not Loose 20 Okay So Share Travel Tours Minus Point Jis Ang 053 More What Is The Return More Share and Subscribe Number Subscribe What is the weather in just 120 days and 10 numbers need to be updated with account number which is not in the solar way can identify friend numbers letter on owner if 8 inch plus 2 And Was Amazed And Updated All The Numbers With Sant Shobhan Shyam Best All The Numbers 2018 Rich In The Mark Dost Numbers Better In Rich Look And They Need To My 10 Number Sisodia 80 Number Four Inch One To And So They Can Indicate Dashrath Pond In Taxes for the number 90 number one more and can indicate the number two 202 to indicate that what should be traveled through The Amazing We met the value of - through The Amazing We met the value of - through The Amazing We met the value of - 500 to hair viman deposit with minor midmenor again atimanas 12345 width and the great mother and son beaten To death in Delhi and the consideration and subscribe 1000 What is the name of the first president of the final were busy rate at which can be 1234 park and like then 80 and editor-in-chief and 312 then 80 and editor-in-chief and 312 then 80 and editor-in-chief and 312 a fact even in this Case And Share The First Step Want Find Any Number This Outside And They Want Update Anything In This Are In The Second Step Again Soon For I Will Go To The For Boys And Activities 3DX Friends Welcome To Make The Test Negative And 3023 Minus One Witch Se Conductor Balance Lineage Helmet Data Is Active For 1021 - 100 Data Is Active For 1021 - 100 Data Is Active For 1021 - 100 Index And Definition Of To Go To Management Whistle Issue 12345 Algo 514 Which Is The Same Taxis Almeida 12192 Swift The Amazing All The Number One Range One To The Second Step All The Number OK And Third Step Number Is Positive And Jai Hind Fauz Ke Sainiks Written And Plus Descendent Value Swift And Spice Subdescendent Will Be The Smallest Missing Number So Now So Let's Logic Pure First Thing He Did Was Filled With Numbers But Not In This World To Invest And Suna N S Not Length Sun Condition S Name Take Back And 30 More Norms Of A Great Vision And Latin Bodhak S It's Not In Reality Show In That Case File Update The Number To Interest Two 's Member Account Number Do You Think It That Shobhan Share And First the number chapter note in rich and strong step will be team of the numbers s negative lighter water hot number and indore range department friend number 10 negative for the previous index wali tight slap to spoil you share so let's amazon 123 - 118 you share so let's amazon 123 - 118 you share so let's amazon 123 - 118 Radheshyam Updating The Number Nine Rich With Plus Two 7 Operating This - 178 Can Happen Plus Two 7 Operating This - 178 Can Happen Plus Two 7 Operating This - 178 Can Happen Chapter 10 Verse Making The Sign Of The Particular - Of The Super 57 - 700 That I Will Be Particular - Of The Super 57 - 700 That I Will Be Particular - Of The Super 57 - 700 That I Will Be Inaugurated And Lad A B That Obscene Input Se That Equal To O My God Apes Loot Off's Name All I And Love You To Check Weather's Is Great With And Without Kiss War Continuation Survey Bhavantu Processes 100g Is The Value Activities And Water Value - 1.8 Particular Index Change Value - 1.8 Particular Index Change Value - 1.8 Particular Index Change Sunlight Shouldering Us All's Minus One * * * Name of everyone - 4a Name of everyone - 4a Name of everyone - 4a that if login here provide before embarking interest negative I need to make share the number of - Punish should not quit can happen share the number of - Punish should not quit can happen share the number of - Punish should not quit can happen the number and 10 minutes development BSP updated to negative right Soviet mixture of the number of - Mana of the number of - Mana of the number of - Mana Ki Is A Greater Than Zero Only In That Case How To Make It's Negative Medicine Only In Login Sites Like Zalm Positive Zero Only In That Business Smart Engine We Is Negative After Due To Find What Is The First President Of The Number Date Is Great Dowry Page Number Is A Great 20 Dhundha Das Particular Number Nine The Giver And The Vacancy Of The Debit Market Vya Ko Vash Mein Singh Soun Cents And Explain The Crush Paani Number Will Be Index Fun With Numbers Associated With One Place And Produce Love You Not Able To Return Indiscriminately State Can Be Careful Are The Amazing spider-man Ka Rate Mein Bhi 12345 Amazing spider-man Ka Rate Mein Bhi 12345 Amazing spider-man Ka Rate Mein Bhi 12345 All The Members Of Present In The Way Are Glad And Also Return To You And For Doctors Most Machine Positive Number Do A Saiyan Well Written In Paswan Dr Ko Select Shabhar Code 500 Test Case Payment Record And Not Accepted On 209 During Time Office Algorithm Will Be Easy Arvind Three For Aloo Sau Aath Jo Favorite Subject Dream Pure Time Complexity Of And Were Not Giving Any Additional Features 10 Complexities And Appeal In Fun This Video Is Us In Comment Piece To write to comment section and you like the video and subscribe show | First Missing Positive | first-missing-positive | Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1` | Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n) | Array,Hash Table | Hard | 268,287,448,770 |
1,877 | hello guys so my name is vessing and today 17 November 2023 and uh today we are going to uh discuss about today's lead code problem that is 1879 problem number 1879 and uh the problem statement is minimize the maximum some pair okay so we have to minimize what we have to minimize the maximum some pair okay so we have to understand all this stuff what is maximum Su pair all this thing okay so first we are just going to see what is the problem statement what does problem says to us okay so first the pair some here he says that pair some like if you have a given array and in given array you have uh 2 4 7 8 and here is N9 then you have to make a pair and pair needs two element so in this case what may be your pair 2 comma 9 maybe your pair and question is asking about the pair sum so in this case what is the pair sum so pair sum would be like 99 + 2 sum so pair sum would be like 99 + 2 sum so pair sum would be like 99 + 2 that is 11 okay so it is equals to A plus b and you have to find the maximum pair sum to the largest pair some of the least of pair because in Array you have n number of element then if you make a pair of Two element each then you get how many number of pair that is n by two okay so here uh they are also taught us what is pair and what is pair sum by given example so here we see the example for example if we have a pair like 1A 5 2 comma 3 and 4A 4 then the maximum because we have to return the maximum pair sum so what is the sum firstly so 1 + 5 that is 6 2 + 3 the sum firstly so 1 + 5 that is 6 2 + 3 the sum firstly so 1 + 5 that is 6 2 + 3 again that is 5 and 4 + 4 that is 8 so again that is 5 and 4 + 4 that is 8 so again that is 5 and 4 + 4 that is 8 so what is the maximum pair sum that is it so in this K it would be our answers so given an AR nums okay you have an AR nums of even length because you need to make a pair of Two element each okay you need to make a pair of Two element each with this and this with this so it's not a valid example you have to add five here then it become valid example so if you have an element in an array and you make a pair you need to make a pair of Two element each then how many pair you get that is n by2 okay so here that give some uh some things that you have to uh take care of like each element of nums is in exactly one pair they said that each element of your nums array in exactly one pair okay and you have to return the maximum pair sum and it should be minimized okay so let's see some example that would help us to uh understand what the problem statement that okay so here is an our input in which and uh what is my logic to solve this problem is that firstly I'm just sort the given array that is 2 comma 3 comma then 3 comma 5 after sorting as we see that in this given array there are even number of here and after sorting I'm just making a pair of first element and last element first and last then second element to the second last element so our pair uh pair would be like 2 comma 5 and 3A 3 so if you find the pair sum so what would be the pair sum that is 7A 6 so what will the maximum so maximum will be seven that is our output okay so let's see another uh example uh here we have to understand the question more and more so that I uh I'm discussing about the another example in which yeah I apply the same logic first I sort the given array after sorting I would get 2 comma 3 comma 4 comma 5 comma 6 and then I'm just making a pair of first element to the last element then second element to the second last element then third element to the third last element okay so our pair are like 2 comma 6 3 comma 5 and then 4 comma 4 then if want to find PA sum then we get88 and8 in this case all pair some are eight so what is our maximum is also eight so 8 is our answer okay so let's go on the lead code uh lead code platform and solve the problem okay so here is our lead code platform and here I'm going to solve the problem and try to submit the problem and see it is accepted or not so first uh what we do yeah as we discussed first we just sort the array sort nums do begin to nums do end yeah just sort there now I am Traverse I want two iterator one iterator at the beginning okay like nums 2 3 4 5 so one at the beginning I put ials to here and yeah that is start equals to here and last here and then I SU okay so sum equals to nums of S Plus nums of L yeah that we want so that we are doing here same stuff that we are doing here okay so I make int start and put at the initial the first element of your area and then another would be L that is at last how to get last that is nums do size minus one yeah it would a last element and then I apply the Y Loop because I want to go iterate over and over till when s is less equals to L so I inside I just make a variable temporary variable in which I just put the sum of nums of S Plus nums of L after this I just increase the S by one and decrease the L by one okay so after putting some I want to put something like that to we get the maximum so for that we need priority Q yeah for that we need priority Q enter okay so when we get some we just put inside the priority CU so PQ do push what we push that is temp yeah simple and last I just written what PQ do top okay so just see this is the whole and let's see our test case would be accepted or not yeah given test case are correct so I'm just trying to submit the problem and see what happened it yeah it would be submitted or accepted or not so as we see that the problem is accepted so thank you for today yeah it's good to see you guys okay thank you so much | 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 |
871 | That the students were only good singers Traditional minimum number of Muslims Top 10 we destination and starts from President gives pain on the number of top tourist destination that also it is giving details not possible to reach the destination in the here facility to open diners Definition of Smart U Letter Creative 10 Minimum Number of Winning Stops Directly to India So Let's Our Pictorial Representation of Question in the Question you liked The Video then subscribe to subscribe and subscribe the Channel Please subscribe and subscribe That The Most Of The Gas Are Let's Considered Test Case For High Court Where In Must Subscribe To Our Channel Subscribe To Plain Mode Of Urine Priority Q Revolution Priority Q And Never Regret Elements From Priority Q David Fuel Available On So Let's Get Started Instant Wear Give The Fuel Other Soft Cotton Words From The Reach Of This Conic Subscribe To I Want In This Way How Many Digestive 1251 Will Develop This Into Fuel To Subscribe To Meaning Now You've Accepted Only A Few Words With Dad Or Station What We Do Will Tubelight And Consume Fuel From The Best Suv Maximum Video Subscribe Now Subscribe To You All This Position Of Candidates Will Go Up Till 5th Have Health And Avoid Thriller Subscribe Share That 108 E Want How Many Destinations Ribbon Counter And 10 Way Willard Into R Priority Q Hello Viewers ID Enter Priority Q& Hello Viewers ID Enter Priority Q& Hello Viewers ID Enter Priority Q& A Few Leaves Three Positions That Nav Again Is As Option Condition All The Furious Don't Increase This Maximum Capacity And What Do You Want To Consume Subscribe Maximum Subscribe Now To Receive New Updates That 11-03 -2011 And Give You Rapid Reply That 11-03 -2011 And Give You Rapid Reply That 11-03 -2011 And Give You Rapid Reply E Saw What Do You Do Per Gas Stations Between Subscribe And Subscribe If You Burn Leader Of Units Of Blood And How Then You Can Give One Mode Switch On This Website Now 112 You Have Encountered Anu Gas Station Should Withdraw Tour 6 Video Subscribe Button Ko Hai Andhra Disposition Even After 65 Years In This Module You Television Producers Remove Subscribe Dash Lutb School Me To Subscribe To Me Let Bar Question And Vitamin President Shravan Subscribe What We Do Subscribe To Ek Anda WhatsApp Dhulkot April 6th House for Commuters from Chronic subscribe and subscribe to subscribe our Channel subscribe's Record Investment in Another One You have Effective and Recording Artist 30c 's Report and Nurse Capacity and 's Report and Nurse Capacity and 's Report and Nurse Capacity and Deprivation S6 and second Aviation Secretary and Tuesday's Subscribe that Itarsi Maximum Capacity If it is, then it is goal and how many kilometers to remove hair from this pollution, swimming per liter of petrol, I added you do the a fresh point to media from ZuluTrade Subscribe I Just Remember Man Singh's Preaching of Twist Point Se 0.5 Withdrawal Subscribe Twist Point Se 0.5 Withdrawal Subscribe Twist Point Se 0.5 Withdrawal Subscribe My Channel Subscribe The 200 Without Much 2008 Important Part Court Mode Clash Of Your Subscribe Number Shop Near Me Means 16 201 Style Define A Priority Q How To Print Result A Part Collar Tune New Priority Tube EWant Which Hair I Will Define In Form Of Maths e request you want to return station with maximum fuel like share and subscribe to that started hydration of grains will cover all the stations at the ajay ko ki these days what are yours and let's calculate the meaning of next and upcoming station next a place in The continent and will be given by station.video and don't you all the station.video and don't you all the station.video and don't you all the best fuel smart station monitor the world with wasted all or fuel which value elements from priority queue and what is the cost in condition is which it means subscribe to I ignore spread All Your Food And Water Can Do Luta Why Luta Do It AFuel That I Will Not Be Marked Volume * That I Will Not Be Marked Volume * That I Will Not Be Marked Volume * Deposit Is Next Current Equal 2X Current Plus Next You All Subscribe My Channel Subscribe - Na Main Ashok Don't Get To Increase The Volume Number Of Media Report Consuming Problems from subscribe The Video then subscribe to the Page if you liked The Video The Latent In The Process Savism Vira Prank One Of The Governor Cases Where You Have Not Reached Your Destination Elementary Mid E Want With A Condition Hai Coordinate Is Lansdowne Target fluid can this day what we do the green signal ka in the volume maximum element culprit who subscribe it to e will simply don a minus one from the door that hindi and you celebrate on number of top minute azhar answer remembered as a very important Switch off the flashlight and marks fuel symbol shank defined a ki line number airtel number 36 ki ho typo a specific loot badna a hain lemon juice a whatsapp text what food to time complexity of this approach time complexity wait bhi mode off and login and Space Complexity of Butter of and Gautam Actor will help to all the stations of interpreting I hope with you like share and subscribe our channel thanks for watching video Ajay Ko | Minimum Number of Refueling Stops | keys-and-rooms | A car travels from a starting position to a destination which is `target` miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas.
The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`.
Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived.
**Example 1:**
**Input:** target = 1, startFuel = 1, stations = \[\]
**Output:** 0
**Explanation:** We can reach the target without refueling.
**Example 2:**
**Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\]
**Output:** -1
**Explanation:** We can not reach the target (or even the first gas station).
**Example 3:**
**Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\]
**Output:** 2
**Explanation:** We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
**Constraints:**
* `1 <= target, startFuel <= 109`
* `0 <= stations.length <= 500`
* `1 <= positioni < positioni+1 < target`
* `1 <= fueli < 109` | null | Depth-First Search,Breadth-First Search,Graph | Medium | 261 |
890 | hey everybody this is larry this is day 30 of the july leco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom ah no three points okay this is gonna be my 850 day streak so let's get to it find and replace pattern given string words in a pattern return list of words that match pattern you may return ends in any order do we not replace do we just find oh that means something okay a p will match a pattern if there exists a permutation of p such that after replacing every oh okay so basically let's see let's read an example one thing that i've been bad at is reading examples lately so maybe today i'll do that i mean it seems like we'll do it one by one anyway so yeah so we'll see um mge patterns a b so we can convert an a to an m a b to a e and so forth i think this is also the other way as well meaning that we have to make sure that the yi converts to only b um doing the other way and i think with those things basically there's a one-to-one mapping and that it is one-to-one mapping and that it is one-to-one mapping and that it is consistent so okay so let's do let's try doing that so yeah for word in words if good of what maybe this is uh maybe i just got match uh then we do so answer we have an answer away and then answer we append word and then we return answer and of course we need the match function um so we have a word we have a pattern so i guess technically we you know we don't need it because but you know it's fine okay so then okay i was just checking to see we need to check the same length because they are the same length we are okay here and then now we go first um let's say a b and sip of word pattern but of course we should have a lookup table and a reverse lookup table and basically what it's saying is that okay if um how do what is the word i mean we can just do more if statements but i'm trying to maybe optimize a little bit maybe not maybe we shouldn't do that okay let's say if a is in lookup then if lookup of a is not equal to b we return force right okay if b is in reverse lookup then if lookup all look up we must look up if b is not a then we return force otherwise we can just establish lookup of a is equal to b and r look up a p is equal to a is this good enough am i missing a condition these things are always tricky um i feel like this is okay maybe let me think for a second more let me try and what i am doing during these thinking is just trying to come up with a case where that is not true right meaning if uh i'm trying to think rather weather um now for example um all right let's at least run it real quick i don't that's the beauty of computers i must cook twice the beautiful computer says you can make it one for you and not you know especially if you pay but uh okay let's give a submit then and then we'll see if i am fortunate this time and i am so yay that looks good i don't know why it is so slow i mean i don't think i do anything funky because the other thing that you have to do is to reverse look up which i forget sometimes because then now you have like aaa then it matches it multiple things map to it but you know that's not gucci okay so i mean this is good this is going to be um let's see right what is the complexity of match right this computer so complexity of match is just linear in the size of the word so this is going to be say of l right so this is going to be all l and which one is of l then this is just going to be of n in terms of this is going to be linear in terms of the size of the input which is the total number of characters in words in terms of space we do these lookup things and of course it's going to be all alpha is up to 26 i think um and that's just because you know every character will be mapped once eventually um so um or less than it i suppose so yeah um that's all i have for this one let me know what you think hit the like button hit the subscriber and join me on discord let me know what you think about this problem i am going to do a bonus one if you hit the subscribe button so if you'd like to do it with me come to discord and you know post some code ask questions whatever you like i'll see you later and bye | Find and Replace Pattern | lemonade-change | Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**.
A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word.
Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
**Example 1:**
**Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb "
**Output:** \[ "mee ", "aqq "\]
**Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
**Example 2:**
**Input:** words = \[ "a ", "b ", "c "\], pattern = "a "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `1 <= pattern.length <= 20`
* `1 <= words.length <= 50`
* `words[i].length == pattern.length`
* `pattern` and `words[i]` are lowercase English letters. | null | Array,Greedy | Easy | null |
122 | let's see another common problem that is asked in facebook interviews and it's from lead core problem number 122 and it's called best time to buy and sell stock and its version is two because there is one simpler version also version 1. this is version 2 so let's see the problem so you are given the stock prices on different dates so this one cell denotes one date on a particular date what was the uh mean price of the stock and obviously stock prices cannot be negative so these are positive numbers and you have to calculate what is the maximum profit that you could have made this is not a trading strategy you cannot follow in real trade it's just that one day back uh you could have made this much profit but you did not so the idea here is that whenever stock price dips you mark this into a variable called buy so you buy at this price let's say it dips further so you update your buy to hold this value and when it's moving up you don't do anything your buy is still here till the moment it keeps decreasing you have to keep updating the buy and till the time it's increasing you don't do anything you sit idle you could have also sold here then bought again sold again but there is no point in that you wait till it keeps going up and let's say here it dips so what you will do when you reach here you see that today's price is lower than yesterday's so you sell it at this price so and you keep accumulating profit so whatever was the profit till now you had made you add this much to your profit so this denotes one transaction and now your new buy is this one and if it decreases further you will update your buy and when it increases you it idle and now again so let's call it b1 s1 b2 is this and the moment it dips you sell so you again add s2 minus b2 so this is the study and it will work you are allowed to make and as many transactions as you want but there is a scenario which i have not considered here let's say here this was the end of the array or maybe this so you got a chance to sell but there may be situation that this was the end of array that is you bought here but you did not encounter a dip in price so you never got a chance to sell so you are not adding this part to your total profit so we will handle that case separately uh that if we bought and we have reached we have completed the entire loop the complete iteration of this array then we will add uh the last price if it's in array a then we will add n minus 1 minus whatever was the latest by so let's write code for this and again i'm warning you this is not uh like it works in stock market because you never get to sell go back in time and sell it's just to aggravate your grief that i lost i could have made this much profit theoretically but i did not so this is just as a retrospective method although people follow something very close to this they don't sell till the moment it's increasing and they also keep a stop loss which is some small threshold let's say this so if the price is here they will always keep a stop loss of t below the current price so if it dips by more than this t amount it will automatically get sold and when it price increases they increase the stop loss also so it's always lagging by p amount so if it reaches peak then stop loss was here and when it falls then it will be sold at this price so the idea is not to sell at the peak but close to peak so this was just some extra info there are of course many more complex tricks that traders apply for their trading let's quickly write the code for this without going too much deep into day trading or long term trading so if first thing is that if there is just one price then you cannot make a transaction you need to buy at some price sell at some price with one you can make a transaction that you buy at that price and sell at that price but profit will be again zero and why would you do that so you can return safely zero in this case if it's one or less then this is the buy i was telling about here that we initialize this by whenever there is a dip and we keep updating till there is a dip so initially it will be prices zero and profit of course is zero in the beginning so now we will start iterating from one because we have uh we will compare if one is less than zero or not so our loop should start from one i less than prices dot size and plus i then if current price is prices i is less than prices i minus 1 this denotes price drop so whenever price drops uh do we need to update profiter i think we can just update uh okay so we need to add to the so whenever there is a dip we sell so we make a transaction so what we will do we will subtract previous price not the current price minus by so that we need to write here profit plus equal to prices i minus 1 minus whatever was the buy price and we do additional step that is we update the buy to the current price and i think we are done this should work for all the cases but uh as seen here the last case if we bought but we did not encounter a dip in the end then we need to add additional case for this one so we will write profit plus equal to prices dot size -1 prices dot size -1 prices dot size -1 this is the last index minus y and we don't need to keep any check here we can always put it here because let's say if it was the peak in the end then it will automatically add this profit which was not added but let's say if it was this one and the buy was this here again we encountered a dip so we would have again updated by so by was pointing to the last price that is a of n minus 1 and we are doing profit plus equal to price of a n minus 1 minus y but this by is nothing but a n minus one so it will be zero so adding zero will nothing will not change anything in the profit so we don't need any condition here and then we need to return the profit and let's try to run our code it passes for our base case let's submit if we are confident i think this is a simple problem we can be confident and uh it's quite good close to 100 and in space also it's close to 100 so that's it | 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,845 | hello everyone welcome to my programming club today we will be solving another daily lead code problem and the problem's name is seat reservation manager so you have to design a system that manages the reservation state of N seats numbered from 1 to nement the following seat manager class seat manager uh constru will initialize a seat manager object which will manage and seats numbered from one to end okay all the sheets are initially available in uh the reserve function what you have to do is you have to find the smallest number unreserved seat and reserve it and its number okay then what you have to do is uh you have to uh complete another function uh with or method uh unreserve which will unreserve the seat uh with a given seat number and it will be available for uh reservation for other customers okay so let's have a look at the uh constraints so the constants uh are the seat number will be ranging from 1 to 10 to^ 1 to 10 to^ 1 to 10 to^ 5 and for each call to reserve it is guaranteed that it will there will be at least one reserved unreserved seat so there will be at least one seat remaining when the reserve call will be made and for each call of unreserved there is it is guaranteed that the seat number will be reserved okay so at most 10 to^ 5 fals in total will so at most 10 to^ 5 fals in total will so at most 10 to^ 5 fals in total will be made to reserve and unreserve both together so let's see how we will be solving this problem basically uh the whole logic or say the implementation boils down to one basic problem here that somehow you have to maintain the order of the unreserved seats okay so if let's say there is a there is one register available for undeserved seats and in this register the seat number with the smallest value is always at the top and it's like a tree like structure okay so whenever you will uh query for the root of the Tre then it will be the smallest seat possible it number possible okay and once you let's say remove this root uh the structure is like that it will reassemble itself and again the top will be the smallest sheit number possible if root removed then also then smallest seat number will be available at will be available as root again this is a kind of Heap data structure those of you who are not familiar with what a heap data structure is I will be providing link uh for it link of article will be provided here and we will be using inbuilt he which is min Heap here to S suit our purpose to get the minimum de number always minimum unreserved seat always okay so many implementation in which language we are implementing Java I think okay so in Java it's priority Q okay so priority Q by default in Java is in increasing order or it will be a minan he okay so without further delay uh let's implement the two methods so initially you will be declaring a private uh let's say RQ and let's call it register or say seat register and initially it will be initialized to null then once you call the Constructor you will initialize your seat register to a new priority queue and then what you will do is uh you will uh enter the number of seats seat numbers uh that are initial unreserved that all are initially un reserved so we will be starting from the very first seat to the N seat and we will be incrementing then in priority we will push register offer seat okay I think in jav it sare and then in reserve uh you will get the minimum seat which is reserved so you will remove the top of the priority q and remove the topmost element of minan Hep now which is the resistor okay and return it so return register P okay and when you will un reserve the seat number you will again enter it into your seat register do offer sheat number okay let's try to submit for the sample test cases actually I have to verify whether these two function method names are correct or not ja let me verify yeah it's uh full and I think instead of offer it head anyhow let's have look at the no offer is also there okay and yeah I think it should work let's see I'm submitting for the sample test cases as you can see it's getting accepted so let's submit for the final evaluation yeah it's getting accepted for the final test all the test cases also and that's how we will be solving the problem and if you are having any kind of doubts or queries please feel free to ask the ask them in the comment section I will be more than happy to answer thank you for watching have a nice day | Seat Reservation Manager | largest-submatrix-with-rearrangements | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. | Array,Greedy,Sorting,Matrix | Medium | 695 |
708 | and welcome back to the cracking Fang YouTube channel today we're going to be solving lead code problem 708 insert into circular linked list before we get into the question you guys know the drill please subscribe to the channel it really helps me grow alright given a circular linked list node which is sorted in non-decreasing order write a sorted in non-decreasing order write a sorted in non-decreasing order write a function to insert a value insert Val into the list such that it remains in a sorted circular list the given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list if there are multiple suitable places for insertion you may choose any place to insert the new value after the insertion the certain the circular asserted the circular list should remain sorted if the list is empty I.E the sorted if the list is empty I.E the sorted if the list is empty I.E the given node is null you should create a new singular circular list geez try saying that five times and return the reference to that single node otherwise you should return the originally given node all right let's look at a very basic example we're given this node which is you know one three and four and we're told that the head uh the node that we're given is this 4 here and we want to insert uh the value two so obviously in order to maintain the you know sorted order the circular insertion should happen here and that way it's going to remain sorted so now we'd have something like one to two to three two four and we maintain our you know sorted circular array here so and you know this is still the head so relatively simple I mean if we're looking at a kind of diagram it's very easy to figure out where to put this but there are a few edge cases that we need to consider so in order to do that I'm actually going to wipe away a lot of this text to give us some more space to work with and we'll talk about all the possible insertions and how we can navigate them and then we will go to the code editor and write the code this question is not that complicated all right let's think about all the possible ways that we can insert this node so we read the question prompt and I told you that there's a few cases that we need to consider and let's kind of enumerate them now the first case and is going to be the most simple case where the head that we're given uh is null right so in the case that head is null all we have to do is just create a new node uh you know we'll just create a new node and then return that right that's our answer right we just have to create it and then link it to itself right so we kind of have like a cycle here in the node itself that's the most simple case easy peasy right the second case is that we insert somewhere inside of it right insert into the linked list so you know this if we go back to our example where we had one um and then I think it was like three and then four right we had the linked list like this and we were asked to insert two right so we would insert it basically between one and two so we basically find the point where it would go into and you know this is basically just going to be a point where you know we have a gap here that we can insert it into so that's you know the second case where we basically found a point where the previous value in the linked list is less than the insertion value uh and it's also less than the next value in the linked list right so in this case uh you know if we were at three or I guess it would be the current value sorry because there is the next one so you know if we're at the node three and then we'd say okay what was the previous value it was one and two can slot in there so we can insert it and there we go that's fine so that's the second one and then the third case is going to be one of the more complicated cases uh and kind of let's redraw our um you know diagram here and we have these three nodes and it's linked like this right and in the more complicated case the insertion is going to happen at the end right so if we're asked to insert the nine then we would have to insert it you know between the one and the four so we need to account for that because if we're just looking for a case like this we're gonna miss it right this is the easy insertion but what happens when it happens at the edge right or if we want to insert zero into here right it would still happen between the four and the one but we can't look for this check here so we need to check whether or not we're actually at the end and remember since the list is given to us sorted we know we're at the end because our current value compared to the next value will always be greater right that's the point where our linked list drops off and becomes circular right it so the one is basically the smallest element and the four is the greatest element when we see that drop off so basically the curve value is greater than the next value in the linked list then we know that we've actually hit the end and now we've wrapped around to the smallest value and our current value is actually the largest one so in the case where we wanted to insert the nine we would have to say Okay four points to the nine and then all the nine points to the one or in the opposite case the same way we could point to the zero which now points to the one and then you know continuing onwards uh for both cases so those are your three cases so this is Edge insertion uh Edge insertion so those are the three cases that we want to take care of right the first is that the head is actually um no the second one is just like a standard insertion into the linked list this is really easy we just look for a point where the previous value is less than the insertion value Which is less than whatever our current node's value is that one's also quite easy the third case is going to be the edge insertion um and you know that's one's a little bit more complicated because we have to identify where the edge actually is uh that we start wrapping around and actually I just realized there's a fourth case where the entire uh circular linked list is actually the same value so if you want to do like three uh three then we have to be a little bit careful here and figure out where to actually insert the value in this case um it shouldn't really matter uh if the entire thing is actually the same um then we can insert it wherever we want and we will maintain our sorted order so this is going to be a uni value uh linked list right where all the elements are the same it doesn't matter so if we're asked to insert two we could insert it here and that would be fine we could insert it here that could be fine it doesn't matter wherever we insert it we will maintain our sorted order so we don't have to worry about if it's uni value we can just put that element wherever we want okay so those are our four cases and this is really what this question is um kind of boiling down to can you identify these four cases and handle them in your code otherwise it's actually really straightforward once you figure out these four cases and how to handle them so what we're going to do now is we're going to go to the code editor and type this up it's only about I don't know 25 lines of code not too complex the logic is pretty easy to follow so I will see you back in the code editor and we will type this up together alright let's go we're in the code editor let's write this up remember that the first case that we need to take care of is that this head given to us is actually null if it's null then we need to create the node and actually link it to itself so let's do that so we're going to say if not head we're going to say the new head is going to equal to node of whatever the insert value is and now we need to link that head to itself because remember the linked list needs to be circular so we're going to say new head dot next equals to new head so we've made it circular and at this point we are done we can simply return the new head all right cool now what we want to do is actually go through our linked list so typically when we go through our linked list we have some sort of Sentinel value and in this case we need that because we actually need to figure out when we've made one for rotation right if we do a while loop and go to the end of our linked list well it's circular so we're just going to be iterating forever we need to actually figure out when we've done one full rotation so to do that we're actually going to create a copy of our head and just point it equal to Cur and we'll use Cur to actually iterate through our linked list here and when the value of Cur actually equals to head then we know that we have actually done our full rotation and we can stop there otherwise we're just going to go in circles for all eternity so we're going to say while Cur dot next does not equal to head so while we haven't completed our full iteration through the linked list we need to do some work here so the first case we want to take care of is the actual insertion right and this is the standard insertion so say we have the values like one and three and we were asked to insert two uh we would basically need to check for this simple case so what we're going to do is we're going to say if card.val is less than or going to say if card.val is less than or going to say if card.val is less than or equal to insert Val Which is less than or equal to Cur dot next dot val then we can actually insert the value between Cur and cur.next so we need to create Cur and cur.next so we need to create Cur and cur.next so we need to create the new node that we're going to insert and we're going to say it's going to be a node with value insert Val and its next value is going to be whatever the next node is Cur dot next and now we need to actually uh update the current node uh it's next right because its next value is pointing to whatever occur.next is but we need it to whatever occur.next is but we need it to whatever occur.next is but we need it to be pointing to this new node now that we've created it and we're going to be inserting it there so we're going to say Cur dot next equals to new node and at this point we've completed our insertion so we can simply return the head which is remember what they're actually looking for all right now we have the other case where we need to handle what happens at the edge of our um linked list and whether or not we need to insert something there so remember that we know that we're at the edge if the current value of our node is actually greater than cur.next.val right actually greater than cur.next.val right actually greater than cur.next.val right because it's circular therefore when we hit the end of it the next node is going to be the smallest node and since it's in sorted order if we ever get to a point where a current node's value is greater than the next node that means that we've hit that cliff and we've gone over it so we have basically gone back to the beginning so we do that by checking whether or not the current value is greater than the next value and if it is then we need to check whether or not we need to insert at the end so we're going to say if insert Val is actually greater than or equal to cur.vel cur.vel cur.vel which implies that we want to insert it at the very end for the case that our insert value is actually greater than the last element or the greatest one that we have or the case where insert Val is actually less than the smallest element that's currently present in our linked list so we're going to say Cur cur.next.val so in either of these cases cur.next.val so in either of these cases cur.next.val so in either of these cases we want to insert our new node at the end and doing this is going to be the same process as we just did above we're going to say new node equals to node and it's going to have a value of insert Val and its next value is going to be whatever occur.next is and again we need whatever occur.next is and again we need whatever occur.next is and again we need to set Cur dot next now to be new node and at this point we just want to return the head cool so if neither of these statements fires here whoops I think this actually needs to be indented yeah there we go okay cool um if neither of these uh triggers then well even if they trigger uh actually no we would return ahead here so if neither of them trigger we need to move on to the next element in our linked list so we're going to say Cur equals to cur.next and we're going to move our cur.next and we're going to move our cur.next and we're going to move our iteration forward all right so either we're going to return in here or we're not and what it means if we haven't returned anything in the actual uh process of our while loop is case number four in which case all of the values in our um linked lists are actually the same in this case we can literally insert that new node anywhere and we'll maintain our sorted order because the entire thing is uni value right so it doesn't matter if we have all threes and we're asked to insert a two we can put it here we can put it you know here we can put it here it doesn't matter um because that will basically be the new smallest element and it's going to be fine so if it's all the same value we can insert that note anywhere which is what we're going to do now uh okay so let's make sure I'm indented correctly here and we're gonna again say new node is going to be node of insert Val and then we're going to set the next one as occurred on next and remember that Cur dot next now equals to new node and then all we have to do is just return our head here so let us um run this make sure I didn't make any syntax errors that was an issue with the indenting so there might be a chance for us okay it looks fine let me submit this and we are good to go so what is the time and space complexity of this algorithm so the time complexity in the worst case we have to go through the entire uh linked list here right because in the worst case it's going to have all the same Elements which means that we're going to have to make one full loop through the entirety of the linked list so because of this it's going to be Big O of n where n is the size of the linked list right for space complexity wise we don't actually use any space here all we're doing is inserting a new node and we're not actually you know using any sort of data structures so it's going to be a big O of one space allocation here so that is how you solve this question insert into a sorted linked list this question is really not that complicated like I said what the interviewers are really looking for here is whether or not you can identify and explain those four cases and remember the four cases are one that the head is null what do you do in that case the second case is that you have one of these easy insertions where you just insert it between two values the next two cases are how you deal with insertions at the edge So based when the list loops around again because it's circular and the last case is how you deal with the fact that the um linked list actually has uni value so it's all the same values and that one is probably the most tricky one to catch but luckily now that you've watched this video you know all four cases anyway I'm gonna stop rambling here because you've seen that the solution Works we've talked about the time and space complexity there's nothing more for me to say other than if you enjoyed the video please leave a like and a comment it really helps move the YouTube algorithm if you want to see more content like this please subscribe to the channel and hit the notification Bell so you don't miss uploads and otherwise thank you so much for taking the time to watch this video have a great rest of your day goodbye | Insert into a Sorted Circular Linked List | insert-into-a-sorted-circular-linked-list | Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value `insertVal` into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list.
If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.
If the list is empty (i.e., the given node is `null`), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node.
**Example 1:**
**Input:** head = \[3,4,1\], insertVal = 2
**Output:** \[3,4,1,2\]
**Explanation:** In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.
**Example 2:**
**Input:** head = \[\], insertVal = 1
**Output:** \[1\]
**Explanation:** The list is empty (given head is `null`). We create a new single circular list and return the reference to that single node.
**Example 3:**
**Input:** head = \[1\], insertVal = 0
**Output:** \[1,0\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-106 <= Node.val, insertVal <= 106` | null | null | Medium | null |
501 | hey everyone welcome back and today we'll be doing another lead code 501 find the mode in binary search tree an easy one given the root of the binary search tree return all the modes the most frequently occurred element in it and that's it just return the most frequently occurred element in it and let's get started so if root if there is no root to begin with we will just return our empty list and if there is no root to the left and not a root to the right we can just return in this case root value because root is the only node at this point present in our you can say the binary search tree making our function which will check the duplicates for us so check the dupes for us and passing it our root like this and also calling it so check groups will be having root okay so I'll be making a map which will be just taking the counts so count will be a dictionary and that's it so let's write our function so if root value is not in our map it means it is a new value so what we will do is just use that value and assign Gate 1 because it was the first time it was seen in our binary search tree and it if it was already there we will just add one at each point every time we see it so if not root left if there is not a root to the left and not a root to the very right then what we'll be doing is just returning at this point and if there is a root to the left we will call the function again and passing it our root to the left and doing the same with the right side if root to the right is present then check tubes we'll be passing it the right side okay we are done with our function let me see yes we are done with our function now we'll be making a result output list and a maximum number you can say a maximum count which will have the maximum of the count values okay like this and for every key and value in our count items we will iterate through it and if a value at certain point becomes equal to the maximum count then we know that it is a maximum value so we will just appended to our uh the key because we will be just returning the key and that's it and just return the result after all of this and let's see if this works and that's it | Find Mode in Binary Search Tree | find-mode-in-binary-search-tree | Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_.
If the tree has more than one mode, return them in **any order**.
Assume a BST is defined as follows:
* The left subtree of a node contains only nodes with keys **less than or equal to** the node's key.
* The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[1,null,2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** root = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count). | null | Tree,Depth-First Search,Binary Search Tree,Binary Tree | Easy | 98 |
120 | hello everyone in this video we are going to see the lead code question number 120 triangle given a triangle array return the minimum pot sum from top to bottom for each step you may move to the adjacent number of the row below more formally if you are on index I on the current row you may move to either index I or index I plus 1 on the next row we are given two examples in this triangle we have to return the minimum path which is 2 plus 3 plus 5 plus 1 which is 11. and there is another example which has only one node minus 10 and we have to return -10 let's see how and we have to return -10 let's see how and we have to return -10 let's see how we can solve this problem when we are in the top of the triangle we can either go to 3 or we can go to 4. out of 3 and 4 3 is the shortest so the sum becomes 2 plus 3 equals file from Phi we can go to either 6 or 5 but the shortest path is 5 now the sum of the path is 5 plus 5 equals 10. from 10 we can either go to 1 or we can go to 8 but the shortest path is going to 1. so 10 plus 1 makes 11. so we are returning the result 11. let's see how we can solve this we can go to the last but oneth list which is this list from each element we can see which is the shortest path from 6 we can go to either 4 or 1 but 1 is the shortest so 6 plus 1 becomes 7. from Phi we can either go to 1 or 2 8 so 1 is the shortest so 5 plus 1 becomes 6. from 7 we can either go to 8 or 2 3 so 7 plus 3 makes 10. now we will go to the previous list which is 3 comma 4 from 3 we can either go to 7 or to the 6 but 6 is the shortest so 3 plus 6 makes 9 from 4 we can go to either 6 or to ten out of this sixth is the shortest so 4 plus 6 makes 10. now we will Traverse to the topmost list which is 2 from 2 we can either go to 9 or to ten out of this 9 is the shortest so 9 plus 2 makes 11. now we got the shortest path that's our top element so we can just return the first element of the list I hope the approach is clear now let's get into the implementation first let's go to the last but one list of the triangle for I in range of length of the triangle minus 2 because python index Dot from 0 minus 1 is the last list minus 2 is the previous list from there we Traverse backwards until we reach the first list now we will iterate through each element of the list for J in range of 0 comma length of the sub list length of triangle of list now from I plus 1 position we will find the smallest number among the adjacent elements and add the smallest element to the ith element let's Implement that triangle of I of J is equal to Min of triangle of I plus 1 element of J comma triangle of I plus 1 element of J Plus 1. now we will just return the first element of the triangle return triangle of 0 let me make a small correction we are finding the minimum element and adding it to the existing elements now let me submit it the solution got accepted I hope you like this approach I'll see you in the next video thank you | Triangle | triangle | Given a `triangle` array, return _the minimum path sum from top to bottom_.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row.
**Example 1:**
**Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\]
**Output:** 11
**Explanation:** The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
**Example 2:**
**Input:** triangle = \[\[-10\]\]
**Output:** -10
**Constraints:**
* `1 <= triangle.length <= 200`
* `triangle[0].length == 1`
* `triangle[i].length == triangle[i - 1].length + 1`
* `-104 <= triangle[i][j] <= 104`
**Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle? | null | Array,Dynamic Programming | Medium | null |
81 | hello everyone welcome to my programming Club today we will be solving another daily need for challenge and the challenge name is search in rotated sorted array for two so this is a follow pronoun for this problem such in rotate subject array let's quickly read the wrong statement out and then see what we have to do there is an integer array nums ported in non-decreasing order non-decreasing order non-decreasing order so it's in ascending order not necessarily with distinctivities before being passed to your function nums is rotated attainment unknown pivot length such that resulting array looks like it is forward stubborn statement is saying is uh let us take the example which is being provided or anyhow let's take our own example in this example we are not considering the duplicates not considering duplicates this part we will deal separately as of now we are not considering duplicates in the array let's say all the values in area unique so if there is something like this now it may have been rotated at a unknown pivot let's say I decide it should be going to derived this viewer then what will the resulting array will be for this part from right hand side of the viewer will be shifted to the front of the array and the resulting array will be 4 comma five one two three so I hope you are able to understand it work by rotation is this is meant here so yeah evenly array nulls after the rotation and an integer Target you have to return whether that Target is present in that note or note for example along with this array you will be given a Target let's say Target is five now you have to tell him when this rotate array will be passed through your function this array will be passed whether this target is present in your array or not Target present or not also you have to make a note that the RDM might be rotated it's not necessarily uh to that the array will always be rotated for example array like this can also be passed to your function without rotation the program statement is saying that it might have been rotated so we will check for the case in which the array is rotated and the case in which the r is not rotated it will be stored in that case itself so yeah that's the problem statement and you must decrease the overall operation steps as much as possible so we have to write a solution which is the most optimal solution most Optical solution possible in that solution the number of operations will be as much as low as possible most optimal solution so before approaching the solution of this problem I would highly recommend you to check the solution of this particular problem this is a problem that was this problem sorted the search in rotated sorted array part 2 is just a follow of this problem oh the only difference is the values here are not unique and in this one the values were unique so I will be providing a link for the video explaining the solution of the previous part in which the values were distinct so before proceeding to the solution it is recommended that you should check that part out and the link will be provided you to win the I button on the top right of the screen so now I hope you have gone through that solution video now there is a just a little tweak that we have to made in that solution so that we will be able to come answer of this particular solution and we are asked follow-up that will be asked promise is follow-up that will be asked promise is follow-up that will be asked promise is if dust duplicates affect any affects the runtime complexity of your program if yes then oh and if no then why and so what we have done is the only thing that we have changed in that program is so instead of asking for the in index at which the target will be present it is asking just for our true false value whether the target is present or not so there will be two changes in the code first change will be log consider this scenario let me quickly erase the word now consider this scenario one two three four five now let's say this is the given input array before rotating it now you will be first sorry after rotating it so let's say I decide to rotate it rotate this at this pivot and the rotated part will be this will be the rotated part and what was the original part yeah it's the original one and this will be the Rotator rally so uh what will happen is with this part from the right hand side will just come in the front here so if let's say you are currently your mid position is currently at this index now you will not be able to decide whether you are in rotated part or known rotated part this is the rotated part this is a non rotated path beside uh by looking at the last index and your mid position whether you are in rotated part or don't rotated part because if let's say this value have been five and this value have been six seven eight nine then you could have easily checked that the value at the middle position is 7 and which is lesser than the which is greater than the right of the current search space right this will be the right pointer and this will be the left pointer pointing to the start of the search basic so the last element of the array is smaller than the middle position element of the array so we are in the rotated part then you would have easily guessed that in which part we are in but here that's not the case you cannot check whether you are in the rotated part or not so how you will be doing the checking part the only thing that you can do here is here two conditions are being satisfied first is your nums of left this is the right it is equal to your middle position element and your nums of the element at the right index is also equal to your middle position element so in this case the only thing that you can do is you should move your left and right pointers towards the center of the array what you will do is you will shift this left and right pointers you will shift them to one position and you will move left to here and write together you will keep doing so till this condition satisfies Wherever You Will generate a new middle position in your Subspace so essentially what will happen is there will be a point when you will your left and right will reach here your left will be pointing to here and your right will be pointing to so here you can check that your core is greater than 2 so your middle position it will be let's say this is the middle position now the middle position element is greater than the last element of the range so you can easily tell that in which part you are in so it will be the same logic for the problem that we I have provided are linked for and we have to just add this condition in this condition what we will do is we will increment the left pointer move the left pointer towards the center and also we will move the right Point towards the center and what we will do is we will move right pointer towards the center by decrementing it I hope you are able to understand it will be left plus so yeah and what we will but the water factor in this uh particular case will have what effect does this particular case will ever time complexity of solution or you can say that what effect duplicates will have any duplicates then work in each operation you are take another slide if there are no duplicates then in each operation you are dividing your search space what is the Subspace here such space here is nothing but the indices of the array which are from 0 to n minus 1 let's call the length of the num sorry as n so these are the indices this is the Subspace that I am talking about so your search space by 2. so the overall time complexity should have been if there were no duplicates of logo and since we are at each operation we are dividing our Subspace by 2 so these number of operations will be required log of n operations but here what is happening is to handle the duplicates uh is to handle test we have to just decrease our search space in a linear way we are just able to linearly decrease the touch space what I mean by linearity decreasing is we are just decreasing the Surface by 2 we are just in case of duplicates let me quickly change the color this is in case of duplicates at worst case scenario pardon me some spelling is incorrect I hope this is not affecting your learning uh we are just decreasing third space by two by moving left hand right pointers Center of array so in that case the overall time complexity will be in the worst case the overall time complexity will be or and N is the length of the num sorry so these number of operations will be required in worst case now what will the worst case all the values in Arya same and let's say you have been asked for Value to find Target let's say two then in each operation what you will do is say initially your left was pointing here this goes left and this was right in each operation you cannot do anything uh like that dividing the Subspace by half only thing you can do here is you can move your left and right position like left and right pointers towards the middle of the array so we will keep moving them and this will take you off and time complexity and N number of operations so this will be the effect that the problem statement is asking in a follow-up question follow-up question follow-up question this follow-up question so how will this effect the runtime complexity power and why so I hope you are able to understand it so in the solution of this previous part problem which I have provided you in the I button uh it will again be showing uh you in the I button here at this point of the solution on the autop right of the video so please check that out if you haven't till now it is necessary to understand this problem so what we have the studied is if the this is for the handling the duplicates is or let me quickly use on Stars so that you will be able to differentiate what is being changed this is different so what is different is condition is to handle the handle duplicates present in the num sorry what you can do is you will move your left and right pointers to the center of the array because you will not be able to determine whether you are in rotated part for the non rotated part of the input array so what is parties I am talking about this is the rotated part the part that have been shifted to front of the array from The Backs back of the array and this is the non-rotated part and this is the non-rotated part and this is the non-rotated part the part which was previously at the front of the array before the rotation was made so I hope you are able to understand what are known rotated body and rotated part is so this is to check that case and in this particular problem we are not no task to return the index at which the target is present we are just simply asked whether it is present or not so if it is present then this thing is also different instead of returning the index of the target element indirect we are just returning whether it is present in the array or not in the middle position happens to be equal to the Target then we will return true and if after completing all of this binary search we are not able to find the element if we are not able to find the target element then we will return false I hope you are able to understand the solution of the column and if you still have any doubts please feel free to ask them in the comment section uh thank you for watching thanks | Search in Rotated Sorted Array II | search-in-rotated-sorted-array-ii | There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why? | null | Array,Binary Search | Medium | 33 |
459 | Ki a hello hi description aman decide aur aa jaa rahe bijli iska guava do karane video me banegi third hai third question he is rather doing challenge see question what is shifted something pattern so why not distract can be constructed by taking substring operate and depending Multiple Officer Chintu Yadav Pumik Hujum Lower Case English Letter End Chalna Safer Chalna To Question Simple Take it Apne Ko Mila Hai Yes Baby Apne Ko Mila Ko Apne Just Pooja Voice I have to tell whether this is a friend or not he is some friend. Is it possible to make it through repetitions? As soon as Begahe is expensive, everything is expensive and houseful and appointments are not there, nor will you make something out of it means that if you buy a small one, it will do just fine, it means that what we have to do is spend that time by taking some obscene poster and descriptive. From whole lion like this is also here so I will request this also twice this baby I don't want to tell this trick to everyone, do n't tell yourself the pattern of any vessel, is it possible otherwise basically what do we have to tell, we have to weave a rich pattern which Let's become a police team. Okay, this is the pattern. Let's see the example of the most mobile Africa tour. This is the one. There is nothing in it that I repeat and make Uday Singh. So let's see this PC this I have. That on Thursday here I am feeling like ABC and full back made CB love now question patience this is a technique if it is a question of list then it also means a boil he found something then there is no blank-yellow on this a boil he found something then there is no blank-yellow on this a boil he found something then there is no blank-yellow on this It should come, you are going empty-handed, It should come, you are going empty-handed, It should come, you are going empty-handed, friend, you need a lot of hard work, it is not necessary that when in the video, but it should come after spending some time or got some bad completion. * Of course it was not going to happen, completion. * Of course it was not going to happen, completion. * Of course it was not going to happen, but in the question, what if it happens? So, the few alarms that I need, do it little by little, set so many from here, we will always add more good years and different, then that is available, subscribe and what did I understand on my questions. Seeing the bad way, it was interesting to me, I wanted to repeat it, I told that it is small and the setting of the training of the case, is n't it, I have the highest information of the candidates, I extract only praise, all Shakti Singh Kang The length was 129 and substring airways whether to remove it or not because now in the process of making it the police has tweeted and removed it from here, so if you leave from here then you will definitely have to play Ludhiana Mila's song sitting properly, how is Eid here if the goods stop this. Also come to hear this one: if the goods stop this. Also come to hear this one: if the goods stop this. Also come to hear this one: Finding the spread among animals, only then this trick will be possible, then cutting basil is something policy, why are you cutting it, this information is to say something, then twisting it is aside, then it means freedom from debt of 147 cotton, bride's wife. Garden police station of three line channel cases, then in my mind there is a bad help hope in bad when I made a single subscription and a picture wishing you that the bride will reset the card password, the acid and all the traffic of the ninth is known to the enemy is coming from the shampoo. Neither was that a record and there is a separate Singh Minister otherwise I could have done it. I thought, find out all these cuttings, it will generate praise to the said teacher. If you cut the maximum limit of more than 5, then most of the valleys in the city will know. Repeat it and repeat it again and again. -Will Repeat it and repeat it again and again. -Will Repeat it and repeat it again and again. -Will you ever be able to make a foreigner? Hey Chhetar Singh Bhatia bhaiya, repeat this once again. If you wash your face, then he repeated that it will be Rabdi, then it means that by increasing the length, there is no benefit in cutting the biggest SIM card. Six and a half from the first Baghwa. If it is inches, then this is the tree which gives an example for example, can I make you the richest or not? Okay, yes, there are two things to decide, first of all, two things, this means that we have blacked all this something, we have to listen to the voice mail message. Subscribe, we will do all the cutting, meaning if the end is this ring, then we will make the end minus one subject, how will we make it, now from Shiva to the next lens, the work of the bride's house and minus one can take all the lions, they will find a lot of subsidy job. The entire setting is closed, no, then what did he sit down after making everyone, he was not born, leaving only those whose multiple pieces would be taken, cut a lemon, serving separate scenes, Kunti also asked Sachin, will you ever be able to make a kiss in the country, apart from this, is there a medical facility? If there is no shortage, then it was decided that the information will come, length means from one line to the length of butter, all the shopping of cotton or and Kathua, in what way cartoon and in what way did it and father, I will shift in the middle of the gym which is multiple from the police. If a team can be formed i.e. if it is related to the entire spring, then from the police. If a team can be formed i.e. if it is related to the entire spring, then from the police. If a team can be formed i.e. if it is related to the entire spring, then giving an interview in Delhi, then the girlfriend's method, Candy Crush Land Cruiser Singh's, neither have I selected all the skips, or I cut, I do not remove 5 minutes, I can, or if I am doing a job, then I am an idiot. Why do I do it, I will never be able to come for 3 minutes and this is only with the help of this, it is like this, the whole body is complete, till the body of my family, then what should I do, friend, I have to find the owner, the shooting is fine, now we will see whether it was both. I will repeat the setting of meaning I will keep repeating, so for the entire screen, there is a Kangaroo team from the compensation equal to Rs. I will try to do this for some time 6590 that I will discuss right now what we will do if we take these then brother we all will be squirting a prefect settings na subscribe and meaning turtle cutting will not give backward traffic but which lens is cutting The length of which is multiple of that which is its length multiplayer Uday Singh Balance meaning like the music is a 15 minute cartoon, then this is what I decided is Kaliyug, friend and the plane was done whose Ranjit Singh Bhati fitted on it is equal to nursing in two places. But open us today and now think man, let's do something less means Singh will leave the ovation, on top of testing also means Singh will attend the meeting, what is the use of it, think like this, accept ABC's ABCD, here how much is the value of knowledge and get exemption from one exam. Don't give, this will be the beginning of solution three. Apart from this, if I submit any river and see, then I am telling my own, I still work just for the lens, this too, I want to send the video of Tasleem Arif to me, you will get it. Now I have accepted that BCE is fine that 41 will be made per Eid, only one by one, the senior team does not do this even on Thursday, what do they do, what did I do, what is the point, it just happened. Let's take an option, Robbie hides that this CID BBC Link MP3 How many Sachin's not cutting this thing is total 10 Neither one's afternoon is five gone nor one girls will be found Two girls will also be found Five girls will be found That all will pay 260 of BTC If we start from this, then come, I will call from here, okay, I have decided that brother, please send my present to everyone, I want to make both my alum Singhs, is his part available in that day, so let's meet here, okay then these two. I will move forward together for now because but the camera person or this is again matching the original center something that is being made, do not match and don't do no why set these 200mb Sam Ghosh I am sitting in ABB that in the film What is shown, whenever it comes, I will keep points in real singh, ghee here, but these two points are appointed, I have told which part I Gurjar Singer consider, to mash with myself, if he will match them in the middle, then mature, we will do so. We just don't pick up, then this event will also mix these treatments, brother, how does this always happen, it is with those who can meet that day, isn't it, if the thing of 5 lenses came, then what would have happened, it would move forward for 5 minutes and move forward in between that. No, okay, now if we sit down to check, this is the only match for the snake, then take it forward, what is the use of repeating it, go to the return forms, that is, from here, stop chatting, then Africa or ABCD will do this, it is ABC that I will be here, yes, now we remember the match, this match has come and everything is good, it was fun at home, now what should I do, this match was about to come, organizers, now try the match for 5 minutes, I went, friend, this match is about to happen. It is a matter of benefit to go back and forth, is n't it our thing that friend, I have subscribed account on my side, it is okay to have such and such length whose multiple is gone, select Prince Singh's 98, which means multiple ordinance is okay, no zoom, repeating and missing. Belt length brother, what do I do after that? I sat down to match my substring with the lessons of my acting course Nal Singh, but I had the courage to match these three lengths, these three lamp patterns, which I had done earlier in the testing. The match is done, the match is done, this is what I will do, the organizers have said that next I will match it, if there is a match then it is okay, if not, then the voice, if the match is done, then what will I do again, the song of the next three days, organized by Main, will be done in this way. What's going on, Baghwa, do you spoil that you will be able to do this, it's okay, if you are in a bit of a mood, then I will take a look, then court friend, we had decided that the appointment is equal to a co- we had decided that the appointment is equal to a co- start lens, meaning set this note that when I will You had taken that I am going to go back, the results are today itself, that it will be at least so that it will be bigger, so do it anyway and I am more like this, at least this entry should be less - - We have submitted here that entry should be less - - We have submitted here that after this What will we check? After this, we will check whether the length of the team is a multiple of the original inch or not, meaning Maine Pyar Kiya Drink Difference 501 Alleged that he is celebrating Venus for five minutes, now only then I will do it That you will even get the idea for just ₹ 5, you will have to will do it That you will even get the idea for just ₹ 5, you will have to will do it That you will even get the idea for just ₹ 5, you will have to subscribe 515 times to Malik Sangh, set a reminder to subscribe in 2006, what is this, brothers, now let's make a pattern, so the pattern we are trying to repeat. This start substring of the pattern is 128 and is hanging from 80, meaning let's say that it is Eid happened, take it like young, do we have here the length key, first of all it will go not only 5 inches, 5 minutes, but first of all it means Lucas has given his debit If he wants five then first of all Sachin has a direct competition, he is leading his side, he will have to make it by repeating, so this is the pattern, isn't it, the button by which you are planning to make a Muslim by folding it, that TK ji keeps only one. Said in a program organized that will keep the current lion so that the current score matches these tie equal to two keep on the line and thick gel equal to keep on Pluto yes I - one par kya baat kah raha hai Pluto yes I - one par kya baat kah raha hai Pluto yes I - one par kya baat kah raha hai If you do and tell me, I am trying to write a little smart that we have gone to the plane, brother, this is ABCD, we will repair it and try to make the volume setting, okay, it means lunch, first of all, decide this flower 10:30 decide this flower 10:30 decide this flower 10:30 How many did we cut and cut? Serving the color, this pattern will be made, the first one to reach and try the five lenses, okay, so we made PM for 5 minutes, now look at this digestion, we made it, where to find it, so what is the use of this garden, after this, check. So, where have I kept it, I have kept it above these planets to take votes, spider-man 2 index will come back and will take votes, spider-man 2 index will come back and will take votes, spider-man 2 index will come back and will sit here and will go and sit as if it is the fifth son, meaning I have been here directly for the last five months. I was sitting and I will talk to you, I will try to match this subsidy to a lesser extent, if it is not possible then return it, then when you get the baby, in the case of a baby, it will be sitting in the eye room. That's why I go to sleep, then again with love, if you try to mash it, then it is Boiled Jade, but this drink means like, what will we do with it, by increasing this ID, this one is Samsung's, in which Jha is increased. You will see that accused Singh matches the text of the original sin, how am I a little inside, this is my pattern, this is my friend, it is fine, I had made all the Singhs in the parts of the text, I have placed them here, I have kept them here, I will check this match with the party and It is match by point and increase by . Brother Rajesh, how long should you keep increasing increase by . Brother Rajesh, how long should you keep increasing increase by . Brother Rajesh, how long should you keep increasing until it reaches the last position? If you put the tempered glass down, does it mean that it had reached the last position by matching? What does it mean that all the lions are matching, all the subscriptions are mashed with that pattern, here on the day of the start, on the sister's day, this is happening and people celebrate one day and one day here. That Singh, all Singhs are equal to a good thoughts, the side of strength was Ujjain, leadership was Laxman, what should I say now brother, BCCI taught me here, ABCD 123 in which match has to be done, neither is the most famous for this, about this and this. My pattern is not matching, then Leo's pattern, God Ad Notification, all this is like a friend fall, that is, it is not equal to Satsang in the pattern, you roll here, take two breaks, take a turn in these, check in etc. What will you do if Aa has not gone from SDM? Now let me tell you the meaning of both the hands. Do it, I have written these two lines quickly, I will give the meaning of Aa to see. What have I written here that let's go with 19th. Then let's see what we have tried to do here, which I think you must have understood. For your spiritual peace, I would like to tell you that I will get spiritual peace. If you all have understood, then this is what you understand. If he has come then we can run from here also, he did not come, see how he cheats on me, what should I do if he does, this was a ritual, okay, we gave him the flour of a sub-singh, for this we gave him the flour of a sub-singh, for this we gave him the flour of a sub-singh, for this we named this part or pattern as If we take the name of the pattern, then what do we have to do by repeating the previous part and repairing this part, Vinod Singh knows whether it is being made or not, then in what order we have made the organizers sit here for so many lengths. Trim's next lesson Sweet Life How to do this pattern Yuvraj Singh is making the most of this I and J It is matching with these waves Wasn't it, I am doing this What is this reception This is in the original print This is the most requested, hence it is cut here when this part was mashed from Spain, what will happen that Ayodhya will become great and will give it here, make it the base and get updated that Ayodhya will be updated, I plus options are open and G plus equal to two. Land on Okay, so Ayurveda years ago, Ayurveda was sitting here, he will match himself with the pattern, he did the original sequencing of the listing, do this pattern's dough with special gift and these three are okay, he trained this pattern with this pattern. So close, it was said that it is available in the next part, no, in the next part, how much bigger balance, by increasing the volume and by increasing it is coming here, it is not coming, when they are here, the message uncle, think if the team was better and could have done variety of foot. Yes, it is ok only till here and this too was matching, the pattern was proved, was it organized, then once the middle class 10th and organized payment had reached here, if Ayurveda treatment was reached here then where would I reach, my advance gets reduced. That's why I have said that if you have any adventure then please return it means that the pattern we had chosen has been repeated and the police team has been formed. If it does not happen then please accept this. This is what Raman Singh has said here. This secret of ancestral birth was lying in the text message that it is not me, this outline goes and it does not happen on IN, I assured that till now all the parts have matched, okay yes, I did this, so now this is the habit of the sea. Let's see and run it properly. Yes, he is right that we have messed something up, play that yorker oh god - and adventure swing, neither did the signal operation, typographic mistakes are made while writing in 25, Jai Ho. Om Prabhu, I have also written here once, now I would like to read it myself, till then, Ireland - Manzil Inch Plus Live - Ireland - Manzil Inch Plus Live - Ireland - Manzil Inch Plus Live - Vanshvriddhi Assistant Vice City Plus Enter Katenge ki ke liye hai in this video, so it is our solidarity against it, let's kill it by submitting. Give it is set that there were more than 90 times in it, but what did it do, first of all, what did we have to do, we have to make it into a hum, is there anything obscene in it, which can be made complete by repeating, have you said that we all subscribed? Let's do it, then which subject should we do? Jairam said that we do the biggest mandi from the building till half an inch, after that the Sunday after that is not beneficial and Vansh should subscribe with half painted one, isn't that also the deprived youth multiple whole team. No, okay, so to do this, we have put below that brother, the length which we want to compare will be useful only if it is related, then check what we have done for career length and 1000 t-20 for minutes. If I want to set one too, then 1000 t-20 for minutes. If I want to set one too, then 1000 t-20 for minutes. If I want to set one too, then first of all I have given the name Pattern to both the cigarettes, Oregano is one of the most original Sin, now after doing all this, what did Original Singh do, this balance was cut, this is the 10th history, so what did the lenskart method do, its just arrived. It has been said that I have to match from this point, then I will take it further in this match, so he Amazon, I have to do a test match for this, I have to keep doing the same thing, if there is such a match, then what did I do for that, I made Ayushi do this. Jio SIM point, I want to match that Riya with the school pattern, then keep moving with the right and with increasing balance loop, share this with plane friends in lunch, which is the need of the hour, this should be in lunch. Okay, on which we submit, if it comes from a string, then we fasten it, pick it up, check whether the pattern is matching with the appointed pattern, break it or else move ahead. I must have been sleeping, so where will we reach? Exactly where will the adventure reach? We have also seen something like this in the past, we returned to 1000, by the way, I hope you know this, you do not know what time it is, for that, let me tell you my pattern here, so here I have told my friends to reduce it. I have used this for this means I should have been out, keep the sequence on your side so that we will just take the pattern and have taken the most interesting vegetables and will take this pattern back. I have ignored Delhi, why is it not there to compare, it is in refueling, friends. If you use it daily every month then friend and among these are not serious then we will add this Tikki address will be on us. If you are welcomed with us then we will have to compare in this way. Okay okay, friend in the edit to read or subscribe. And see that, but you will experience this at this time, its value is done on the cricket stadium, Terribly Kohli or not, you can compare MP3, so this was the question, you can submit the question, you are available to change it, if you like the video, then please give it a flight by commenting. Please tell me any change I can make with it. Yesterday many people told me that if I was in Noida, then some video editing would also be good for you. If there is any problem with that, then due to this enthusiasm, I try to make it in a quiet place only. Apart from Sakun, subscribe this channel, if you have n't subscribed, then you want any video from me or anyone else, then I do not make it alone, now Vikas is also with me here, Bittu is there, all three of us together make videos, so there is someone like this. While leaving the video, you guys told us the topic, we will definitely try to make it a video, institute-wise, Jai Hind, make it a video, institute-wise, Jai Hind, make it a video, institute-wise, Jai Hind, Jai Bharat. | Repeated Substring Pattern | repeated-substring-pattern | Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
**Example 1:**
**Input:** s = "abab "
**Output:** true
**Explanation:** It is the substring "ab " twice.
**Example 2:**
**Input:** s = "aba "
**Output:** false
**Example 3:**
**Input:** s = "abcabcabcabc "
**Output:** true
**Explanation:** It is the substring "abc " four times or the substring "abcabc " twice.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters. | null | String,String Matching | Easy | 28,686 |
322 | leak code question 322 coin change so you're given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money return the fewest number of coins that you need to make up that amount if that amount of money cannot be made up by any combination of the coins return minus one you may assume that you have an infinite number of each kind of coin so here is an example we have coins one two and five and the amount that we need to make is eleven the output is three coins are needed to make the amount eleven and those coins are five and one remember we can have an infinite amount of any of these coins so we have chosen five twice here plus one okay so this is a very tricky question there are a number of different ways that we can compute this answer we can use a depth first search recursive solution we can use breakfast search but because this question is asking for the fewest number of coins so it's asking for an optimal so anything like the fewest number the greatest number the highest amount the lowest amount usually is looking for the optimized approach of dynamic programming as the solution so let's discuss dp there are two possible ways of carrying out dp there is a top down where you start from 11 and branch out and work your way down through possible solutions or there is bottom up and bottom up is the approach we're going to be taking so bottom up requires you to start at the smallest possible amount so say we chose the amount of zero and work out the solution of that amount and then we'll work out the solution of the next value to that so that'll be one and then we'll work out the solution to 2 3 4 etc so we're going to create solutions to sub problems and then we can ultimately use previous sub problems in order to generate the actual solution to 11. so with our dp bottom up solution we need a dp array and our dp array is going to store all the solutions to the values between 0 and 11. so we need our dp array to contain amount plus 1 values so once we have created this we need to initialize the dp array with a certain value now remember from the question it asked us to return -1 if we couldn't asked us to return -1 if we couldn't asked us to return -1 if we couldn't find a valid solution so if no coins would add up to the values say we had coins and we had an amount of two no coins will ever make up two so in this case we need to be able to return minus one so what we need to initialize the dp array with is an invalid value so if we initialize it we say positive infinity and we initialize each and every value with positive infinity then if at the end say in this example we have infinity at the end we can say if dp at current amount is greater than the actual amount then we can return minus one else return dp at current amount with positive infinity so now that's the dp array sorted we can start adding values in here so firstly with this dynamic programming solution we can add a base case to this and the base case in this example is going to be dp at zero so how many coins does it take to make zero it's going to take zero coins to make zero so now we've updated the infinity with zero and now we can carry out this process so how many coins does it take to make one well we need to loop through the coins right so we're going to start off with one we're going to check so the current amount of one is within coins array so we can just say it takes one coin from the coin array to make the current amount of one let's move along so at two we can again loop through the coins array so we can see that two is within the coins array so we can just update that with one coin because two is here that is one coin we'll add into the dp array now moving on to three let's check this so dp at three if we start off and we look at one so we have taken the coin one so that counts as one coin and we're going to add the remainder so we're going to add the amount the current amount minus the coin that we just took so minus one gives us two and the minimum amount of coins it takes to make two is one so that's one plus one which is equal to two so we can put this in here as a temporary value then we need to go across again to the second coin which is two so that counts as one coin and then we need to do the current amount minus two which gives us one and that is also one so that is equal to two and lastly when we get to five well the current amount minus the coin is less than zero so we can exclude that we can add that as an if clause so we can say if current amount which at this moment in time is three minus the coin five is less than zero then return so now that we've done that we can move on to four so dp at four is equal if we choose one that counts as one coin then we have to do the current amount minus one which is equal to three so one plus two is equal to three we can add three in there as a temporary value but we still need to check the other coins for a minimal so we move over to two counts as one coin and then we do current amount minus two which is equal to two the smallest or the minimum amount of coins needed to make two is one so we add that one and that is equal to two so that is smaller than three so we can update this to two then we move on to five current amount minus five is less than zero so we don't include that so now we can move along so as you can see there's a pattern here and this is what's called the recurrence relation so dp at current amount is equal to the minimum between dp at current amount or 1 plus dp current amount minus coin so if we look at five now we can see that coins contains five so we can just add one into there so if we move on to six we start off with one so dp at six is equal to one plus six minus one so six so here we have one plus dp current amount minus coin so current amount is six minus coin so we've got one so we work out the dp of that so that's one so that's equal to two we can add two as a temporary value and check the others to see if there's an even smaller value so dp at current amount is now two so dp down here becomes two so then we move on to the next point we take two so that counts as one plus the current amount minus two which is four so that's plus two so that's equal to three so one plus d pick current amount minus coin is three which one is minimum two so we can keep this as two okay and then if we moved on to five counts as one coin six minus five is equal to one so that counts as one again so one plus dp at current amount minus coin is equal to two so we can keep two there and then we can carry out this process for the rest of the values so dp at seven if we choose one we have one plus seven minus six which is one so that's one plus one which is equal to two we can choose two to begin with we have our current amount at the minute dp account amount is equal to two if we choose two that's going to be equal to one plus seven minus two which is five so it's going to be one again that's equal to two so that's two so the minimum is still two if we choose five now that's one plus seven minus five which is equal to two so that's again one which is equal to two dp at eight if we choose one it's one plus eight minus one which is seven so that's equal to two so that's equal to three so current amount dp is currently three so if we move over two that's one plus eight minus two which is six so that's equal to two so that's equal to three as well so those are the same then we move over to five we have that counts as one coin eight minus five which is equal to three that's two so that's also equal to three so we add three in there dp at nine we take one so that's one plus current amount is infinity one plus nine minus one which is eight so that's three so that's equal to four against infinity which one smaller four so we can have four in there as a temporary value so four becomes dp at current amount this gets emptied we move across the coin so if we take two that's going to be one coin plus nine minus two which is seven so one plus two is equal to three is less than four so we update here with three so that becomes three this is emptied we move across to the next coin we have five so that counts as one coin plus nine minus five which is equal to four so that's two which is equal to three and three both the same value so we can leave that as is dp at ten if we take one that counts as one coin plus 10 minus one which is equal to nine so that's three so that's equal to four so infinity against four which is smaller four is so we have four in there so this becomes four this is removed we move it over to the second coin so that's 1 plus 10 minus 2 which is equal to 8 so that's 3 again so it's going to equal 4 so 4 stays there and then lastly we choose 5 which counts as 1 coin plus 10 minus 5 which is equal to 1 in the dp array so that's equal to two so four against two is the minimum and lastly for dp at eleven if we choose one that counts as one coin plus eleven minus one which is two so that's equal to three so infinity against three is minimum so three can go in there as a temporary value this goes to three this is emptied we move over to the second coin so that counts as one plus eleven minus two which is nine three so that's equal to four is not less than three so we can forget about that we move over to five that counts as one coin plus eleven minus five which is six so that's two so that's equal to three and three is the same as three so we can keep that in there now that this array is full we can just return dp at amount and remember we need to make sure that we have that if conditional logic just in case this value is still infinity so in the case of this example up here if the last value is infinity we need to return minus one so i'll show you that when we code this out firstly let's discuss time and space complexity so time complexity is o s times n where s is the amount and n is the denomination count and then space is o s where s is the amount to change so when writing this out it doesn't actually take much code so firstly if we create the dp array so we say array amount plus 1 because we want to have zero up to amount so we need to add that extra value and then we need to fill it with an invalid value so that's going to be infinity we can set the base case this dp solution so dp at zero is going to be equal to zero because it takes zero coins to make the value of zero so we need to create that for loop current amount is equal to one because we've already carried out zero up here current amount needs to be less than or equal to amount and then we can have current amount plus now we need to loop through the coins so coin of coins if current amount minus coin is greater than or equal to zero then we have a potential value because remember if it's less than zero then we just forget about it because it's not a valid solution then we can say dp at current amount so now we're going to start filling out that dp array and that's going to be equal to the recurrence relation we created so it's going to be equal to math.min dp at going to be equal to math.min dp at going to be equal to math.min dp at current amount for the current value within dp and one plus dp and current amount minus coin so we're going to loop through the coins we're gonna check the coin minus the coins value from current amount and we're gonna add a one here and this one here resembles the current coin that we have taken and then to end off we need to include the if conditional logic which determines whether the value is equal to minus one or the dpr amount so we need to return dp at amount if that is greater than amount so if it's infinity we can return -1 so if it's infinity we can return -1 so if it's infinity we can return -1 else we can actually return dps amount let's just check see if that's worked it's been accepted let's submit it and there you have it | Coin Change | coin-change | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104` | null | Array,Dynamic Programming,Breadth-First Search | Medium | 1025,1393,2345 |
1,752 | Hello Happy Birthday Bhaiya Ko Interwoven Any Problem Research One Only Are Short End State Government Interior 173 Return Value History Sadhe And Problem Hai That End Would Be Given Declared Welcome New 2018 How To Enter Final Year Shiva Are 3512 Time And Obscene Short End Routed through if the output is dry sonth hai shravan stars decreasing only one effects of examples are isko bhi ri 14521 ki pati hai that on this number shruti electronics numbers what is the number here please subscribe for november and in this case hawaii which is into effect C e agri dubai which number one and five plus one is going to be born in it is going to be born in more people subscribe to this channel Don't forget to like and subscribe to a few seats in problem set me difficult rule to find the index of rotation what is going through your phone into account the any1 account deficit till counter a greater can cut interactive way depression point its creator wants fame return for not Written Episode and Listen on Thursday To incremental counter subah and they are saffron the ajay ko ki ek plate a saiya pit transport se zulm find solution for two problems with similar products point minimum interested in soil returns water in liquid subscribe to | Check if Array Is Sorted and Rotated | arithmetic-subarrays | Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`.
There may be **duplicates** in the original array.
**Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation.
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** true
**Explanation:** \[1,2,3,4,5\] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\].
**Example 2:**
**Input:** nums = \[2,1,3,4\]
**Output:** false
**Explanation:** There is no sorted array once rotated that can make nums.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** true
**Explanation:** \[1,2,3\] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100` | To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic. | Array,Sorting | Medium | 413,1626 |
219 | Hello welcome back friends loot problem 219 content duplicate 250 start looking details into this problem is mentioned that if one to three digit code solution videos in java and java j2ee related interview helpful videos come also have a positive created play list for list solutions advisor important you No Java Interview Questions Will Judge Define Research Tree Edward Dynamic Programming Swadesh Play List A Positive Label To My Channel Please subscribe and It's Not Good Material Is A Please Subscribe So Let's Look Into This Problem Not Forgive And Interior And Arms And Interior's Return Form Is During to distinguish India S I N G L in the research that is named Safiqul Poonam Subject and Episode of I - 23 Jan Bluetooth K So this is and Episode of I - 23 Jan Bluetooth K So this is and Episode of I - 23 Jan Bluetooth K So this is the problem statement so mm so example give one example share so let's take one example and share and they Will discuss in Surplus reddy123 and disaster in Digest of the Rings 1006 What they are going to do to solve this problem which you have to find out during your indicate elements with the distance equal to listen or equal to two requests to hear for example if You see this one and Yashwant sur distance between to - 0 is to so we can return true spirit of how will be to - 0 is to so we can return true spirit of how will be to - 0 is to so we can return true spirit of how will be implemented solution is hui argument user has made after winter and list printed add the validity so let's go through period related through the year end Lifted her first Stuart make I can explain how they can implement the solutions for Delhites is time you probably value its the day after tomorrow first element extinct is lineage so this is not a rhythm app so they will put one servi and they will put and list of The India It Is Zee Induced License For One So Now Here To Write Two Years And 202 Dars Will Create Entry Into His Mother Index Will Be Given Her Right Call To So That's Our List Hua Sonics Element Competition Hair Solve Would Have Also Will Enter Slaughter Index Nearest to Bigg Boss-2 is Slaughter Index Nearest to Bigg Boss-2 is Slaughter Index Nearest to Bigg Boss-2 is the index Nominee Entry Istri Show Will Make Entry Because It's Not Available Hair Shodh Index Pati Here Some Villagers End Three Index End Native When It's One Is Index For Us They Will End Up For Hearing Tower List Ajay And Next is to super to will and five years in the earliest that and next is 3 and will add 6 * or that and next is 3 and will add 6 * or that and next is 3 and will add 6 * or list his favorite song this is the way already from his Amazing they are now what will be doing this will take you will read this House Map And Will Only Look Into The Entries Which Are Having The List Size Subha Greater Than Or Equal To Two Right Greater Than Or Equal To Two And Why It Is The Great American To Because Hui And Finding A Duplicate Entry Child Rights Or Duplicate Entries Will Only Happen If It Is Great Than Or Equal To Right Dalit Sahitya Wife So Will Take It's A First Year Looking At One So Weird Look Into This Leads To Avoid This List And You Will Find Distance Between All This Element Ride Sharu First Will Find Distance Between 0 and in 2012 * - 00 Distances 218 How To in 2012 * - 00 Distances 218 How To in 2012 * - 00 Distances 218 How To Therefore This Day And Equal To Right Short Will Daily * A Software Of High Class Go Into Daily * A Software Of High Class Go Into Daily * A Software Of High Class Go Into Returns Through Investments To Find Delhi And Distances Lose Aniket Day Will Return Form Soe This Fluid The Oldest Map And Will Never Find Any Entry Which Is The Record Broken And Will Return Forms In That Case 34 The Implementation That Were Going To Solid World War Implementation Hair Software Creating Map Of In Teacher And Student Teacher Hair And Share Trading Gare Number And Hui Opportunity In The Map Android Software Will Never Dare Is No Entry Hui Creator And You Will Destroy Evil And The Index And Will Update Entry Into I Print The Number And List Play List Solid And Villages And The Index In To-Do List And Again Will Further Entry At Least To-Do List And Again Will Further Entry At Least To-Do List And Again Will Further Entry At Least Back Into them have rights over this for jupiter donga map is ready tuesday now you visited this map here and they will get the earliest and they never leaves for his greatest enrique want to means late evening delhi's duplicate elements present day to you will get through this List and will check the I plus one and I think will check in last rights and duties and distance between that I plus Vansh and identify this place in equal to senior Jin viewers return form basically din hui already foundation day to you are looking for this Is the conditioner eight otherwise set and vital force co clips take the examples and have given sirvi and mirch square sans points 100 is so is printed on this map to show you how the map look life so for example if you look at the first example i police And one and will enter in devices printer 2013 and for two it printed one here two in one hand free is drive subjects of the match pure athlete and will look into delhi seema how much distance with fine between the corresponding element side subah software doing some research Remote system dot statement only to show the map internal submit solution is to tax act by it's good for this is the way you can solve the problem content duplicate to so you can just like solid with the help of map and in you can Just You Know Drivers Discuss Pending List Check You Find Like If You Find Any Kind Of Distance Each Rate More Equal To Kevin Vijendra List Element Right Side Effects Code * Kitab Account You Can Check There Effects Code * Kitab Account You Can Check There Effects Code * Kitab Account You Can Check There Sole This Phone Create Lead Solutions Jha And Sony Samsung J2 In Interview Helpful Material Videos and Please subscribe to the Channel You Will Get Laptop Good Videos Here Thanks for Watching | Contains Duplicate II | contains-duplicate-ii | Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105` | null | Array,Hash Table,Sliding Window | Easy | 217,220 |
46 | morning everyone this is logic coding today we are going to look at another backtracking problem called permutation so permutation and combination is a type of problem that backtracking and recursion can give us all the possible results so in this one it's pretty straightforward we're given a vector of a integers array of numbers of distinct integers so every number is distinct and i want to return all possible permutations you can return the answer in any order for example if we have one two three we would have six different possibilities in the first position we can either place one two three so in the first position i would have a choice and then in the next position because we have already used one possibilities i only have a minus one choice and then until the last position i just have one choice cool then um to do this we can build a backtracking function and at the first index i have unchoice i can iterate from the very first to the very last i can swap them so i have n choice and then um the next is i plus one in the next choice because the first is already fixed then i can only swap my second with the rest of them so as always for backtracking we um okay before we do the implementation let's look at time complexity the time complexity would be n factorial as i just described and the space complexity would just be o n because of the recursion stack now let's look at the implementation so as always we first declare a solution holder whenever we meet the end condition we just append the current permutation to the answer and then we define a backtracking function which takes the numbers current position this i index we start from zero and then the solution holder so now let's define this backtrack i have my numbers i have my index and i have my solution holder so if my index reaches to the last which means i'm down with the current one so answer would be pushback the current numbers and just return otherwise at this position i have from it to the end choice so i start from the index i end with its size i plus at each i can swap my current with i of course i need to swap it back but in between i can continue my search parties for the next position answer so in this way at each level the choice will be decreased by one and until we reach the end we can explore next level yeah i think that's pretty much it again it's a template question for backtracking but it teaches how to do the dfs in the solution space and practice on the recursion structures we have an end condition and at each level we have some certain constraints for this one we actually do not have any constraint and we do not any duplicates but we still have the outer for loop for all the possible choice and the action for the current level continue this call the recursion function and backtrack let's try and run the code try and submit it looks good cool um this is very similar to the video that i just did called generate parenthesis and letter combination and i'm going to let me actually let me double check of the time and space complexity oh yeah so if we um if we consider our answer also as the space complexity then we do need n factorial space as well yeah so answer is also in factorial china okay cool um but if we do not need to consider everything then i'll just say it's om because uh oh it's actually we do it's one if we do not need anything but the answer itself will hold in factorial time that's it thanks for watching see you next time | 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 |
793 | anyways what's up this is your girl and today we'll be discussing problem 793 or fleetwood so follow those who would not read the question i just pause the video here and please read the question okay I hope you must have read the question and question is not at all difficult in understanding so straight we move to the solution how will we approach the question okay so as you all know that you know zero factorial this one having no zeros at the end similarly 1 factorial 2 factorial 3 factorial and 4 factorial why because they have no 5-minute the number of zeros in any 5-minute the number of zeros in any 5-minute the number of zeros in any factorial is you know defined behind however how many fives are there right so basically from 0 factorial - 4 factorial we have 0 number of zeros - 4 factorial we have 0 number of zeros - 4 factorial we have 0 number of zeros from 5 factorial 9 factorial we have 1 0 and then from 10 factorial 2 15 factorial 14 sorry same similarly from 15 to 19 we have three zeros from 20 to 24 factorial we have four zeros now the mean part from 25 factorial n factorial we have six zeros at time I hope you know the reason that 25 is 5 into 5 right so basically we have only two possibilities for the answer either our answer would be 0 suppose I ask you for k equal to 0 what will be your answer it will be 5 because 5 numbers are having zero zeros at the end or equal to zero answer is 5 for k equal to 1 we again have 5 for k equal to do we again have 5 for k equal to 3 again 5 for k equal to 5 we do not have any number whose factorial have 5 zeros at the end so what do we need to do in this question we have to check whether the number whether there is any number who contains a number of zeros at the end or not if there is no such number than the answer is zero if there is any such number then the answer is fine of this No so we can basically apply binary search on this okay so this is a basic function which calculate the number of C using any factorial I hope you know this how we calculate the number of zeros if not I mentioned only in the description please go and watch that video it is very small with you know the main function so what do we do in a binary search we take a start so start is zero we take the end you can take any end but here we have given we are given that there can be K can be in the range of 0 to 10 to the power of 9 right it means there could be 10 to the power of 9 zeros at the end which means there are 10 to the power of 9 fives in any number right in to the part of 95 which means there has to be if we do not know how many suppose in the worst is each at every 5 we encounter 1 5 right when we have 5vm 1 5 at 10 we have two fives at 15 we have 3 5 6 so in the worst is 10 to the power of 9 this can contain this number can contain 10 to the power of 9 fives in the worst is right but as we know 25 contains two fives 50 contains 2 fives 75225 125 contains 3 fives right so I have taken the maximum I've taken the long max so simply how we approach in a binary search we find the mid by start plus n by 2 we check how many zeros are there in this factorial in mid factorial if X is equal to 2 which means a number home we simply return on sulphide suppose that had this the number of zeros and more than key which means that the number the current factorial which were calculating is much bigger is containing your number of fives so simply we what we do is n equal to mid minus 1 and if it is having lesser number of zeros then he we have to increase the number we have to increase the factorial so start is equal to n plus 1 this is how we do it and if there is no number if there is anything suppose for five there is no such number then we have the answer right we return 0 this we were trying for this let's do it right suppose my star is 0 and I'm not taking very big number let's is end s 100 ok and I am calculating for k equal to 2 k equal to okay so initially mid is equal to 50 it is equal to 50 the number of zeros in fifth effect to rely definitely more than 2 so start is very sorry the number of zeros are very greater very much greater than 2 so n is equal to mid minus 1 so what will be our end it will be 49 now again mid equal to 24 factorial again contains more zeros so n is equal to 23 now 23 by 2 0 plus 23 by 2 made equal to 11 again 11 factorial contains 2 zeros right so this means the answer is 5 now let's suppose the same case but with k equal to 5 we know that k equal to 5 the answer should be 0 so let's dry run for this again 0 comma 100 our mid would be 50 the number of zeros are definitely more than 5 right so our new is 0 to 49 the mid is 24 okay number of zeros is 4 so start is v4 is definitely 5 which is greater than X which is greater than number of zeros so will increased our start would be now 25 and my mid proved my end would remain the same 49 this is mid would be startled aside by 2 which is 14 right again thirty seven factorial zeros are much greater than five so n would be 36 now from 25 to 36 25 plus 36 by doing so this way it will be my end will be lesser than start this will go on my end will come less than start so this loop will get over and it will return answer us 0 I hope you have got this question if you liked the video please like hit the like button and do subscribe to my channel thank you | Preimage Size of Factorial Zeroes Function | swap-adjacent-in-lr-string | Let `f(x)` be the number of zeroes at the end of `x!`. Recall that `x! = 1 * 2 * 3 * ... * x` and by convention, `0! = 1`.
* For example, `f(3) = 0` because `3! = 6` has no zeroes at the end, while `f(11) = 2` because `11! = 39916800` has two zeroes at the end.
Given an integer `k`, return the number of non-negative integers `x` have the property that `f(x) = k`.
**Example 1:**
**Input:** k = 0
**Output:** 5
**Explanation:** 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.
**Example 2:**
**Input:** k = 5
**Output:** 0
**Explanation:** There is no x such that x! ends in k = 5 zeroes.
**Example 3:**
**Input:** k = 3
**Output:** 5
**Constraints:**
* `0 <= k <= 109` | Think of the L and R's as people on a horizontal line, where X is a space. The people can't cross each other, and also you can't go from XRX to RXX. | Two Pointers,String | Medium | null |
148 | Hello and welcome to the channel, so today's question is 148 Saltless Four will come here, 3 will come here, okay what are you doing now, what is your method of merging them, batter, so equals have been added. And slow is equals then added ok and one you prefer take divide karnal demand people then what will you do vile fast is not equal then null and pass next is not equals then null will go once what do you have to do now Divide it into two parts and divide it into prove what will you do what is its name what is function list Vishnu to return list two parameters list note left note right is not equals then we will learn write. Done next, both of these are done, now what will you do if you don't have time, if this is equals then will happen every time, will happen every time, will happen every time, okay m.next this equals then left, if equals then right what will you do in return, what will happen to you next will be return Your return should be on which line This code should be equal to this and support it once I have more elements then we will check There is none and once I take all the elements then what will happen | Sort List | sort-list | Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)? | null | Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort | Medium | 21,75,147,1992 |
1,483 | hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go it's close but uh it seems good so on to the last one cave ancestor between node so yeah q4 this is I don't know what so a lot of people would have refreshed six people already got accepted so well done though six people I was way you know this is only ten minutes into the contest I was like wow it's still something I'm missing do I because for me I died I don't know if this is a known problem of simple arm and you know leave a comment later below and I'll explain how I solve this later but for now I actually knew when as soon as I saw this problem I was like okay it's some of this is matter but it's a q4 on the code which I've had practice on demons it's a quad core hard problem and for a hard prom you probably can't blue force and my blue force I mean an N squared query that goes up way like of each query takes off and time that's too slow so immediately my I my dog process jump to finding a log n process where n is you know five times ten to the fourth and that would be fast enough so I was just thinking about well and this is something that actually reminds me a little bit of omq algorithm I was thinking that's specific to that but that kind of technique where well we need to fit some in log n so instead of storing now in a naive way maybe you could store the distances it's like okay for you snow store the first ancestor the second ancestor the third ancestor and so forth way and for if gap and nodes and gather a degenerate case of baby central inkless where one points to zero two points to one and so forth you know come en square so those are the things I'm thinking about and in this problem so I knew how to do this problem immediately ish but it's the first time I've ever meant something like this I was really thinking through and to be honest I was just thinking wow people have solved it really quickly it's still stupid away is there an easier way is there more obvious way or am i doing like you know more work tenants for I didn't really think I didn't I couldn't find one so I mean that's not to say there isn't but I couldn't find one during the contest while are solving this so yeah so the idea behind what I later end up doing for this problem is just instead of storing the first ancestors the second ancestor to do dances and so forth we stored the first ancestor the second ancestor the fourth ancestor the eighth ancestor and so forth so basically we store the powers of two ancestors away and from that because there are most like n powers of two ancestors everything would be log n ish I do a more in-depth be log n ish I do a more in-depth be log n ish I do a more in-depth explanation and analysis of this later on in the camp and in the explanation section but yeah but basically that's all those things that I talked about other things that I was thinking about now and now it's just like and now I'm mostly thinking about the implementation detail because I don't I haven't done this before or maybe I've done it before but I've done it like decades ago like maybe the last time I've done this technique was ten plus years ago I'm not even exaggerating and that time I didn't do it in Python so the so here what you're seeing is me trying to figure out from scratch how do i am from implement is what is the right approach how do I get this in a cool fast way and this is also what practice would get you is that you yeah so basically here I was just thinking about the techniques and I was like okay well yeah because I haven't done it in Python before I was like okay I don't know the right way to do it so that's just you know this is something that as I was saying if you have practiced and you have know how to do it and on the other problems I practice similar things so tubes to get to speed that you see and of course if you just check out this problem there's a link to the entire contest below and I was just like okay that's just do everything in the hash table right oh yeah but basically some of this is because I have been familiar with this part of the pipeline so I was trying to think how do I do basically you said you like a two-dimensional array but with hash two-dimensional array but with hash two-dimensional array but with hash tables way so I just wasn't sure about the syntax and that's also what's something that if you practice if you done it before you know how to do without like needing to want to see if it compiles but yeah now I was just basically okay let's go through creating well that's not like from what we said I'm trying to start from first principles of okay well one distance away of one ancestor away is just a parent right and that's what I am that's what I put here drivers as you can see you are going a little bit and yeah I guess I haven't done this in like a decade so I'm just trying to think about what's the best way to implement this and you could see that I'm typing very slowly okay yeah and for this problem I wasn't sure how far up you may need to go Wow so I think I definitely did not implement this looking now I didn't implement this in the most code efficient way in terms of you know just practicing it basically and it turned out to be a little bit of a dynamic programming time I said I did it Ben it's my basic dynamic programming I guess but basically the idea is that you know for each node what is to distance away well it is one distant away and then that ancestor that enters one's distance away so that's the to distance away how do you get four distance away well it's my grandparent my grandparents which is another way of saying is my to distance of ways to distance away and then kind of doing it that way that's how I construct a swimmer child construct the list constructor lookup and I don't know why just one instantly and again there the lack of familiarity means that I actually did have like my base case wasn't quite correct so yeah if I could have just changed the default dictionary to be on this bit maybe that should be okay hmm but yeah now I do want to do one time issue ever so again because I have not done this I am enough for me event and some of the syntax is a little bit different I wasn't sure what is the part that is wrong and that's why I had to one the code just to see for myself whether my syntax is kind of make sense that's where practice will get you I know that I talk a lot about practice and I mean it earnestly that you know do you want to be fast if you want to be good do you want to bathe yourself tease a lot of over it is just practice and of course you have to learn the fundamentals so that you know what you're learning it's not just like you know typing but you know with that said if you learn the fundamentals in a good way given without practice where did you see me doing this and you are I am try going a little bit to be honest but you know but I'm able to solve the problem right maybe I'm not as fast as two people could sit in like three five minutes three to five minutes but you know like I'm not know it's not a what's my code item and like it's not impossible for me so I'm happy about that so even though this one I didn't do super well on this problem can come point I didn't make a silly mistake that I'm you know that I think I was just a little bit careless about I think I've done about it yeah we'll talk about it when it comes up and yeah now I'm just putting out for debugging I was like oh my I'm still a lot of zeros so that means that like I said I shoved this change the default value to be negative one I think that's what I should have done but it was just like weird stuff this way and I spent way too much time T bunking this but some of that is you know the learning process and me just thinking about it because if you look you watch me now and if you're still watching instead of fast 4 into an explanation you know everything I do here ok maybe not next time maybe I still make the same mistake next time with respect to implementation but you know eventually I will learn it I'm excited about that I'm happy about that and you know what you see now and what I'm printing discovery of how to go about this problem because I really don't know how to self or don't know but I don't I have not implement this before he's not in ten years ten plus years so it is definitely something that I'm happy and proud that just with an idea or binary numbers that I could solve this problem and it also beats just like solving dynamic programming prompts the entire time as it seems like that's all the thing is recently yeah and that's pretty much it for the pre-processing pretty much it for the pre-processing pretty much it for the pre-processing now we have to get to ancestor I was like ok that looked reasonably good enough for me to move on I don't know if it's right but it's enough for me to move on and I think some of why I did get of wrong answers because of my unfamiliar with this algorithm and how to push it in a way that because I was worrying about space I was worrying about time so those were the two things down my the top of my head and when you practice these things you get more confident about certain constraints and stuff like that in terms of complexity and it should be good enough I was worried about space a little bit as well I think it looking back I shouldn't have because then I could have just handled the edge case in a more cleaner way if I had just said that I got the idea behind the gate cave ancestor the query is basically just take the biggest power to remove it and then keep going and you know basically for example and I explained this later on but you have to say 15 your tech aid which is the biggest power to that is less than 15 and you keep that's what I would essentially do and then you just call 'roof you know that number of notes 'roof you know that number of notes 'roof you know that number of notes ahead and because you are and most gonna make log K of these jumps I want to lock a time cool yeah I went into some hours I forgot a base case which is like yeah so this looks good I was like okay what should I test for I really should have tested for one more case besides submit but again I was really worried about timing out more than anything thought it'll be fast enough a long time and I didn't actually get a wrong answer so I was like huh okay I made a critical matter of mistake here because I cook them more details it didn't tell me any more details what a ripoff and the problem now is that uh I did copy and paste that test case I did copy the test case but I don't know what's wrong about it because I didn't get to compare so I had to take some time to manually create the answer key for this one which was a race of a couple of minutes may yet but the short answer is that I did not do season off by something because I didn't go all the way so at it gets stuck on certain notes because I just keep on recursing on those instead of double-checking that if those instead of double-checking that if those instead of double-checking that if note is negative one because of how I did default dictionary if it goes to negative one it goes back to zero because the default Y is zero that the really stupid thing that I got no I should have just convert the default values negative one and that would have been okay but yeah I just add an if statement and that fixes it yeah that's all I have with this problem it's uh like I said it's the first time I've seen this given do I have played with around like I know enough about how to do this so I was able to do it from scratch and never seen this never practices so I feel really happy that I was able to sit solve this my contest ranking or rating will suffer but that's okay the first time you do anything it's gonna be hard to do it really quickly but yeah that's all I have I'd hang out of Giada Larry and you know I hope you had a good contest okay I mean not bad for something that I honestly created by mice - for um so the honestly created by mice - for um so the honestly created by mice - for um so the way that I did it I don't know how other people did it because people did it really fast almost like people know how to do it already I didn't I am proud of myself even though I took about 20 minutes to solve this problem I actually knew how I wanted to do this immediately but I don't know how to implement it so maybe is that maybe it's nonfarm maybe people have been practicing I'm not going to make excuses but I'm trying to understand the problem in a way that without seeing how other people did it I'm just amazed because this is but some of that may be just that I this is the first time I've seen it and you know you could have to sometimes you have to fit you know cell forms that you haven't seen before and that's okay and that's where you know you hope your knowledge and your practice carries through and your techniques and your and what you've learned where from here um so the first thing I well I think there was just a lot of reading I wasn't sure what it meant and then after that I looked at constraints is such that okay if you have the edge case or the big long case would be like you Centrelink list where you have one point or 0.21 or get away well one point two or 0.21 or get away well one point two or 0.21 or get away well one point two zero two pointing to one so forth so you have a huge linked list and if you do something naive you that maybe easily be n square so what I did was I have I need to do this immediately in terms of algorithm but implementation definitely is something that people need to practice on especially on the language that they may not have done it on and from here looking at the end which is 5 times 10 to the fourth I knew immediately that I needed something log n decide where that Q log ends up because if you times Q times n I mean in this case n is you go to Q so it's easy to confuse them but yeah if you do something that q times n well that's gonna be ready to regulate it's like 25 times 10 to the 8th and that's way too big so we need to get something that you know on each query is at most log n and of course we cannot do it and square processing either otherwise you just do a brute force and square processing and then for each one you know store all the possibilities which is n square its xn squared times X n square space which is both of which I don't we don't have so what I did in instead is I mean this looks a little bit weird and it is the first time I've written this so I am maybe later we'll try to figure out how to practice this but basically the thing that I was thinking is well like I said we need log n right and here we can do n log n so what is the way to do n log N well way to do n log n for me it was just to break it down so that and stuff you know so the naive way would be like okay for each node let stores parent it's grandpa heaven its third ancestor is for fences and so forth so what I did instead was I was thinking about okay so the way to do it to save space and time is to store every power of two instead so this is I forget what the name for this so sorry if I maybe I'll leave in the comments or you know even comment but basically we represent or the distance from so it's you know for each node you store the distance that's one away two away for away five away oh sorry for away eight away 16:08 dirty to arrange away eight away 16:08 dirty to arrange away eight away 16:08 dirty to arrange so four powers of two's way so because it's powers of two you know that you're gonna get log n of them where n is at most in this case it's n which is the size of the input so that's how I saw create this thing it turned out that if you thought about it that way it becomes a little bit of dynamic programming I mean that's the way that I have it kind of win and I actually didn't think about this as I was writing it but it becomes dining programming because you know if now how do I get you know let's say I have a given node and I want to get to the fourth ancestor well the fourth ancestor is just my second my grandpa my grandparent which is my second ancestor and my second ancestors second ancestor away so in a way you add them together so and how do you get and then similarly to get the eighth ancestor that's just your fourth ancestors fourth ancestor right so that's how I did this loop and just change your way to kind of construct that and then the lookup is just the reverse of that where I think the biggest power of two and then I think the biggest power of two - so think the biggest power of two - so think the biggest power of two - so basically if like let's say I've given him 50 random number like 15 well 15 the biggest part of - that goat that's under biggest part of - that goat that's under biggest part of - that goat that's under 15 is eight right so then that means we go eight and then we go seven and then also we go eight then we go for then we go - then we go one two add up to 15 and go - then we go one two add up to 15 and go - then we go one two add up to 15 and that's basically what this code does and you could prove that it is log n time because do you divide it by two effectively and every step right so a lot K that is in this case so what is the complexity of this algorithm now that we have this album well the pre-processing is going to be n well the pre-processing is going to be n well the pre-processing is going to be n log n because you have you're given and numbers and this one set at most log n times because every time you're doubling right so it's gonna double your distance get case ancestor this is we get Q number of careers of them so this one's in total 2 times log K times for the queries and in space this well we didn't have to do this because of this and if you didn't do recursively then this is all one space but I did recursively so you could have to count the stack space which is like a and here just for the cache it is n log n because you know you have n of these first index and you have log n of the second index | Kth Ancestor of a Tree Node | rank-teams-by-votes | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root node.
Implement the `TreeAncestor` class:
* `TreeAncestor(int n, int[] parent)` Initializes the object with the number of nodes in the tree and the parent array.
* `int getKthAncestor(int node, int k)` return the `kth` ancestor of the given node `node`. If there is no such ancestor, return `-1`.
**Example 1:**
**Input**
\[ "TreeAncestor ", "getKthAncestor ", "getKthAncestor ", "getKthAncestor "\]
\[\[7, \[-1, 0, 0, 1, 1, 2, 2\]\], \[3, 1\], \[5, 2\], \[6, 3\]\]
**Output**
\[null, 1, 0, -1\]
**Explanation**
TreeAncestor treeAncestor = new TreeAncestor(7, \[-1, 0, 0, 1, 1, 2, 2\]);
treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3
treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5
treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor
**Constraints:**
* `1 <= k <= n <= 5 * 104`
* `parent.length == n`
* `parent[0] == -1`
* `0 <= parent[i] < n` for all `0 < i < n`
* `0 <= node < n`
* There will be at most `5 * 104` queries. | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. | Array,Hash Table,String,Sorting,Counting | Medium | 947 |
814 | hello everyone and welcome back to another video so today we're going to be solving the lead code question binary tree pruning all right so in this question we're going to be given the root of a binary tree and the goal is to return the same tree where every subtree of the given tree not containing a one has been removed a subtree of a node is node plus every node that is a descendant of node okay so in simple words all this is saying is that if there is a subtree which does not contain the value one we get to remove it okay so let's take a quick example so over here we have one zero one okay so let's just look at the small sub trigger so let's just look at zero one right so this part over here so this over here even if there's a zero it's child it has one in its subtree right so then we leave it as it is but on the other hand if you look at the left of zero it has a zero and there's no one further down right it's subtree does not have any ones so in that case we get rid of it or in other words we prune it and prune pruning basically means cutting or trimming something right okay so in this case we get rid of this and what we end up with is one zero one um as shown over here okay so let's just take a look at another example so at example two over here we have this and this subtree over here has all zero so this gets uh rid of and we also get rid of this over here okay so now we're gonna see how can we actually do this so the question itself okay so doing this that's actually not too hard but let's just look at the same example okay so we have this uh tree over here and the goal is to get rid of all of the subtrees which do not contain a one so one approach we can take to this is a divide and conquer approach so let's just okay so example words let's say we find a zero right so let's say over here we've got a zero now the next task that we need to do is we need to check if there is a one in any of its sub trees right so we can traverse through this on both directions and check if there's a one and if there is a one we could leave it right so that's one approach we can take to that but that might get a little bit complicated so for example in something like this uh one of them stays while the other doesn't so an easier way to look at it is instead of looking from a higher value over here we go all the way to the bottom right so let's try to go to the most bottom level that we can so it would be something over here for example so over here what we want to do is you want to check if this as it is needs to get removed or pruned and in this case it would because this over here is a leaf and it does not have any children and it has a value of one okay so let's just write those conditions okay so sorry if it and it does not have a value of one okay so if it has a value of zero if it has no children then in that case we're actually going to get rid of it okay so we get rid of this over here since it has no children and it does not have a value of one now the same way over here this over here has a value of zero and it does not have a left child and it does not have a red child and to be more specific it does have left and right children but they both have values of null so we just consider that it does not have any left or right children so this also needs to get pruned okay perfect so how do we actually say that we're getting rid of something so one way that we can do this which is pretty simple is we're going to change this value to null and this actually helps us as we go for further above so let me show you what i mean by that so since we need to prune this over here and this as well we're going to change its values from zero to null okay so in that case now we go up to its root over here and check if we need to prune this as well and now the condition to do that is going to be the exact same as what we did so first we checked if it's not equal to one so this over here is zero so that's one condition and then we also need to check if it has no children now since we changed its children's values to null we can do the same thing so left so the left child has a value if not uh null and the right child also has a value of null so in that case we can get to prune this as well so we do the same step and we make this to null okay so now we move on and we don't go to one itself right now so we go to the right subtree so this part over here and we go to the bottom most value there so we go over here okay so add zero over here uh what we're going to have we need to check if we need to prune this and it's the same check it's equal to zero it has no children so this becomes null okay so over here we have a value of one right so that means that we do not prune it and even though it doesn't have children it is a value of one so this stays as it is so now we go to the root over here and over here we have a value of one and uh the other condition is that it has to have no children but it does have a child the right child of one okay so now finally we go to our head sorry of our root note and over here we do the same check so this is not equal to zero so that's one condition and it does have a right child of one even though it's left child is not okay so in this case this is what we get rid of and our final output is going to be this okay so we actually understood so we were basically going to the lowest level and working ourselves up or working up from there and going to a higher level and based on that we're removing our pruning nodes but how exactly are we traversing through this so the traversal that we're using is something called a post order traversal okay so let me just write it down post order and the way it works is you can think of it as you go to the left subtree then you go to the right subtree and then you go to the root okay and this is exactly what we're doing over here so a quick example so you start off at the root then you go to its left until you reach the ending so you go to the left over here then it's left over here and then when you go to its left nothing exists so you stop over there okay so at this point we're currently uh so we went to its left and it's empty then we go to its right so its right is also empty so then we include its root okay so then currently we include the root so let's just call it a okay now that we had its root and we also already visited left and right children we need to go to the right of its root okay so its root over here is this and we go to its right subtree so in its right subtree so we're currently over here but before we actually add this value we check its left subtree which is empty and we check its right sub 3 which is also empty so then we add the root itself so let's just call it b okay and then now we've looked at this roots left subtree and we've also looked at its right subtree so now we add this node itself and let's just call that c okay so the same way right so we don't actually add the root right now right because currently we visited the left sub tree of the root so now we need to visit the right subtree of this root over here okay oh sorry okay so the same thing applies we go to this root over here now we check if we can go to the left we can so we go here and before adding this left is empty right is empty so then sorry so then we add the root itself let's call it d okay and now finally we go to the root again before adding that we have to visit its right subtree so over here we go and its left is empty right is empty so we go to and add the root itself so let's call that e and finally since we've got the left subtree of this root and the right subtree of this root we can add the root itself which let's call that f okay and finally over here at the root we've got the we've accounted for the left subtree and we've accounted for the right subtree so now all we need to do is we account for the root itself and uh let's just call it one so this is going to be a post-order traversal and this is post-order traversal and this is post-order traversal and this is the order that we're going to follow so in simple words we're going to do a post-order traversal we're going to do a post-order traversal we're going to do a post-order traversal and at each node we're going to check whether or not we have to prune it okay so if we have to prune a and we have to prune b and in that and if c is also has a value of zero then that means c gets pruned as well but if c over here had a value of one even though it doesn't have any children it does not get pruned okay so this is the order that we're working up with and now we'll just see how this looks like in code okay so let's first start off by actually having our recursive calls okay so first remember uh we're using post order traversal so we do left right and then root okay so first we're gonna go to root dot left and we're going to call this function on itself recursively so it's called prove tree so self dot pre-tree and the root tree so self dot pre-tree and the root tree so self dot pre-tree and the root in this case is going to be root dot left okay now we do the same thing but for root dot right okay so we go to the right of child and we call the function on the right child again okay so we have this okay now in the beginning what happens is we go to the left most note so we go to the left again and left again so at this point we actually end up hitting no but what happens when we hit no we don't actually do anything in that case we're going to return none so that's what we need to implement first so if we do not have a value right so if not root or in other words the root is equal to none then in that case we return now okay so that's the first condition and we're gonna do that in the beginning here okay because uh if we go further down over here and none dot left is not going to exist right so yeah okay so we have this and now at the ending that means that we've got to a root okay and over here we have a simple check and we're going to check for these conditions over here so if root is equal to zero and it has no children then in that case we're going to prune it okay so let's do the check so if root dot value is equal to zero and it does not have a right child so and not root dot right and same way we can do and not root dot left so now that we have this condition that means that we need to prune this value so what we're going to do is we'll return a value of null so if you're a little bit confused of why we're returning law the reason for that is we're giving the value so root.left for we're giving the value so root.left for we're giving the value so root.left for example we're giving it a value of 9. okay so earlier it had a value of 0 over here but now it's going to have a value of 9. okay so we return none over here but if this is not the case then that means that whatever root we're on is either a value of 1 or it has a value of zero but one of its child's uh its children does have a value of one so in that case we need to keep it and we do not prune it so we're going to return the root itself so let's submit this okay so quick mistake um i forgot to okay spelled it incorrectly so let's submit it again okay and as you can see our submission was accepted so thanks a lot for watching guys and hopefully this video did help you thank you | Binary Tree Pruning | smallest-rotation-with-highest-score | Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_.
A subtree of a node `node` is `node` plus every node that is a descendant of `node`.
**Example 1:**
**Input:** root = \[1,null,0,0,1\]
**Output:** \[1,null,0,null,1\]
**Explanation:**
Only the red nodes satisfy the property "every subtree not containing a 1 ".
The diagram on the right represents the answer.
**Example 2:**
**Input:** root = \[1,0,1,0,0,0,1\]
**Output:** \[1,null,1,null,1\]
**Example 3:**
**Input:** root = \[1,1,0,1,1,0,1,0\]
**Output:** \[1,1,0,1,1,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 200]`.
* `Node.val` is either `0` or `1`. | null | Array,Prefix Sum | Hard | null |
1 | so hello everyone i am straight i am a software development engineer so we are starting with this lead code premium top interview problem series we will be discussing each and every problem which are mentioned on the lead code top interviews and also this will help you to crack your next coding interview in the top notch product based company so let's start with the first problem so the first question belongs to the easy to medium category that is twosome it's a very classical and a very famous problem so let's look at the problem statement oh i'll just zoom in my screen a bit yeah so the problem says that we are given a group of integers an area of integers and a target we have to return the indices of the two numbers such that they pair up to a target so let's take this example and try to visualize what is the problem saying yeah okay so let's say we have been given two three five and seven uh this is our array arr that is given to us and we have been given a target that is equal to 9 let's say and we need to find two numbers such that the sum of x plus y is equal to target so we need to return the indices of this number so the brute force approach will be real firstly we will take up a number and look for the remaining amount this y in the whole array but this approach will take o n square time so we try to optimize that further so we can do it using hash map and two pointers method so in this video we will look at this approach so it's a very intuitive and a very nice approach uh that we can use so let's start with the two pointer method so we have been given this array and this is the target so the target is nice so what we can observe that this array is sorted so if it is sorted uh we can directly use it if it's not sorted we'll just apply the sort function to the array cool and the two pointer method is like we use two pointers i and j which are pointed towards the start and the ending indexes and we try to find pairs by adding both of them means in the first iteration we'll look for seven plus two sum and we'll check that if it is equal to the target or not so if it is equal we'll return true and we'll store the indices and we'll give it give us the answer and if it's not the case then if this sum is less than then we know that we have to move we have to add some more value so we move our left pointer towards the right side and if we have certain value let's say if the target was somewhat like 16 then we would have moved this pointer towards this side cool or let's say it will we have any value which is constituting of some certain target that is lesser than the sum is coming less than the target so we are we will just move this pointer towards the left side so let's try to code it down and it will give you a more clearer understanding of what the problem is saying so this is the array numbers is given to us and let's dig let's make a pair vector cool in which we'll store all the information required so this will be a pair in hint yeah and we'll just insert all the elements inside it's numbster size yeah i plus we'll just we do v dot pushback and nums comma pi we are storing the indices and the value with the help of this group cool now we are as i discussed we need to sort it so it will be sorted now v dot end this is done now we declare two pointers that is i and j as we discussed this will be minus one cool and we have declared two indexes that will store the indices for us idx 2 is equal to 0 cool now let's loop over the statement this is less than j and we'll check for that if this dot first plus v of j of first is equal to target then what we'll do we'll this is the thing that we were looking for we will just store our in answer f of i dot second and we'll just do it for idx2 and this will be j cool so this will be the answer and we'll just break out of the loop so if it is not the case what we'll do we'll just shift our pointers towards right and left respectively so let's say this is less than target so we'll just do an i plus to grab greater value and here we will do a j minus and finally we will return idx 1 comma idx 2 so that's it so sorting will take log n time complexity and n log n and this will also take so the overall type this will take a big o of n so the overall time complexity will be 50 will be big o of n log n ah the space complexity will be um yeah so we will run this one this will run fine yeah it's accepted so this was the implementation of this problem hope you have understood it make sure you submit it | Two Sum | two-sum | Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity? | A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search? | Array,Hash Table | Easy | 15,18,167,170,560,653,1083,1798,1830,2116,2133,2320 |
1,401 | Everyone welcome to our episode of Late today which is our problem date is a very interesting problem a little bit based on mathematics geometry and I hope you enjoy it let's quickly jump to the problem so what is the problem status is it's a circle and Rectangle Overlapping Lead Code 14 Problem What does the circle represent s radius x center and a center okay so we have a circle this is n y2 So if I talk like this, on access online rectangle something like this okay this is the x1 y1 coordinator this is the point and this is the x2 y2 coordinator this is the point okay return true circle in rectangle and overlapped edgewise return water in other words check If there is this other point This is the origin zero okay here is a rectangle right here I have a rectangle right here this is x1 y1 this is I am writing a center No, this is not an example, it could have been like this that here is a rectangle like this is original, here is a circle like this, okay here I have zero, this is some x2 y2 but if it was overlapping then just tell me this. Is there any point which is common among these, if it is then just return true, okay, now how will we solve this, if I somehow find out which is my nearest point from this circle, okay, this rectangle. Okay, if I have this circle and this rectangle, which is the nearest point from this circle to the rectangle, then obviously this point will be this one. Okay, now I have found out that whatever x2 is, y2 will not always be there. Because this circle is here from the index, I have some other point, if it was here then it would not be necessary to tell the story. If this point was there then the nearest point can always be made from this and from the center which is the nearest point and what can I do after that? Calculate distance: I will Calculate distance: I will Calculate distance: I will calculate the distance from the center point to Neeraj point and after that I just need you to check whether I am ready and equal, which is my distance, then you think and see that if this is my distance, which if I give this distance. If I want to say, this is my distance given, if it will be smaller than the radius then it will be the date min's story na story it is over line, if right now like my distance is greater than the radius, it is bigger than the radius then this is happening, you are not lining up, not overlapping. If my distance had been less, if some such scene had happened, mother, take this rectangle, I am calculating the SSC distance, this is the distance I have calculated, the nerist point is fine and then it is ready, then here you will see that the distance date is on the top left of the minute. There is simple logic, okay, so if my distance is given and equal tu radius or I write it in reverse, given radius is greater and equal tu distance is like common point of date mains and I need you return through this distance so Let me reset that off this and just remove dump okay no now you eat that can I calculate x2 how can I calculate y2 first of all al just right point I calculate in which and in which is my center and which is my Can do or to the right of this okay can like here also can like okay in this point so if I take this mother okay then if you my x2 okay if I x you sorry x2 and x in the center which Bhi minimum aayega agar minimum mera maa lo a center a raha hai date min’s he is liking me on this side, he is date min’s he is liking me on this side, he is date min’s he is liking me on this side, he is liking me on the left. If minimum my ex you are a date man’s ki he my ex you are a date man’s ki he my ex you are a date man’s ki he is liking me on this side. You are thinking logically. Look, x2 is this and here x is the intersection, so my coordinate system is like this, here it is zero, 1 2 3 4 5, so x2, if my le is And if x2 minimum will come You find which is the de nerist point now my max x2 is here so basically the logic what is divided is max of Okay, when I found my X, basically you will see what do you mean by nerist Texas, this point, if I project the I can do nearest I was doing gym that I am fine, this is the point when this distance will be big, can I calculate this distance by subtracting it, that is, the nearest There was a center what I mean by date in this nerist If we are doing mines, then I got this distance. Similarly, out of all this, the nerist was white. Okay, here I got this nerist Now I have this second distance, what is the Pythagorean theorem, from this let I am taking From I'm taking this to the nearest distance and giving this equal you nd² Let's just resume for now I just took out this egg square Okay take the root inside or don't take If you take HD then you You can compare the direct radius. If you are taking the root inside, then I am saying this because you have to apply additional formula to find the square root. You do not need to do that when this much is in the format of nd². So you compare it directly with the radius square because this is what it does if I say let's say I am 4 = 4 then it will be equal to 4 squared, 4 = 4 then it will be equal to 4 squared, 4 = 4 then it will be equal to 4 squared, okay or so I say you give this 4 then 2 The square will always have to be taken from the force square, in this way nd² whatever comes, if it is given, then it will also have to be taken from the square of the radius, so always you have to put power bus on both the sides, then either you HD Compare nd² with r² or compare nd² with r², then the only thing you have to do here is when this distance of distance Okay, then you understand what did you do first, okay what did I do first, nearest tax to me is this Okay taxi will give me this okay aa in the difference of the center of the circle then the nearest one will give me this when this is like my reference if here then nerist tax will give me this okay and nerist a will give me this point okay so when I have this distance If it is required then what can I do, I will subtract this from the total distance, then I will subtract this from the distance, okay then also apply this logic bill x1 y1 if it is here then what is this point is x1 y2 Right So you need you just find the denier distance of this point so its corresponding if you have So you need you just have this I apply it a little bit, it bill give you match more butter understanding okay so let's talk about the application if the application it very match simple let's say nerist okay of the square if you take the root inside of it then you remove the square You can just compared tu Compare tu radius but you have to go to the monastery to do the square root of function tomorrow, this is why the scene is dependent on external library Na le ke just compare drop let me submit this So this is the implementation was easy but the mathematics behind it is the coordinates system of date you need to understand date this you can implement easily so thank you so match and back with Andar Episode | Circle and Rectangle Overlapping | number-of-burgers-with-no-waste-of-ingredients | You are given a circle represented as `(radius, xCenter, yCenter)` and an axis-aligned rectangle represented as `(x1, y1, x2, y2)`, where `(x1, y1)` are the coordinates of the bottom-left corner, and `(x2, y2)` are the coordinates of the top-right corner of the rectangle.
Return `true` _if the circle and rectangle are overlapped otherwise return_ `false`. In other words, check if there is **any** point `(xi, yi)` that belongs to the circle and the rectangle at the same time.
**Example 1:**
**Input:** radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1
**Output:** true
**Explanation:** Circle and rectangle share the point (1,0).
**Example 2:**
**Input:** radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1
**Output:** false
**Example 3:**
**Input:** radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1
**Output:** true
**Constraints:**
* `1 <= radius <= 2000`
* `-104 <= xCenter, yCenter <= 104`
* `-104 <= x1 < x2 <= 104`
* `-104 <= y1 < y2 <= 104` | Can we have an answer if the number of tomatoes is odd ? If we have answer will be there multiple answers or just one answer ? Let us define number of jumbo burgers as X and number of small burgers as Y
We have to find an x and y in this equation 1. 4X + 2Y = tomato 2. X + Y = cheese | Math | Medium | null |
1,491 | welcome to this video now we're going to solve a coding interview problem average salary excluding the minimum and maximum salary here's the problem statement given an array of unique integers salary where salary i is the salary of employee i return the average salary of employees excluding the minimum and maximum salary if you're given this array as input then we have to return to five zero by excluding maximum this is maximum and this is minimum okay if you are given this particular array here we have maximum 9000 minimum 1000 if we exclude this 2 salary then we'll have average of 4750 now how we can solve this problem let's suppose that we're given this array first we're going to find the maximum and minimum the maximum here 4 000 and minimum we found 1000 okay then we're going to iterate through this array from left to right by adding all the element except maximum and minimum since we have unique items in our array okay in this case if we exclude four thousand and one thousand then we'll have three thousand and two thousand so three thousand plus two thousand divided by length minus 2 because we are ignoring the two value maximum and minimum will have this answer okay if we're given this particular array first what we're going to do we're going to find the maximum and minimum this is maximum and this is minimum then we're going to iterate through this array from left to right by adding all the element except maximum and minimum and we have here eight thousand two thousand three thousand and six thousand if we add all of them and if we divide them by the length minus two of this array then we'll have this answer okay and this is how we can solve this problem now let's see how my solution might look likes into the code first i'm going to declare a function average that takes nums array let's suppose that this is our given array then we're going to declare to variable mean cellar equals to max integer the maximum value we can store in an integer and maximum salary equals to mean integer the minimum value we can store in an integer then we're going to iterate through this array from left to right to find the minimum salary and the maximum salary at the end of this loop we'll have mean seller equals to 1000 and max seller equals to 9000 okay then we're going to declare a variable sum equals to zero now we're going to iterate through this array from left to right again to add all the value except minimum and maximum and here exactly what we're doing okay so at the end of this for loop we'll have the sum of this element and this element at the end we're going to divide the sum by length of our array minus 2 because we're skipping to value minimum and maximum and here we should have num psi not salary okay since we are passing this parameter to this function at the end it will return for this input 4750 this solution will takes big of 2 end time complexity and that's equivalent to big of int and the solution will takes constant space complexity all guys hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video | Average Salary Excluding the Minimum and Maximum Salary | number-of-times-binary-string-is-prefix-aligned | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Output:** 2500.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
**Example 2:**
**Input:** salary = \[1000,2000,3000\]
**Output:** 2000.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
**Constraints:**
* `3 <= salary.length <= 100`
* `1000 <= salary[i] <= 106`
* All the integers of `salary` are **unique**. | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. | Array | Medium | 319,672 |
236 | all right today i'm going to talk about this bit code problem 236 those common ancestor of a binary tree so you're given a binary tree and you want to find the lowest common answers of the two nodes that are also given to you p and q and the those found analysis is defined here is basically a note that has pnq as its ancestor and it should be the lowest possible known entry for example if you look at this tree here this is the same as this tree here so let's say this is level zero or one this is a level two level three level four right and you're looking for five and one which is five and one here so the lowest common ancestor would be three but for example if you had you were looking for six and two the lowest coin answer would be five although three is also an ancestor but it's not the lowest common ancestor similarly in this example uh so you're looking for five and four five is itself its own ancestor and also you have four somewhere underneath pi which makes five the lowest common ancestor here similarly so i tried to draw some example here to make it more clear so you're looking for five and one this is same as the example shown in the problem description what happens is that we first go and search the left subtree you can see here the left subtree and try to find either five or one and if we find one of them we somehow mark it we keep that in mind we hold that right and after that we go and check the right subtree and to see whether we can find the node or not for example in this case we go to the left subtree you find one find five and we go to the right sub three find one and then because the lowest common ancestor of these two would be three we return three as the results uh note that based on the problem description all the notes have unique values so you don't have repetition so there's just one five and also they're like they're defined as three notes they are not just values keep that in mind so in another example let's say you have six and two and both of them on the left subtree the way we're going to approach this is you start from the root and we're gonna do recursion as you're gonna see in the code you start from the roots we go to the left subtree here now our new root is basically five the root of the left subtree right and then you go to the left subtree of the new root which is sticks here you find six you mark this one you hold on to it and then you go to the right subtree of the current dude which is five you find two you hold on to it and then as a common ancestor of these two lowest common answers that you return five as a result note that three is also common ancestor but it's not the lowest one based on this level things that i mentioned earlier so this is the one this is level two so you wanna find the lowest level highest level in this case so that's why because five is level two you'd return this one as the lowest common ancestor the last example is similar to the second example in the description i guess oh no last example is somehow you have one of them in the left subtree and the other one on the right subtree and regardless of uh way where they are if the two nodes are in two sides of the roots then your lowest common ancestor is the root regardless of where they are located the way we are going to approach this problem is using recursion so personally i find recursion and when mostly when they're combined with trees one of the most difficult problems at least for me to handle so i guess make doing the practice a lot and try to understand the code in a way try to write it down on a piece of paper probably is going to be helpful for you so how we're going to solve this problem so for any recursion problem that we do if you want to solve a problem using recursion we need to come up with a benchmark or a bit like some base cases in which if you hit your you're gonna move back up right because in the recursion as you may remember if you're moving from top to bottom and when you hit the base case we move backward up until we get to the original place that we started from here for example you start from roots you go down either left or right subtree find the nodes we're interested and then we move backward up until we get to the root and then we decide what is the lowest common ancestor so in this case the root if we find uh either of the p or q it doesn't matter it should be both of them but if we get to a note that either is p or q we determine that note as one of the basically we hold on to network we keep that demand somehow if you start from the root and this doesn't get satisfied we move to the left or right subtrees let's say good has a left subtree we do something and if boot has a right subtree we do something else and then based on what is the output of these two we decide what's we're going to return as the lowest common ancestor before starting the recursion we need to define some variables i'm defining left and right as none because at the at first we don't know what they are but we're gonna update them if we get to find one of the nodes we're interested in p or q and here is what recursion comes into the play so you call the function again this time on the desktop three all right so you don't you start from the root you come down go to left stop3 and this calls the function again but this time root is your left subtree root basically in for example in this case you start from three but now you're at five and then if you find the node you're interested in for example in this case p is five so you five you find five here you return root which is five and then that's what gonna be the new value for your left so now left somehow holds on to the uh note 5 for you and since you find the left sub you find the uh p already now you go to the right subtree and you try to update uh right variable here again doing the exact same thing this time on the right subtree but you can't find anything because none of the nodes oh wait here uh q is on the right subtree so basically your right gets the value gets updated it's not anymore and it includes this node basically holds on to this node now your left points at five your right points at one what you're going to do you know the answer the lowest common answer is going to be root but how we're going to decide on this we say if we have posts or left or right stop three meaning post left and right are not none anymore both of them got updated somehow then root is the results but if uh one of them is none still right we return the other one let's say if uh left or right left has some value and right is still none then we turn left or if left is none and right is not none then we turn right so going back to the example we talked about earlier for example here so you start from three this doesn't do anything because p and q are not equal to root right they're not equal to three you go to the left subtree you define these two variables you go to the left subtree five now your new root is five you call this function again check this line again bam you get to five you return good basically now your left gets to have the basically this node saved into it now your left points at somehow points at five you're done here you go to right sub three now your root is what one you call this function again go again bam you got the q you return the root now both right and left got some values they are not none anymore because none of them is a is none of them is none then you return root which is three which is the correct answer similarly let me bring it up a little bit similarly for this example you start from three again you go to the left subtree because this line doesn't get passed you go to five now your new route is five you do your left uh basically your left recursion you get to six because you're calling the function again here now you have your uh loot is equal to p because you already found the p which is six now you turn left as a new value which uh basically holds on to six now you go to a root right keep that in mind it's not the root right of uh the root of the three it's the boot right up five you go here you find two your q is two good right is updated to a new value and both of them are having a new value right now that's why you return roots root here is five it's not three keep that in mind right now your left get now you go up because you got the benchmark you found your first comment answer selected you go up you get the left let left got updated already now you're at root again you do your right sub through your recursion now but you can't find anything right doesn't change is it's still not now this line doesn't do anything we get to here because one of them is not right is not here and left has some values and we turn left which is basically the file the five that we already found and it is the less common ancestor uh that's it seems complicated but if you understand the uh how the recursion work and how we traverse our trees it's gonna be it's not gonna be that difficult it's too difficult this is not an easy problem uh so i did check this myself so it should be fine right yeah so that's it please | Lowest Common Ancestor of a Binary Tree | lowest-common-ancestor-of-a-binary-tree | Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the tree. | null | Tree,Depth-First Search,Binary Tree | Medium | 235,1190,1354,1780,1790,1816,2217 |
229 | Hello everyone, today's question of ours is Majority Element 2. Recently we had done a question on Majority Element. Before this we had done a question on Majority Element. So in that we had to find only one element which increases n times. This question was the one which increases n times. Batu works more often than time, so we used this approach, okay, if you want to know this approach in depth, what we did, well, I will give a little overview, okay, but if you want to know in depth, then you can read the previous article. You can go to the video with geotic element in the video and see what logic we had applied. Okay, basically we did it, let me give you a little overview. Now okay, what we did in it was like we were traversing the array and in the array. While traversing, we found out how many times, like its count is three, first we kept one, in the element we first stored three and its count was one, after that we started our array from here, we reached here. What happened next, here we checked whether the same element is there or not, if the same element is there then we will increase its count, if there is a different element then we will reduce its count, okay if we reduce its count then it is different. If there was an element, then we reduced its count, that is, whatever element was in our element, now it is like if the count here becomes zero, as if its count was one earlier, it is fine, when we came to two, then we saw two and two. If they are not matching, then what does it mean that the chances of the three and the two are equal, that is, at this time both of them have equal possibility to become our majority element, so right now any one of the two We will not do anything, okay, after that we came to the next element, now we have three, what does it mean when our count becomes zero, after that all our previous elements are doing even number, okay, it means as many as one. The element has approximately the same importance as the other elements, only then our count becomes zero and the element whose count is left in the last place will be saved separately. The element whose count remains one or more than one is that element. Our maximum element will be that means it will be majority element, it will be doing the most number of times. Now we are going to apply the same concept in majority element two, like what we were doing inside it, earlier we were traversing the entire array, in this also we will traverse the entire array. And then what do we do after that, if the count is zero, then by making the count one, we put a 'i' in the element, the chances of put a 'i' in the element, the chances of put a 'i' in the element, the chances of its happening at the position where the number is present, like here we were 32, so when we were coming to three. So all the previous numbers were present, canceling each other out, but when we came to number three, we saw that this is an element which is working even after all the other numbers are null, so we adopted it. Majority element is accepted for now, we are doing like this, so what we did is count one and put that element in the element, if that count is not zero then we reduced the count, okay and if our element is that. If it is equal to nam jai, then we have added the count. Okay, this is the same approach. Now we will do the same thing for two elements, meaning this thing which is the if above, all the ifs of ours, all these elements are one element two. Count one, count two will work for both of these. Okay, now we write this first. First of all, just like we had defined element one and element two in it, we have defined element one and element two in the same way, we will define it in this. Now here we will write and is equal to, now we have nothing, keep it as minus and, it is okay now, but not here, our number is my 10 9 s, so we also keep it int maximum and keep it int minimum, okay. We kept int minimum, what did we do after that, we also have to store a second element, we have to write everything for two elements, like here we had defined only one and a count for one element, but now we have two elements. Well, first of all, we will define the count as two. We will keep the ant count equal to 0. In this, first because we have not yet inserted any element, we have inserted the first element in this, hence we have kept the count as one. In this, we have not yet added any element. If the element is not inserted then the count is kept at zero and int count two is also kept at zero, here we make the count one, it is ok int count two also count here our count will be CO Y A Y our count is ok count two we have We have defined the count, now what will we do after this, we have to return a vector, so for that also we will create a vector and answer, okay, an answer type answer, an answer name vector of inj type, we have declared it, okay, so we What we were doing in this loop, we were traversing this loop now, so what are we doing now? Ant aa e0 aa lesson numbers dot size i plus okay, all this we started from zero here because we We haven't even counted the first element yet, in that we had counted the first element, so we started from one, okay, so now we came inside it and we are like this, now what have we done that if then our count is count one, sorry count. If one is zero then what do we have to do? If the count is one zero then we have to put i of the current number in one and make the count also plus. Okay, we have to make the count one because once we add the element Apart from that, if this thing does not happen then else if then our if count one is not zero then okay then we will look at count two if is zero then in this also we were doing like this we had seen count zero. We checked in this, is the count to zero, if so, what do we have to do, we have to define our element two, we have to define the i of the names and along with it, we have to define the count two to plus and also on the base line. The count will not come, okay, count two has been made plus, after checking this, count two has been made plus. Now what else can we have, that element is this, which is element one and the moisture is equal to this. If we can, then L one, we put that our av is equal to two is equal to numbers i, so what we have to do is to increase our count one, is it okay, then next we will write elf, now we will write elf if then our at is equal to two. Equal to is Nam I Se then we have to increase our count to. Okay, so increase our count to. Okay, we have written the same thing. Now what will we do? If neither of these two is there then we will have an else. What will happen in that if neither that element is the same nor its count is zero, only then we reach to else, then what do we have to do, that is, if there is another similar random element, then we have to reduce count one to minus and count two. Okay, we have done this thing, after this now we have to make sure whether the elements we have here in this count one and count two are majority elements or not, meaning they are doing more than n bath time. Otherwise, we will keep an integer c1 and put it equal to 0 and we will keep a c2 and put that also equal to 0. Okay, we have put zero to both c2 c1 c2, now what we will do now, inside this we have Now we will traverse the array for int aa ect 0 aa len nums dut size i ps array we have searched if then if numbers of aa i equal to element one then what we have to do is make our sav plus if It's not like that, our names of I are equals to equal to le2, then what we have to do is to make c2 plus, okay right, we have to make c2 plus, now we have come out of the loop, we have made its bass c1. We also have a count, meaning element one also has a count, element two also has a count. Now if we apply the condition that if then s1 means the count of element one is greater than numbers dot size divided by 3, right? So answer dot will push back that element will be one and next if then c2 which is ours is bigger than numbers dot size divided by three then we will push back answer dot at is ok and in the last we will return our Answer: OK, now the only our Answer: OK, now the only our Answer: OK, now the only problem in this is that it can happen that we put the same element in both our element one and element two, when our count one becomes zero and it can happen that the element That element is already there in two and that element has come to us again and count one is zero, then by entering element two inside it means that by not increasing the count of count two, it can give value to count one, then it means we This also has to be checked. Here we will put one more condition. We also have to check whether L2 is not keeping its count. L2 is not equal to two names. We have to keep this in mind. We are fine and similarly here. Also, we have to keep in mind that after placing the end and end, it is not already keeping the count of our Nam Jai. If it is then we do not need to give it to element two. If element one is already keeping its count, then it is fine. Yes, now we run it once, okay, answer, we defined the answer above and we pushed back in the ANS below, okay, because we defined the answer here, now we run it is run now. Let's submit it and see, it has been submitted, okay, so I hope you all have understood this question and thank you everyone. | Majority Element II | majority-element-ii | Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times.
**Example 1:**
**Input:** nums = \[3,2,3\]
**Output:** \[3\]
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1,2\]
**Output:** \[1,2\]
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-109 <= nums[i] <= 109`
**Follow up:** Could you solve the problem in linear time and in `O(1)` space? | How many majority elements could it possibly have?
Do you have a better hint? Suggest it! | Array,Hash Table,Sorting,Counting | Medium | 169,1102 |
1,297 | hello so today continuing on contest 168 let's take a look at this problem called maximum number of occurrences of a substrate and so the problem says that we'll get a string s and we want to return the maximum number of occurrences of any substring under these two rows the first rule is that the number of unique characters in the substring must be less than or equal to max' letters be less than or equal to max' letters be less than or equal to max' letters the second rule is that the substring size must be between min size and max size so these are the tools that we have for the first example we have this string max Lawrence is 2 min sizes 3mx size is 4 and so if we look here if we take the substring of length 3 a B it occurs two times right and its unique characters are 2 and so it is less than or equal to max letters and it is in the it size is 3 so it occurs because so it's in the range 2 3 4 inclusive and the number of substring the number of such occurrences of it is 2 and so we returned that because if you look and try to find any other substring that occurs more than 2 that is there isn't any substring like that because well the only one that occurs like multiple times again is a B and a has one unique character so it doesn't conform to the first role a B has two unique characters but its size is less than three so it's not in the range so it doesn't conform to the second role so you get the idea we want the substring that occurs the most and follows these two rules essentially if you look at this example the shrink that has that it's aaaa three times and you could see here that they can overlap and maximum here the unique letters number of unique motors is just one and the mid-size is um is just one and the mid-size is um is just one and the mid-size is um is three right so the mid-size is three so that tells so the mid-size is three so that tells so the mid-size is three so that tells you that system size at three AAA has size three so it follows the rules so that's um that's good and you could take a look at the rest of the examples but essentially that's the idea and min size microsites are just from one to twenty six I will have only lowercase English letters and s can be relatively big so let's see how we can solve okay so how can we solve this problem so a couple of things that we can so with the rules that we have that the problem gives us is that so we want the number the maximum number of occurrence of sub-strings and the rules are the sub-strings and the rules are the sub-strings and the rules are the following right so we have the first one and the second one the first one is that number of unique characters should be less than or equal to max' letters and less than or equal to max' letters and less than or equal to max' letters and the second one is that length of the substring should be in the range inclusive of min sized and max size pretty much so these are the rules that we have now how can we approach this problem so the one thing we can think of is okay was just I just construct these strings was just these sub strings and basically just count the occurrences of each substring that is valid according to these rules and then takes that take the maximum so very straightforward approach and so to do that what we need is just well we need to construct these strings right this constructing them in with the first rule is kind of hard but with the second rule is pretty easy so what we can do is just in our approach here what we can do is just first we can just construct sub strings that are valid for the second roll right and then once we do that what we can do is construct all substrings right all of them which means including so this is very important here so including sub strings that overlap right strings that overlap what I mean by this is in the case in one of the examples where we had a and the substitute that we considered was this one and this one so you can see that they overlap so we need to try every starting a point and take only those that are valid with the range 2 which basically means take every start I and then just try I plus me in size write the word starting at I end and we're flying them in size and fry the one of length means size plus 1 starting at I and then the one with size means size plus 2 starting at I and tall the one starting at I and of length max size right so basically try all the valid ones according to roll to write and then once we do that what we after that what once we do that we can check at every step so basically check if substring that we just generated here is valid for the first roll right because if it is that means it's a candidate to be maximum number of occurrences of a substring right so basically that means if valid that means it's a candidate solution basically and so how can we keep track of the candidates so that we can get the maximum number of occurrences of a substring so to do that we can just keep a map right so just use a map here so basically use a map from word right or our from a substring since that's what we are exploring here from a substring to the number of its appearances right and so this map here will contain only the valid world only valid words right and basically once we do this it will contain only valid words we will have all the valid sub strings according to these two rules and their number of occurrences and so as the in the end you can just take the max right so in the end return the max the substring that occurred the most among the valid sub strings you can you will no notice here in this construction what we did is we add to the map only the words that advant that are valid according to these two rules right and so how can we do the construction the first step the construction how can we do that so we could just start right we could just start from every position right so we just do for I in the range of n right and then so we start from every position and then we try all the valid sub strings according to the second role right and so to do that we say for its ending position has to be in the range I plus me in size plus minus 1 right because if it starts from I then I gets counted when it reached mine size my I plus minus size minus 1 the length would be - size and here I plus my would be - size and here I plus my would be - size and here I plus my exercise right and since in Python range stops at the position before it would be max size minus 1 and that word would have size max size right except there is one caveat which is maybe I plasma exercise is more than the length of the string so we just need to add min year for this and n to make sure such that n is just the length of the string to make sure we don't go out of bounds right okay so now these are the here at this position we know that s I to J plus 1 is valid for rule 2 right because that's literally what the construction that we did its size we generated words that have size that is in the range mean size max size right inclusive okay so now what is this substring that we are dealing with here so the substring is this s from I to J right and so we do J plus 1 for Python so that it includes the character at position J and now we do the second step which is we check that the substring is valid for all 1 which means it's number of unique characters is less than or equal to max letters and so to do that we do if the to get the unique characters we just take the length of the set for the substring and we check that it's valid which means it's less than or equal to max letters right now if it is valid so this means this here means valid for role 1 so if it is what we said is we're going to use a map that keeps the number of occurrences of these substring because at this point it's valid for both roles so it's possible solution and so we need to have a map here that stores this so let's just call that map occurrences like this and let's initialize it to be collections in Python default dict so basically this is just so that it will be initialize it with the zeros so that we don't need to initialize it and here the races of the world substring increase it by one right and so we did that so that we can keep track of how many times that substring appeared and now at the end to get the maximum occurrence valid substring we can just return max of these occurrences values because the values would be the number of occurrences right and we are interested in the number of its occurrences so that's what this will get us and just to avoid the problem where occurs may be empty because we didn't find any valid word we just go into default to zero right in Python this would say if occurrence is empty just return zero basically and that's pretty much it so we just went through every position generated a word that is valid using it the second rule which means it's length is in the range that the problem asks us for and then we check if its length if the number of unique characters is less than or equal to max letters so that it's valid according to the first row and then we increase the number of its occurrences and at the end we just return the max okay so let's type this into elite code and see if it passes the test cases okay so I just type with the solution that we just did in the overview here so just constructing the word that are valid according to the first row which is the size and the range that we want and then checking that the number of unique characters is less than or equal to max letters if it is we count how much many times it occurred at the end we return the max and so let's run this and see okay so looks like it's good submit okay so the solution passes now in terms of like time complexity and space complexity this solution here we do all when and here we do the range back sighs - min sighs so if I take em to be mint - min sighs so if I take em to be mint - min sighs so if I take em to be mint max sighs - - min sighs and here we have max sighs - - min sighs and here we have max sighs - - min sighs and here we have our vent so the overall time complexity would be of an M right so overall we would have of an end time and then in terms of space complexity the only expensive space thing we are using here is this map which contains maybe all the sub strings which can go into to be oven squared space right and so that's this space and time complexity analysis I'm so another small optimization that we can do here is we actually don't we actually can avoid doing this max that will do a pass over all the values of the appearances by just having some result valuable here that winch lies to zero and then at this position here when we increment we could just say okay res is going to be max of res and the appearances of this word that we just substitute that we just increased right and then at the end we just return result so that's one way we can optimize this small way we can optimize it okay so that passes now another way we can think about this is to optimize this even further to a no vendor solution is that well if some if we find a word that is of size mean size right that is valid according to the tools that we have here or actually if we find a word a substring that has size let's say anything bigger than a mean size right that is valid right which means that it has unique characters or less than or equal to max' letters so that than or equal to max' letters so that than or equal to max' letters so that means that substring right is valid so basically let's say we find if we find a substring of size X let's say that is bigger than equal to minus size that is valid that means that a sub that a substring of X right is also valid right substring of SX with like min size right mean size is also valid right because well is it's valid according to the second rule because it says is min size and it is valid according to the first role because if X the unique characters of X are less than or equal to max letters that means that a substation of X also must call this substring of sy substring Y of X that means also that the unique characters of Y are less than or equal to max letters right by definition because well it's parent has less than or equal to max' earners and less than or equal to max' earners and less than or equal to max' earners and since why it's smaller it also has less than or equal to max' letters so that than or equal to max' letters so that than or equal to max' letters so that means that this one here is also valid and this one certainly occurs either the same amount of times or maybe it occurs more because maybe X is just YY right it's just like in this format right here right and so whenever you have one that is bigger than there it sizes bigger than means aisles that means we can just take a substring of it varies of science mean size and which it will give us the maximum number of occurrences so basically that means we don't need to check my size and we don't need to check anything bigger than min size we can just check min size and that would be enough it will always gives us the max occurs and so to do that then we can just not do this not go through every possible size between min size and max size and instead we can just take I to be any starting point that can give us a size min size right and so that would be min size plus one right like this and now our sub string instead of J it would be just I plus min size since we know that if there is a solution that is that has the maximum occurrences it must have sighs at least min size so we can just do that this way and now just check if it fell in fits valid and that would be enough right and so and that's pretty much it and we can just return the result and we now we just did all of n instead so we don't need to check max size at all or anything in bigger than min size so let's submit this one and see so you can see it's um it's it passes and it's a lot faster and in terms of time complexity this one is actually just open time right and in terms of space it's still like open space but it's a lot faster and this is just by noticing that we actually only need to check the sub strings of size mean size right yeah so that's it for this problem thanks for watching and see you next time bye | Maximum Number of Occurrences of a Substring | maximum-number-of-balloons | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4
**Output:** 2
**Explanation:** Substring "aab " has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
**Example 2:**
**Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3
**Output:** 2
**Explanation:** Substring "aaa " occur 2 times in the string. It can overlap.
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= maxLetters <= 26`
* `1 <= minSize <= maxSize <= min(26, s.length)`
* `s` consists of only lowercase English letters. | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". | Hash Table,String,Counting | Easy | null |
1,770 | so hello everyone welcome to my channel so in this video i will be explaining this problem maximum score from performing multiplication operations so you know this is a pretty easy problem from dynamic programming so i will in this video i will tell you how to identify dynamic pro programming inject problems in general and then how to how do we solve this problem okay so in this video first i will be discussing the problem then we will be developing our approach and then i will code it okay so the problem is basically saying that i have been given two arrays one is the num's array and one is the multipliers array so at each uh we have been given certain number of operations so these are the number of operations the size of multipliers so and in each operation you can choose either the first character or the last element of this array and then multiply it with the current operation multiplier so if it is your first operation you have to choose one character either from the start or the end and multiply it with -10 the end and multiply it with -10 the end and multiply it with -10 then in your second operation you have to multiply that any character from the start or the end with minus five and so on the size of this nums are it will keep on decreasing okay so one thing i want you to say is that to so identify a problem that it is a dynamic programming problem or not what you have to do is that first you have to identify that are there am i being given some number of choices and is there any optimization so if this is the combination that is choices plus optimization then you should think about dynamic programming okay so in this problem what are my choices are that i can choose either this the first element of the array or the last element of the array then again first one or the last one and what is the optimization part is that i have to choose these arrays uh these elements such that the output is maximum okay so i have to maximize this so this is the optimization so you know how to solve any dynamic programming problem is do that you should always write the recursive code and then memorize it okay so in this video i will be explaining i will be coding and explaining the code simultaneously so let's code it so just one second okay yes now it is fine one second okay so first of all i will be just writing into n is equal to norms dot size and end m is equal to multipliers dot size because like this and then what i will be doing that i will be making one integer actually two integers int l is equal to zero and r is equal to n minus one and int index is equal to 0 so what these mean that l will be the left side of the nums and r will be the right end of the nums and i will keep on increasing and decreasing in the subsequence recursive subsequent recursive calls and index will be the pointer so index will be the pointer to the multipliers array so it will keep on going ahead okay so these are the three uh parameters that i have made now i will make a recursive function okay return solve okay so and i will pass these parameters norms multipliers and l comma r comma index okay and now i will just write this recursive function hint solve i will just copy this thing ctrl c ctrl v comma into l comma into r comma in index okay fair enough so now what i have to do is what will be my base condition okay so my base condition will be basically when my number of operations are over okay so in the question it is given to me that the number of operations m is always going to be the less than the size of the nums array okay so my base condition is going to be suppose if my operations are over if index is okay just let me copy this ctrl c ctrl v okay so if index is greater than or equal to m then return zero so basically what this means is that if your number of operations are zero then you will have to return 0 okay now i have to take this multiplier so suppose let the current multiplier be x and let it be what multipliers index okay so this is going to be the current multiplier so to solve any dynamic programming problem the we have to write do the recursive part so any recursive part can be divided into two parts the first part is the base condition and the second part is the choices okay so you can by doing these two things you have to build the recursive any recursive function okay so what are my choices will be return maximum of what return maximum of either i can choose the left side nums l into x and then i will i can carry on with my uh further recursive calls so the my further if i choose the left one then my further recursive call will be nums multipliers and since i have chosen the left one my left index will increase and the right one will stay the same and index plus one index will always increase that is the basically the number of operations i am doing and then what i will do is that nums are into if i choose decide to choose the numbers r1 then i will do nums r into x plus solve what nums are just this will be basically same except for one thing that is you know nums l will be same in this case and in this case r minus one okay because the size of the index will size of the norms array will reduce okay since i have chosen the right one so you know this is pretty much it so that's the so that's how we write the recursive code so let's test this recursive code so this will certainly give me time limit exceeded okay just if i get tle okay so tla so this is a good sign because you know because since i am solving in what is the meaning of dynamic programming we have to reduce the sub problems that we are solving repeatedly okay so in this we are solving these problems repeatedly so i will to optimize my code i will make a what i will make a dp vect uh matrix so that will store the sub problems so how do we make a dp matrix so in this problem uh so to make any dp matrix you have to choose the number of parameters that are varying so in this problem see nums is not varying multipliers is not varying l is varying r is wearing an index is varying but you know r is not actually varying r is not independent r is kind of dependent on left end index so i don't have to make a 3d dp i will make a 2d dp because in reality only l and index are varying r is kind of dependent on index and l so i will make a 2d dp so let's make that 2d dp vector of vector and so you know what if you have written the recursive code then it's just a game of a snap like thanos to memoize it further so vector of vector and dp and now i will just assign this dp dot sign assign so since the number of operations can be around so i will just assign this dp as 1000 size or you know we can just write m plus 1 so the size of the number of multiple operations and vector of vector int what m plus 1 minus 1 so in this way i have initialized my dp with minus 1 at every place now what i will do is that i will store my sub problems so my sub problems will be what dp index comma l so since my the two parameters that are varying are only l and index you can choose r also it doesn't matter but then you have to face some problem assigning here so let's choose l as our second parameter so now in this way what i'm doing is that i'm storing the result of that sub problem in my dp matrix so now what i have to do is that the memoization part so i will check if dp index l is not equal to minus 1 that is basically i have already solved this sub problems then i will return dp of index l okay so that's it so you know let's check this out okay it is running pending it is finished it seems good now let's submit it is accepted so you know it is a pretty easy problem if you know how to solve dynamic programming problems you just have to take into consideration the base condition the choices that you have in your life okay you have to take the correct choices and then you after you write the recursive code the game is over you just have to see the parameters that are actually varying and then you have to memorize it so you guys if this problem is clear to you please consider subscribing the channel and i will making videos in english so you can subscribe the channel so thank you and have a nice day | Maximum Score from Performing Multiplication Operations | minimum-deletions-to-make-character-frequencies-unique | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of the array `nums`.
* Add `multipliers[i] * x` to your score.
* Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on.
* Remove `x` from `nums`.
Return _the **maximum** score after performing_ `m` _operations._
**Example 1:**
**Input:** nums = \[1,2,3\], multipliers = \[3,2,1\]
**Output:** 14
**Explanation:** An optimal solution is as follows:
- Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score.
- Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score.
- Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
**Example 2:**
**Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\]
**Output:** 102
**Explanation:** An optimal solution is as follows:
- Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score.
- Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score.
- Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score.
- Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score.
- Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score.
The total score is 50 + 15 - 9 + 4 + 42 = 102.
**Constraints:**
* `n == nums.length`
* `m == multipliers.length`
* `1 <= m <= 300`
* `m <= n <= 105`
* `-1000 <= nums[i], multipliers[i] <= 1000` | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before. | String,Greedy,Sorting | Medium | 1355,2212 |
494 | Hello guys welcome to the video this series target the pirates sub selection inter national symbols plus and minus to Left Side You Find The Number Of Two For The Example To Interest Received Notification 1962 Answers In The Answer Will Have To The Number Of The Thing You Want To Make A Call To The Giver - Plus Two Plus Minus One Two Subscribe To Take Another Example of Witwatersrand Support You Want to Make One Behavior Disagreement Example Goals Plus Minus 5.2 Options for Example This Plus and Minus Two Now Half Me Solution Send Its See You Half Toot Someone Time And Labor Plus Science Related Stuff Like This Is My Plus Science And Liquid Liner Subscribe 40 - Vegetables 40 - Vegetables 40 - Vegetables Are Basically Problems Tuesday Divided Into Two Subscribe Now To Make The Teachers Taking December - - - - Teachers Taking December - - - - Teachers Taking December - - - - Subscribe To quickly into two sectors and intuitively possible subset at subset one - most two is equal to subset at subset one - most two is equal to subset at subset one - most two is equal to three super in this subject and subject pinpoint the voice of the thing but you all network plus most two to a world without tight will be till protein probably this indicate White 518 This Party Will Have Two Equations For Redmi Y2 Just For Distribution Crush Play List Equations Of Its Something Interesting Video plz subscribe this All Elements Positive Villages With What Is The Target Plus Two Have So I Need To Find Promotion Subsidy To Science Subject Vitamin Target Plus Number Two How To Find Subject Code By Targeting This 3 Cm White Part Plus Price 8 2012 - Subset With Sampoorna - Subset With Sampoorna - Subset With Sampoorna That Nine Ten Problem Is Basically A Very Simple Problems In Which You Have To Just Find Subsidy Side Sampoorna That And You Find The Amount Off Subscribe Whole Earth And Answer Three Soldiers To Follow A Simple Problems Which Can Dissolve In Ocean World White Something But December 4 End Searching Decide File Ok Sweet Can Be Sold To Se Mintu Bank Contact Setting Quick And Skimming On Duty Matrix End And Morning Sea Problem Video Shining List What is the How Many Most Which This You Select My Name Is Former President Find the Number of Success with Sampoorna I Will Be Able to Get Answer is the Same Acid 122 Sam2 U Sam Melon Subject 2012 Time Loot a Surprise to Vanish ID together target is fixed then divide intended to subset description subsidy to fennel they are waiting plus time all these elements have to take place voting on - no more 10 elements - porn voting on - no more 10 elements - porn voting on - no more 10 elements - porn video's target and subscribe most tourism prosperity something which they can tree calculate trick Just in 1977 call elements and every situation not the solution very simple app to find at subset with complete mansion final submit complete proof that they through different most and defined account you most subtle course that for example year first one month side it Matrix initially it for rent agreement for treatment and all its soil has been defeated and satisfying complete app to find no subset with some food and basically declare defeated now to friend who were trend fighting s role number reduce actually 12345 big enters return 129th suicide aloe vera answer And your marital affair is optional School discussion How to suppose I want to make zero point You want me 100 One possible best you can just one Nothing in you will be able to make sure 299 plus seat ₹10 Suppose I want to make one but you Have only ₹10 Suppose I want to make one but you Have only ₹10 Suppose I want to make one but you Have only element shaders because never make any element of this element you can never meet you have nothing to fear nothing can you make something but you can not make any response to this entry through the pad to the next to front neck to what do next role You have to find out how can you make one ok we investment can you make midfielders we have gas can make word using one rescuers element lineage how will find out that you will vice captain sir investment research c history to make one and you how to use pair able To make one minus one video pimple to 100 number of waste set date will give numbers best to make one vikas 1022 100 and world end will give your answer one tweet simple hai jo hair oil scene filmaye not using this ₹1 to make two and Donate filmaye not using this ₹1 to make two and Donate filmaye not using this ₹1 to make two and Donate for investment using ajwain alone can you make two you can never make two rate fix follow andar dip table on yo lokendra dp table using one you want to make for using word you want to make your day element 122 - - - 122 - - - 122 - - - 1ST YEAR You Want To Make Another One To Take Notes In Another Lord Vishnu But Not A Single 12121 You Can Make You Can Insert Into Doing What You Love What Is This 1080 According To Previous Plus Minus One Subah Sacrifice His Admission In The System Date And Several Years Due To Values Voices Of Military Years Due To Values Voices Of Military Years Due To Values Voices Of Military Bases And Salts Normal Note Use 310 Try To Make The Number 16 Previous Sila 22182 A Little One Plus Two Three Lakh People You Can You All The Shrivansh Entertainment Civil Aviation So What Is The This To Make Too Using all the impossible balance so how can you make sure you will have to make to use in this very disappointed with this app you can be completed in mid-2014 z60 two that 11111 this former one ok 100 were less on pilot side to continue feeling Difficult for class sixth standard six for distance from plus minus pack try for example I can make for chapter two make for using all the possible bones are using all possible one side and good and 5s then is my answer in this world and returning Sudhar Sabha Election let's move forward to coordinate morning have in which is the rise of the following is not a what you want to celebrate subscribe to the Page if you liked The Video then subscribe that sui want to make Egg White O'clock School President Chiffon Not Even Been Stated Earlier And Logic And Shouldn't Have Been Allocated A Sum Taste Tone And Surplus Of Bums Negative Anger Will Keep Vanishing Include Something Share Calculated That Will And Vinay Katiyar Target Can The Give Any Major Target Just Ask Too Negative Rose Don't want to search and negative sentences of egg yolk forms and it will give you Play Services liquid discussed and initially e will give the way listen and prevention and improved and accordingly the checking that condition easy and simple way to count number of these to make a Particular Subscribe - - Great attention and subscribe school from its users can be no entry like doing his upcoming and innovative projects in the entry of course all the all agree guys just want to say but subscribe to the video channel - - - - 110 | 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 |
1,935 | hi welcome guys yeah welcome to my id call sony section so the resume is 1935 maximum number of words you can type so there's a male function keyboard which wears some keys do not work and all actually is on keyboard property and a given string text of words separated by a single space and a string of broken letters of all distinct letters uh keys are broken so basically all these broken letters that you cannot type in right so uh so for example uh you and you need to return a number of words in text here you can fully type so for example hello words uh this ad right so how low you can type it because uh ad is good but uh about the word that you cannot type right because uh this mail function so you return what okay for decode lt's okay lt is my function right so leads cannot do this okay so this problem is very easy you first split uh split your text into various words and then you initialize your result to be zero and you go through each word right so i usually go each uh word and then for each letter in the in a character so for example let me just let count initial to be one if i found it uh if i found any uh any letter which is uh in the broken either that means these words cannot type so i make ct to zero and the rest add or equal to ct and that return rest that's it right so a very simple exercise okay so i'll see you guys next videos | Maximum Number of Words You Can Type | minimum-number-of-operations-to-reinitialize-a-permutation | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** in_ `text` _you can fully type using this keyboard_.
**Example 1:**
**Input:** text = "hello world ", brokenLetters = "ad "
**Output:** 1
**Explanation:** We cannot type "world " because the 'd' key is broken.
**Example 2:**
**Input:** text = "leet code ", brokenLetters = "lt "
**Output:** 1
**Explanation:** We cannot type "leet " because the 'l' and 't' keys are broken.
**Example 3:**
**Input:** text = "leet code ", brokenLetters = "e "
**Output:** 0
**Explanation:** We cannot type either word because the 'e' key is broken.
**Constraints:**
* `1 <= text.length <= 104`
* `0 <= brokenLetters.length <= 26`
* `text` consists of words separated by a single space without any leading or trailing spaces.
* Each word only consists of lowercase English letters.
* `brokenLetters` consists of **distinct** lowercase English letters. | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. | Array,Math,Simulation | Medium | null |
803 | hey what's up guys john here again and this time let's take a look at another lead called problem here number eight zero three bricks falling when hit hard yes it is a hard problem okay so let's take a look at the description here you're given like a 2d grid with only one n zeros and one represents a break zero it means nothing and then it gives you another a parameter as a string as a list of hits coordinates it means that there's a sequence here so at the first place you remove zero basically you remove the uh sorry you remove the brick from this location if there is one and by removing this by removing the uh this brick right basically anything any other bricks that has not been connected to the roof will be far i mean will fall and it asks you to uh ask you to return and a list of integer that counts every time when you do a hit right basically when you remove uh a break from this 2d graph how many other bricks would will fall okay so let's take a look basically they're like breaks here right let's say for example there's like this one let me do this okay for example this one there's a one zero and one zero right so and this is the roof okay there's only one bricks there's only one brick connects the roof and the heat in this case is one and zero which is this one right one zero which means the first the heat will remove this brick we remove this break and after removing this brick the uh basically this one component becomes the two components right the first one is this one second one is this and the first one this break still connects the roof that's why and it won't fall but for the other two here those two will fall because if there's no way this to connect the roof that's why we have two here okay and okay another example is this one okay the second example the first row is do one zero and second one is one zero right and then the first hit is one which is this one right by removing this one there's no other break will fall right and then the second one is one zero is this one still because at this moment this one has already been removed that's why with this with the second hit still no other brick will fall okay cool so basically that's the two examples the problem uh gives us so how can we think about how can we try to approach to the solution right so as you guys pretty uh maybe has already noticed that so because basically at the very beginning there's only one component right and by removing the uh one of the bricks one of the breaks where we're breaking this one components into several sub components right and each time we remove breaks we're basically breaking it into a more sub component and with this kind of sub components problem we can always try to use a union find to uh to solve this problem right and for this problem specifically let's see how we can solve this solve it by using the union find technique right let's say we have a let's see this is a roof here okay and we have uh we have brakes i'm just drawing the brakes like an area here okay and okay so for example we have this kind of bricks at the beginning right just assuming those are the ones basically those are the ones uh in this 2d array and all the others there are zero so the area i'm i mean i'm including here the other ones right and that's our first initial state right and let's say the heat will be like somewhere here right this is the heat one and then there's a heat too okay and this is the hit three okay i'm just using this one uh using this as an example here right because there might be other like sub uh components that connects the roof right for example this one here there could be like some parallel uh ones connects to the roof here right as long as this thing at the beginning that connects to the roof right there could be some other components right here so just similar as the ones we're drawing here right similar like this so there could be other many other sub components that connects to connecting to the roof at the beginning right i'm just using this one as the example here so let's say we are having three hits here one two and three basically by uh by removing this one two and three we're dividing this what uh this one components into four sub components right and okay and it depends on the sequence of where depends on the sequence we of we are doing the heat the bricks that gets dropped uh also various varies right and how can we uh basically how can we solve this by using the union fine right so one of the key concept here by using the union fine is the uh we have to somehow write the way we're calculating the breaks that gets dropped is by uh first we are basically removing all those um those hits first and then we'll be constructing those components first by util after removing all those kind of hits will be like basically union those sub components right one by one i mean within the component itself we're gonna do a union and then we're gonna and the also another key point that is that when uh while we're maintaining a union like a class here we'll be also maintaining the size of each component because that's what that's how we're gonna use that's what we're going to use to calculate the breaks that will get job right and the way we're doing it is once we have those kind of sub components union together we're going to try to add those like heat breaks back one by one but notice here we're going to add them in a reverse order why because let's say we're doing this heat one two and three right so by the time we're doing the one hit all those two and three they have they'll have already dropped right and the way we're calculating the drops breaks is basically every time when we add one of the uh um the heat back we'll be recalculating basically not recalculating we'll be getting the uh trying to get basically recalculating uh how many bricks are connected to the roof all right so with that being said so other than the union find of its sub components we're going to have like a u like a universal a union root the root for the roof here basically everything that's connecting to the roof will also be a union with this zero here because we're using zero to represent the roof here and let's say the breaks from here to here is three okay and this is like uh five four six okay so basically by remove by removing one here right we are dropping like and we're dropping five plus four plus six right and we are also going to include this like the ones we are the heats right because let's say when we are when we uh remove this one this heat from here right all those ones will become zero and when there's like another heat hits a zero basically it does nothing right and so okay let's so we're doing it in the reverse order right basically we have this uh four union components and which first we add the three back we add three back and we're trying to union uh to use the three as a starting point we're gonna use you need a round basically we're gonna unit around uh four and six while we're doing that we're also trying to uh basically trying to update this roof uh roof count here and by the end we finish the uni here we'll be calculating okay what's is there any difference with this uh the new roof uh the all the breaks connects to the roof word and then the new value and the old value and new value if the difference between the old value and the new value will be our final result will be the result by uh will be the breaks that would drop will fall by removing the current heat okay say so for example here so by adding three and back so the four and six right those two components will be union together but it will not affect the union of the roof right because those twos are still not connected to the roof so that's why our in our final answer here the last element will be zero since we're doing this uh hits in the reverse order right and then when it comes to this two here right so the two basically we will union this five and this components right still it will not affect the roof count okay so that's why the second one is also zero but then when it comes to the first one right so when it comes to the first one basically everything is connected together and also connected to the roof right so and the difference will be four five four six right it's gonna be a not gonna be 15 in this case the difference because the roof will be uh will be increased by 15. that's how we are got calculating this result okay so um okay so with that being said let's try to code these things up this is going to be a long implementations and i'll try to finish it as soon as possible because not only we need to uh to get our final result but we also need to implement a new class for the union find okay so to start with let's implement the unifying class first right dsu the disjoint unit basically right so that's the depth okay in it self right and with the union line basically they're like two units unfind right find x and the union right x and y basically that's a two key method in the union find class here okay so to for the find right so for the find basically we're trying to find the roots the common root for this x right and the way we're doing is we do if x is not to this stuff parents x right we do what so if you guys know the unified algorithm so when we're doing the find we're also doing a path compression here so that every time we do a fine it will also basically let's say there's like this and this right this is the root here and at the beginning this one's parent pointing to this and these patterns pointing to this and this one parents pointing to this so once we're doing the find let's say for example for this axe here right while we're where we're traversing back along the way here will be flattened this tree structure right basically for every parents along the way will be basically move this their parents directly under the roof here basically this one will be under back to here pointing to this and this one will also point into this so that the next time when we do another find for the x it will not basically traverse back all the way back like again it will just uh do a one time one times uh look up and then we'll find it basically then the next time when it comes to here okay the parents of x is x so we simply return these parents um okay x the parents act okay and since at the beginning right we're going to initialize this self parents note right and uh parents and at the beginning the each element parent it's itself right that's why when we uh do it do a find for this x here when it reaches all the way back uh all the way up to here then we find out okay so the x is equal to the x the self-parent.x because at the x the self-parent.x because at the x the self-parent.x because at the beginning each element are pointing to itself so and then if it's not right and then yourself dot parents x right equals to the self find self parent.x right basically we're self parent.x right basically we're self parent.x right basically we're doing this like recursive call and then in the end we simply return the self parents x right okay and to start with the union find here right we're gonna basically that we started to service the union find we need to uh for each of the elements here we're gonna start with its same it's same with its own like components at the beginning right basically at the beginning every uh element itself is its own component and how many elements do we have here right it's a it's m times n right so i'm gonna pass in the two parameters m and n here right and then so at the beginning right so the list will be uh be a range of m times n plus one so why i need to do a plus one here like i said i'm going to use a zero to be uh to stand to be this to represent all those components that just connects to the roof okay that's why i'm using a 0 as a special number here right and then so so the range okay so in python 3 the range becomes like a numerator that's why we need to convert it to a physical list and then self dot you know i'll be using the ranks here because ranks is the way we're doing the union find will basically will depends on the current rank of the route we'll be either assigned the route to the other one or the other way around right and i'm going to just keep the ranks here at the beginning each of the components the rank is zero start is the part class one then okay and then the size right so for at the beginning each size is one because the one itself right but the one thing to be noticed here that is the size zero which the our special one is zero at the beginning because at the beginning we haven't checked we haven't unit anything right so that we don't know the uh the size of the of zero which is the total bricks that connects to the uh to the roof okay so once we have those uh several components uh variables here we can just uh and for the unit here right so that's defined and then the union we're gonna have the root one because to find x and root two you also find y so if r1 is not to r2 right and then we check if the rank of r1 is greater than rank r2 then we assigned our r2 to r1 basically the parents itself parents of r2 equals to r1 right i'll see if rank r1 are smaller than rank r2 right we do it in a different in the opposite way we assign parents of our one to r two right else so basically if the rank are the same it doesn't really matter which way we're doing the sign but where i'm just using this one to the uh we could either assign that or the other one right and then when we only when they're the rank are the same and then we will be updating the rank by one soft rank since we're assigning the parents to r1 here so the self that ranks uh r1 will be increased by one okay and like i said not only will be maintaining each component of um each components uh to all the components but all we also need to include the uh maintain the size so basically once we are assigning the uh the r2 to r1 the size of the root r1 will become will be added by this right same thing this and for this one we're going to do a opposite way right so now we have this simple union fine here okay that's our simple union fine with the size okay is the size now let's uh start implementing the uh start implementing our main logic here right so first m equals to length great and look at the size of the grid here okay and then uh i'm gonna do what directions here four directions since later on we'll be union uh find the directions of four directions right and then we're gonna create the dsu class here uh dsu by m and n right okay and then first uh so first we will remove we'll remove all the uh the hit points right for range uh now for the x and y in h basically if the grade is one it's one then we mark it as two right so why we need to check to uh check it once because the heat might hit an empty and uh at zero point right in that case there's no need to uh there's no need to union them together right because at zero we will not do anything okay and so for in this case i'm going to mark this the hit point to add another value in this case i'm going to use two here okay so now we'll be using those components first right so for i in range m and for j in range n right so basically if the grid of i and j is one then we'll try to union them around right union around okay i and j okay so that's another hyper function we're gonna define here because basically what this one does is we're gonna use the uh we will be uh basically union all those like uh the current one with all those like neighbors in four directions as long as the neighbor is one yeah we so basically here we're using like uh a for loop here or we can use a dfs search you know to uh to do the unit here basically we start from here and then we uh we do a dfs or bfs search to union everything but here we're just using a simple way here uh we just loop through all the other elements here right and then for if any of them is one we try to uh union them using them together okay and okay so now let's try to call this helper functions here define a union around right so it's going to be i uh i and j okay so like i said since there are like this many have here so for each of the components or each of the elements on this 2d agree we need to have give them a uniquely identified sequence to represent each element right so basically we would just simply use the uh sequence equals to uh i times m plus j and plus one right because the zero is the ones we need so for zero zeros we want it to be starting as one because zero has a special meaning here it means all the uh all the components uh connects to the roof right so okay so that's and then for directions right in directions and new i equals to i plus d zero right mu j equals to j plus d one and we do a simple uh sanity check here okay and j equals to n right and of course and the new the great new i and new j is one right so then we'll reunion we'll do a union dsu dot union sequence and okay sorry the new sequence here new sequence right so nu i times m plus mu j plus what right so basically we're gonna union those two sequence together right and then so while we're doing the unions here and uh another thing is uh to notice here so for everything that's connecting to the roof we still have we need to uh also updating this value here right so basically if any i and if any i is zero equals to zero right then we simply dsu that union zero right zero is the current sequence right okay yeah so with that so that's the union around here and now we have the union around so at this point we have particip partition those like components into several sub components right now we just need to uh add those uh heat in reverse order okay so that's the current well i'm going to define the current bricks right connect to roof okay i'll just call this so it's going to be a dsu dot size right so it's going to be the size of what of the dsu dot find zero right so that's the uh because the size is maintaining the uh for each component and we need to find the zeros so why we're doing the find zero instead of zero because when we do the zeros you know the because we are not guaranteeing that the current roof of the uh the current roof of the zero is still zero right because every time we are oh yes you're right we are uh union the sequence with zero but the roof of the of this may not be the zero itself right it's not guaranteed basically here that's why we need to find the common root for that because we're using this common roof as the roof id the roof value as an index to indicate the size of that component right that's why we need to find the common root we need to find the root for this like the components right of this zero are the containing to the zero to find the size of that right so okay now okay the answer 8 counts okay length of hit and then the answer will be the size of the heat right so we're going to initialize this thing to the heat count and then we're going to reversely traverse the heat okay it's count minus one right that's how we do a traverse uh loop for the heat count and x heat cap set hits i zero why is the heat i one right and okay yeah like i said right uh we need to check if this thing is a zero or one right because the uh the heat could also like i said it could also hit a zero right so for the zero it means that we didn't remove any ones right so that's why we don't want the union do a union around on that by mistake that's why we need to check if the current grade of this heat is two or not right that's where making sure there was a one here right now we need to add that one back by union around doing the unit round so first we'll add that union that hit back by uh changing this grid value from two to one and then we're going to do a union around of this x and y right and after finishing the unit around here i'm gonna have a new bricks right connect to roof okay from it's basically the same thing here right from updated value here and then with those two values i can just get our answers right answers dot i equals to the new bricks divided by the buy this one okay and we also need to do a minus one here right the reason we're doing the minus one here is because we don't want to calculate this one by itself right so the heat itself cannot be counted as a dropped heat a dropped uh bricks because by the time when we do this union do a size query here it will also including this one we just it back here right that's why we need to do a minus one here but there's another thing we also need to be careful here because by the new bricks the new and the current and old one could be the same right basically known it could be the same could it be the same yes it could be the same yes right so it could be the same because there's no new component gets added but to the roof right so in that case this thing will become -1 right but we this thing will become -1 right but we this thing will become -1 right but we don't want it to be -1 even though it's don't want it to be -1 even though it's don't want it to be -1 even though it's they're the same we just simply do a max here right or we can simply do this okay if right we do a simple it's greater than this okay and then we do this otherwise we'll just keep this one as zero right because we initialize every element to be zero and after that we're going to update i'm going to update this current with this right so that we can keep updating this one so the next time it will be having a new updated bricks okay so and then in the end we simply return the answer so that should be about it 36. directions okay ranks yeah since this is such a long implementations you know there might be a union you need around 70. yeah so many typos here you need around okay let's see which one yeah i think since this is such a long video and implementation i must have made many typos here for example this one here size right and size here okay so this one's fine let's try to submit it this index out of range index okay i'm and x where does this m x come from right x come from the union here right x and y how about where does the union come from union from here that's union old sequence and new sequence and where does the old sequence the new sequence come from i j plus uh here instead of m it should be n because x times the column and then plus the column number right same for this one okay now let's try to submit it again oh my god finally okay it works okay such a long implementation and it's a really hard one so at least for me it's hard one so okay i don't know if we really need to do another recap because this video is already over 40 minutes so basically just a union find concept but instead of the ranks and parents will also be using like a size for the union unifying because we'll be using the union find component size to and in the reverse order to check and plus adding the heat break back in the reverse order to check what's the uh the drops the what's the breaks that will drop uh for this current heat right okay cool i think that's it for this problem yeah i think that's enough for this problem thank you so much for watching the videos and see you guys soon bye | Bricks Falling When Hit | cheapest-flights-within-k-stops | You are given an `m x n` binary `grid`, where each `1` represents a brick and `0` represents an empty space. A brick is **stable** if:
* It is directly connected to the top of the grid, or
* At least one other brick in its four adjacent cells is **stable**.
You are also given an array `hits`, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location `hits[i] = (rowi, coli)`. The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will **fall**. Once a brick falls, it is **immediately** erased from the `grid` (i.e., it does not land on other stable bricks).
Return _an array_ `result`_, where each_ `result[i]` _is the number of bricks that will **fall** after the_ `ith` _erasure is applied._
**Note** that an erasure may refer to a location with no brick, and if it does, no bricks drop.
**Example 1:**
**Input:** grid = \[\[1,0,0,0\],\[1,1,1,0\]\], hits = \[\[1,0\]\]
**Output:** \[2\]
**Explanation:** Starting with the grid:
\[\[1,0,0,0\],
\[1,1,1,0\]\]
We erase the underlined brick at (1,0), resulting in the grid:
\[\[1,0,0,0\],
\[0,1,1,0\]\]
The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:
\[\[1,0,0,0\],
\[0,0,0,0\]\]
Hence the result is \[2\].
**Example 2:**
**Input:** grid = \[\[1,0,0,0\],\[1,1,0,0\]\], hits = \[\[1,1\],\[1,0\]\]
**Output:** \[0,0\]
**Explanation:** Starting with the grid:
\[\[1,0,0,0\],
\[1,1,0,0\]\]
We erase the underlined brick at (1,1), resulting in the grid:
\[\[1,0,0,0\],
\[1,0,0,0\]\]
All remaining bricks are still stable, so no bricks fall. The grid remains the same:
\[\[1,0,0,0\],
\[1,0,0,0\]\]
Next, we erase the underlined brick at (1,0), resulting in the grid:
\[\[1,0,0,0\],
\[0,0,0,0\]\]
Once again, all remaining bricks are still stable, so no bricks fall.
Hence the result is \[0,0\].
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `grid[i][j]` is `0` or `1`.
* `1 <= hits.length <= 4 * 104`
* `hits[i].length == 2`
* `0 <= xi <= m - 1`
* `0 <= yi <= n - 1`
* All `(xi, yi)` are unique. | null | Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path | Medium | 568,2230 |
1,944 | hey what's up guys this is john here again so uh this time i'll be called 1944 number of visible people in the queue uh this one um it's um i wouldn't say it's a hard one it's a medium more like a medium one so we have n people standing in the queue right and they numbered from zero to n minus one in left to right order and you're given like a height of distinct integers right basically each person have a different uh height and the person can see another person but we got a bunch of minions here a meaning can see another meaning to their right if the in the queue if everybody in between is shorter than both of them okay so this is a more formally explanation so the person can see this person if i is smaller than j and anything basically there's no block between those two persons right and our task is to return like an answer of length of n where the number of people of the eighth person can see to the right in the queue right so for example we have this bunch of minions with different heights right so and then the output is three right the output is a three one two one zero this is because you know for the first meaning right uh it has height ten right so how many minions can see it can see uh this one it this one is fine but this one is not because obviously you know because this one is blocked by this minion right but this one can see this one because this one didn't get any it will not get didn't get blocked same thing for here right and then and also this one right but not this one because this one is also blocked by this one right so that's why we have three right and then the next one is what the next one is one so for this one for the second minion the answer is one because this part this one can only see this one there's nothing more because all the others they're all being blocked even though right i mean even though this one is uh is higher but it even though this one is this high but i think we didn't count that because the definition is that you know uh in order for this person to for this minion to see to this meeting all the meanings in between has to be smaller has to be shorter than any of them right that's why the answer for this one for the second meaning is one right and then for the third one right first for this meaning it can obviously you can see this one right and then you can also see this one but not this one right because this one has been blocked by this one right similarly as you guys can see right so at least the meaning can see its neighbors on the right side similarly for this one right so for this one it can only see this one right and then for this one right it can see this one but there's nothing here that's why it's also one for the last one obviously it's zero right and yeah that's it right i mean 10 to the power of 5 and all the values of heights are unique okay um so this one i mean so first for this problem you know obviously the brutal force ways that for each of the meanings right for each of the meanings we loop through to the right side right and then and we loop through everything right to the right until we have seen a one that is greater than the current one for example right if from 10 we loop through to the right side until we have seen how we have reached the uh 11 right uh no sorry i mean from 10 we loop through everything to the right side okay so every time uh there's like let's say for six it's fine but for eight right for eight is five eight is fine but for five is not because you know basically we're maintaining the current the previously highest median right and then we only accumulate the answer when the current one is greater than the previous one right for example when the six and then the previous the highest is six when the is eight the highest eight right but in the five when eight is greater than six that's why the eight is fine but when the wind comes to five smaller than the current height which is eight that's why five is not but eleven is fine 11 because 11 is greater than 8 but now 11 is a current heist and the nice knot right so which means obviously we have to uh for each of the minions we have to do a often scan right it will be a n square time complexity so for this one you know the easiest way to do it is to simply use the monotonic uh monotonic stack i think is it stack or queue i think it's monotonic stack so which means in this one actually all we need what we need uh we need is it increasing or decreasing let me think i think it's going to be increasing q uh increasing monotonic stack it's because okay so what how do we use that to help us solve this problem you know so first you know in order to do that we have to look through from the end to the start you know because as you guys can see right so the first one is nine right the first one is nine the second one is 11. you know if we loop through from the end to the start you know since 11 is greater than 9 right so what does it mean it means that it doesn't really matter how many meanings on the left side and none of them will be able to see 9 c9 anymore right because there's like 11 on the left side which will always block the knight right similarly for like you know we have 10 6 8 5 11 and 9 right similarly for the uh for this five here you know let's uh so for five right i mean we have eight on the left side of five right so what does it mean similarly you don't know what anything on the left side will not be able to c5 because eight has is blocking in front of standing in front of five right so which means that you know every time if we loop through from the right to at the end to the start you know any every time when we see like uh if the current height is greater than the previous one we can simply re remove it because that's not useful anymore right we can simply remove it that's why you know this is like the perfect u candidate for the monotonic stack right so what does it mean means that like this so first we have 9 right so we have nine in the uh in the monotonic stack which is the increasing stack and when the 11 comes you know so 11 see okay 11 is greater than the nine right that's why we're gonna move this one out so now we have 11 here okay and then we have five right so five is smaller five smaller it's not greater than 11 that's why we're gonna keep increasing pushing it to five right and then the eight comes so when a comes eight is greater than five right so we're gonna remove this one and we're gonna push eight here but it and then eight is smaller than eleven that's why we're gonna keep this eight here right and then we have six all right six is smaller than eight that's why we keep it there and then we have ten right ten is what so ten is it's greater than six so six is out it's greater than eight eighty eight is out but 10 is smaller than 11 that's why we're going to put 11 here all right we're going to put 10 here right now as you guys can see actually the number of the people the current person can see is has a very close relationship between the numbers that got popped from this monotonic stack right for example this 10 right let's remember we have uh eight we have six and now the ten comes right so ten will pop six out right and then we'll pop eight out right that's why we have two here right and then we have 11 right so this is this third one because 11 even though 11 is it's not get not gets popped but you know the 10 can see 11 right so i think that's pretty much it is right so basically we simply maintain like monotonic stack and then we count how many numbers how many uh numbers got popped out because as you guys can see this five will not be counted right because five have already been popped when the eight got pushed into this monotonics in the increasing stack that's why you know that five is not counted uh for this minion has height 10 here only the 6 8 and 11 right and yeah so for the implementation it's pretty increasing stack maybe i was cut this one and then we have n is going to be length of height right and the answer is going to be this okay and then we loop through from the end right n minus 1 and minus 1. um we have a total maybe so while increasing stack it's not empty and the height of the current one is greater than the increasing stack of minus one right because this one is the uh the top one right and then we increasing stack dot pop okay and then we increase the total plus one okay right so and then another one is that you know if the increasing stack is not empty we will basically increase the total by one right so this one is for what for the next for the person right for the count the person who is higher right than the current one right because you know for example for 10 here right so for 10 we pop six we pop eight and then we have two here but you know the answer is three because we have eleven here we go this current person can also see but the reason we don't do this separately is because you know for example for the 11 right for 11 you know once uh when the 11 comes it will pop nine out that's why the total is one right but the answer is for eleven is one because there's no more uh a minion left in this increasing stack here that's why uh we have to do it uh increasing the total separately whenever only when this there's still some meaning left higher mean left in this increasing stock stack right and then we push this increasing stack with the current height right and then and in the end simply uh we update the answer right with the with current total right and then return the answer that's it okay submit yep so that's it right i mean uh it's pretty straightforward i mean i don't know why they rate this one the heart maybe because of the use or the idea of using the increasing the monotonic stack it's not that common right but yeah regardless i think it's a very necessary or a very useful technique everyone should know right basically you know the reason we use a monotonic stack is that you know we will not reprocess the this useless meaning multiple times for example this 9 this 5 this 8 right so which means that you know each of the meaning will only be pushed and popped in and from this monotonic stack once that's why the time complexity for this one is often right yep and the reason we can use the increasing stack is because like i said anything that's after on the right of this higher meaning will be totally useless because it will be completely blocked by this one that's why we can safely discard this one right because of that we chose to use the monotonic stack and okay i think that's it for this one and thank you for watching this video guys and stay tuned see you guys soon bye | Number of Visible People in a Queue | truncate-sentence | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is **shorter** than both of them. More formally, the `ith` person can see the `jth` person if `i < j` and `min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1])`.
Return _an array_ `answer` _of length_ `n` _where_ `answer[i]` _is the **number of people** the_ `ith` _person can **see** to their right in the queue_.
**Example 1:**
**Input:** heights = \[10,6,8,5,11,9\]
**Output:** \[3,1,2,1,1,0\]
**Explanation:**
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
**Example 2:**
**Input:** heights = \[5,1,2,3,10\]
**Output:** \[4,1,1,1,0\]
**Constraints:**
* `n == heights.length`
* `1 <= n <= 105`
* `1 <= heights[i] <= 105`
* All the values of `heights` are **unique**. | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence | Array,String | Easy | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.