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 |
---|---|---|---|---|---|---|---|---|
285 |
hello friends today I will try something author successor in PST given a binary search tree and a node in it find the inorder successor of that node in the BST the success of a node P is a node with the smallest key creators and pitiful let us see the example given a tree about 2 1 3 and P is 1 so we will return to so basically almost older PST racial problem can be solved by the in order traversal the same to this problem we can definitely see to simulate the auto traversal but the time complexity will be open and is the total nose in this BST can we do better yes we can solve this problem in which time entry the height of the pencil tree mmm because we have to take use of the property of the BST with them missing about it given a tree know what where will it possible inorder successor in order successors position 1 it will be if it has the right children it should be the minimum of its right children because if it has right children all the writers are greater than it so we should you find the minimum of the right shoulder it will be the successor under what if we do not does not have the right children then a parent should be eat inorder successor right in which case we will not have fine it which will be the greatest know the industry such as under six industry then we cannot find the tree note so basically first we will check if the P it's alright not if what you know we can return finding find a minimum of the P right and we will implement to the five minima afterwards and if we're not the case we should show compared with the root of all right with set a successor first ego to know and the why of the root not equal to the know will compare their each other but if the root of a greater than Padova which means the root can be the successor we said so the successor to the root and the way that root equal to root left to see if we can find the smaller one in case rooty is fine and we want to find order success of the tube and the first we set a successor to the five and then we keep a fine then we change to the three right and this a case if the root stop valve is the best impede about which means we should find in a right place right so root equal to root at all right else if we there it equal right if they are equal we cannot find the equations in this tree with ending greater things in this tree right if we there you probably just a break why because easily if we are if the trees this tree and the piece five we will do this part we will not do this part what if we are at three pins three and the root is five so we will first add a successor to the five and then we move to the street and we end as a while loop so we still get the right successor return this successor Leslie implemented our final minimum they were even a tree node P what is the minimum where is the minimum is a will be the left her left a monster tree nor Y or P not P so left not equal to know which are very pijo to repeat the left this also tell you of the property of the yes key okay so the term compressive should be Oh ash actually is the height of the BST okay thank you for watching see you next time
|
Inorder Successor in BST
|
inorder-successor-in-bst
|
Given the `root` of a binary search tree and a node `p` in it, return _the in-order successor of that node in the BST_. If the given node has no in-order successor in the tree, return `null`.
The successor of a node `p` is the node with the smallest key greater than `p.val`.
**Example 1:**
**Input:** root = \[2,1,3\], p = 1
**Output:** 2
**Explanation:** 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], p = 6
**Output:** null
**Explanation:** There is no in-order successor of the current node, so the answer is `null`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
* All Nodes will have unique values.
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,173,509
|
559 |
hello guys welcome to deep codes and in today's video we will discuss related question 559 this is maximum depth of energy so what does an editory means this is this would be the first question that comes to your mind when you think of this question okay so an editory means so let me try to give you an example so let's say this is a binary so what does binary have one property that it can have at Max two children this is not possible like two three five this is not possible it can have at Max two children but what does narrow tree can have an area can have more than two children as well like three four five six it can have n possible children what and children's is the name suggests binaries are only two so yeah the binary tree can have two children whereas n editory can have multiple number of students so that's the meaning of an auditory and we need to find the maximum depth of this identity so guys this question is mostly based on the this based on the equation maximum depth of binary this is almost similar to this question and if you don't know how to solve this then make sure to check out my video on this question maximum Vapor binary you will find the link in the description so yeah based on this approach of the maximum depth of binary we would try to solve this question as well and I also I will show you the difference between the code for the maximum depth of binary and N energy there is only slight difference otherwise it is completely the same okay so yeah the first uh thing here is uh to find the intuition so what uh to build the intuition for this equation like a tree that is some basic approaches that is bare breadth first search and that first search so yeah today also we will be using this simple approaches question to solve this problem so now let's take a look at this example like this is the given an error trim and you need to find the depth so as you can see here this there is a depth of three like one three and five or one three and six that are of depth three so your three is our answer this is one two is the only of depth two so it is in the maximum that is three so here in this question the maximum that as you can see here is one three seven eleven fourteen how many nodes are there in this path final so return will be written five okay simple as it is so yeah now let me try to explain you that how uh DFS will work how DFS approach will work so here DFS approach will in what video in DFA suppress what we do we simply do one thing we Towers from parent node to child node okay the same thing we would be doing here traversing from parent node to child node right see let's let me give you an example so this is parent to child then this on reaching this will also move to this child this will move to child but child is now so uh so we will try one based condition that if we found null then we would return 0. okay and if not none then what we would return one by one because if there is simple one node in a tree so take count is only one node then the depth what of this tree would be one so each node has a one adapt of itself right now here what this will return to this parent this is written 2 by 1 plus previous answer the previous answer is one here correct so it will return to one plus previous answer is 2. now for this node itself what would be the answer it will get 2 plus 1 means one plus previous answer also one plus previous answer this is what we are doing for all the notes the previous answer here is two and one for if that's of itself so it will be three okay now from here we would move to this will now again call this node then this five will call to six and six will check first time no check sooner so it would return zero so here uh the return would be one it would return one for itself here two means one for itself and one plus previous answer here three and here zero here the node 0 plus our previous answer that is one plus previous answer so it's four for this part four as you can also see we have four nodes correct now uh this will call to this three will call to seven okay what seven will written seven will return to one now after retaining one this will call to this age what it will return it will also written one okay here both the places are returning one now this three will call to this uh this node like this nine okay 9 will call to Ten will call to 11. now be on 11 there is nothing right so according to no it will return 0 . now what 11 will be written one what . now what 11 will be written one what . now what 11 will be written one what 10 will return to 9 it will return two what nine will return to 3 it will return three okay now here at this node 3 it will take 1 plus maximum of this maximum is of three one and one so it will take one plus three the maximum of all this node Stream So what is this is four so what this node 3 will return to node zero it will return four and here what does node 0 does it will it do one plus previous answer so that is 5. okay and now it has three possible answer like one is this second is this and third is this so what does this node variated in this node will itself written the maximum that is five so five would be over answer so I hope you guys understood that how DFS function will work that each node will pass some value to its parent node and at the end we get a list of answer and from that we will return the maximum answer right here also we are doing the same thing at three we had three answer like one comma 1 comma three these three different answer and here what we are choosing the maximum answer and adding one to it similarly you are choosing the maximum answer and returning that as our answer simple as it is so I hope you guys understood this DFS approach now let's take a look for the coding part of this DFS approach so let me show you so yeah this is the code for this DFS approach so here we are initially uh checking if the root is no if it is then we return 0 then we are taking one vector v by vector v so you know so we took Vector because we don't know what how many children are there it's in binary tree it was fixed that it makes two children but in N RF tray there is no uh fixed size of how many children are there so for each root we need to travels for all its children whether it be two children three children four children five children we need to travel all this all those children and the answer from all those children we need to store somewhere okay simple as it is we need to store somewhere and Vector is one best possible data structure because it is not of any fixed size correct this is not a fixed size so yeah that's why this that's why we stored a turbine in this vector and what other thing we are doing we are simply taking the maximum of the from the list let's say we have stored this as a list one comma three now here what we need to do we need to take maximum of this answer right so we so that's why we are taking maximum foreign the same thing we are doing here correct so yeah this is how the DFS approach will work for this energy not showing you the same see the DFS approach for the binary trees here the code is same as it is same the only difference is that here there were two children so we could have taken left nurture and right chart simply but here since there are n number of children so we have to take something like vector to store the answer right and we need to Traverse all these children and from all this we need to take the maximum here also we were taking the maximum but maximum of only two but here since uh there are n number of children we need to take maximum from all this end right and we return time as our answer here also we are doing plus one here it's a coded so yeah the approach for the maximum depth of n editory is same as maximum depth of binary only the difference is that since we have n number of children so we have to take something like vector and store the answer from all the children so yeah I hope you guys understood the approach the DFS part as well as the coding part now if you want to do the BFS Traverse it is as simple as that if you have understood the approach of BFS traversal in a binary tree then it is exactly the same in the an array exactly the same only difference is here we are traversing n children's instead of two children that's the only difference so yeah I hope you guys understood the DFS as well as BFS travels the coding of both days and you are not talking about the time and space complexity the time complexity here uh would be big off and time complexity would be big off and as we are traveling all end nodes and as well as the space complexity would be bigger of it for both DFS and BFS approach because this DFS approach will store some nodes in the recursive stack and in the BFS approach we are using something known as Q so yeah the space complexity would be big offend because in the worst case we are storing all nodes in at a time so yeah that's for the time and space complexity and yeah that's all from my side today I hope you guys understood this video and if you have any doubts then do let me know in the comment section make sure you like this video And subscribe to our Channel thank you
|
Maximum Depth of N-ary Tree
|
maximum-depth-of-n-ary-tree
|
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** 3
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** 5
**Constraints:**
* The total number of nodes is in the range `[0, 104]`.
* The depth of the n-ary tree is less than or equal to `1000`.
| null | null |
Easy
| null |
767 |
hello everyone welcome back here is vanamsin and today we have something super interesting lineup and for you a problem that's easy to understand but will give your brain a nice workout so we are attacking lead code 767 uh reorganized string problem and this isn't just a problem it's a puzzle that you are going to love solving so buckle up because we are diving deep into this one so all right let's understand what the problem is asking us about you are given a string as filled with lowercase English letter and your mission should you choose to accept it is to rearrange this string in such a way that no two adjacent character are the same so if that's not possible we return an empty string so to put it in a context if the string is a b we could potentially rearrange it to a B a so got it so great now let's dive into detail and code this out so I will be coding it in Python today but fear not if you are into other programming languages I will put the equivalent code in Java C plus go rest and much more in the description below so you are covered now let's talk strategy we are going to use a python hip library to make this happen so why hip you ask well hips are excellent at keeping track of elements based on their priority which in our case is the frequency of each character in string so this data structure will sort out characters by their frequency in a descending order making it easier to select the most frequent character first so step one is to initialize our frequency map at Max hip so we will iterate through the string and count how many times each character appear so let's implement it uh count frequency of each character so frequency map will be map and four Char in s frequency map picture will be frequency map getter plus one and yeah in s okay so uh now uh we need to build max Heap based on the frequency so uh let's implement it as well so build Max Heap based on frequency so max hip will be minus frequency enter 4 chart frequency in frequency map item and hipify Max Heap and initialize result string okay so if we working with an input like a b our Max hips would look like this after initialization so it will be uh minus 2 a and -1 for B so now let's get minus 2 a and -1 for B so now let's get minus 2 a and -1 for B so now let's get into the core logic so we will keep popping the two most frequent character from our Max hip place them in our result and if they still have a remaining frequency we will push them back into the hip so we will initialize a result string and then alter placing the most common letter so result and alternate placing the most common letter so while Len of Max Heap greater than 2 frequency 1 tractor one hip hop Max hip and frequency 2 character two will be hip pop Max hip as well and results extend chapter one and character 2. and IF frequency 1 plus less than zero hip Q hip push Max hip and frequency one plus one character one and IF frequency two plus one less than zero hip push Max hip frequency 2 1 director two so if Max Heap frequency character will be hip hop Max hip and if minus frequency greater than one return empty and result append character and return join result Okay so after our first Loop iteration our result string become a b and as you can see the two a are separated by a b which is exactly what we want so to wrap up we need to handle any remaining characters uh if a character still exists in the Heap and its frequency is greater than one that means we can't find a unique uh partner for it so we return an empty string and yeah and there we have it our final output for aab should be a b a so let's test it and see if our implementation work so yeah all working so now we can submit it for unsynthesis cases as well uh to verify and yes or working and our implementation this time bit 93 with respect to run time 35 milliseconds and 46 percent with respect to memory so uh it's good and efficient so that's how you tackle this fantastic problem uh I hope this detail uh breakdown helps you understand not just the world but also why and uh how of this solution and if you have any question or different approaches feel free to drop them in the comment section below and don't forget to check out the description for code in order programming languages and as always see you next time keep practicing and happy coding
|
Reorganize String
|
prime-number-of-set-bits-in-binary-representation
|
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.
Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_.
**Example 1:**
**Input:** s = "aab"
**Output:** "aba"
**Example 2:**
**Input:** s = "aaab"
**Output:** ""
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
|
Math,Bit Manipulation
|
Easy
|
191
|
48 |
foreign hello everyone and welcome back to another video so today I'm going to be solving the lead code question uh number 48 rotate image all right so over here we're going to be given a n by and two dimensional Matrix which represents an image and the goal is to rotate the image by 90 degrees in the clockwise Direction so we have to rotate the image in place which means that you just modify the input to The Matrix directly without allocating any extra space so obviously let's say we have this example of one two three four five six seven eight nine and when you rotate it so 90 degrees right so you can just imagine everything moving like this right like an image and what you get is this result over here so let's actually try to see if there's any sort of pattern that we can recognize which allows us to come up with a solution to this okay so we have these two examples here and let's start off with a smaller one right so just try to imagine it first in your head right so you have this image and you're rotating it so how do the pixels move so you can just think of these uh values as pixels right so essentially in this case what's happening is this one two and three when you rotate it comes like this so in very simple words the first row that we have over here ends up becoming the last column okay so let's just kind of write this relationship so whatever the first row was or actually let's just use zero indexing so the zeroth row becomes the last column okay cool um so let's just move on with that so the four five six let's rotate it and what happens is that becomes the last but one row okay so in other words the first row ends up becoming the last butt one I'll just write that as last minus one column okay and over here we have the last row over here the second row and that ends up becoming the last but two uh column okay and so let's just write that relationship the second row and so becoming the last I'll just write part two is -2 column cool so we kind of part two is -2 column cool so we kind of part two is -2 column cool so we kind of found this relationship and if you look at the four by four over here it's the same thing right so this is nothing else but the last column five one nine eleven and the relationship just goes on so um let's just write it for the four by four so now everything stays the same except we have one more thing which is third row becomes the last minus three column okay and you can think of the first one as loss minus zero column so we have this very direct relationship and we kind of want to code this out right so we understand what we want to code and now we just want to see how can we actually do this so let's just focus on the four by four since it is a bit bigger so we can look at it a bit more better so over here we've understood that this is what we want to code now how exactly can we do this so just to kind of show you the relationship right you could just think of this or actually let's just go back to the three by three so over here you can just kind of think of this as a circle right it's the one goes over here the three goes over here the nine goes over here and the Seven goes over here likewise the two takes place of six takes place of eight to four to two and the five states as it is you can see the same relationship over here with the four by four now you could code this relation out but that is going to be a lot harder to do and I think it's a lot easier to just code the relationship that we found out in the beginning okay so how exactly are we going to do this so what I want to do is I want to add a few more elements to this so just so it's easy for us to look at so the last minus zero column is nothing else but the last column which is the third column okay the same way the second column is the First Column and this is the zeroth column okay I'm just writing it so that's easier for us to interpret Okay cool so how exactly can we do this so one thing that we could do is we could transpose the values so if you don't know what that means it's uh so if you have X comma y after transposing it you would have y comma X okay and what that really does if you just look at it at a broader perspective it takes the First Column and it makes that the first row and so on and so forth so let's see what that looks like okay so I'm going to take 519 11 so that's the first row and when you transpose it that's going to look like this 5 1 9 and 11. and uh just so it's easy for you to understand so this was at the index 0 comma one and we transpose it set the index one comma zero as you can see okay so let's just do that for the other rows so 2 4 8 10 so when you transpose that you go two four eight and ten uh then you have thirteen three six seven and finally fifteen fourteen twelve sixteen so this is what I get after transposing our Matrix okay so what exactly has happened so let's just use this color so what happened is the zeroth row okay has now become the zeroid column okay now the first row so let's just write this after transposing the column okay so the zeroth row has become the zero code right the first row has become the First Column the second row has become the second column and finally the third row has become the third column now it has this rotated our Matrix well not yet but we have gotten closer so now what we can do is very simple right so now that we have these the zero throw as the column and the zeroth column we just need to get it in this order over here and we can do that very simply and that is just by swapping out the columns themselves right so if you swap out this column and the last column what happens is now the zeroth row is the third column right which is exactly what we're looking for and we can do the same over here we just swap these two out so this is exactly how we're going to solve our question so first we're going to transpose it so all the rows become the columns and then what we're going to do is we're going to swap them so the zero so we're going to swap these two and then we're going to swap these two so by doing this it's going to be a lot easier to code out the solution and we're going to end up rotating our Matrix so let's see what this looks like in code all right so we have two parts to this so first we gotta transpose our Matrix and then what we have to do is we have to swap the columns okay so cool let's start with the first part so we're going to first iterate through the row so for I in range length of Matrix and we're going to do the same thing now for the columns Okay cool so now that we have this uh this is actually wrong but let me just show you why okay so essentially we're going to have Matrix i j and that is going to get swapped with so now that is going to have the value of Matrix j i so since we are swapping the values we got the same for ji so Matrix j i is now going to have the value of Matrix i j okay cool so now this is what looks correct but there is a small mistake with this so let me just show you that so I just wrote the small thing here so for I in range 3 for J in range three print I comma J and then J comma I right so 0 after transposing becomes zero which is correct zero one becomes one zero and zero two becomes two zero so all of that currently makes sense and now we have a small problem so over here we have one zero becomes zero one and the reason that it's a problem is because that now the what we swapped over here is now getting swapped back again so essentially it's just going back to its original position so essentially if you run this line of code over here what you had before and after running these four Loops is going to be the same so a simple fix to this is we could just have I over here right so in that way we're not going to have any overlap cool so now that we've transposed our Matrix we're going to swap them so let's get the columns first so for J in range length Matrix now we're not going to get each and every value we're not going to go through each and every column and the reason for that is because the zeroth column gets replaced with the last column so essentially we just need to do halfway right and if it goes in the ending uh that's not actually going to work uh so we just go hovered and we can just do integer Division and this is going to ignore the odd value which is completely fine because that is going to stay as it is uh cool and now let's iterate through our row so we're going to get all the row values so that's going to stay we're going to get all of them right okay cool so now what we do is we take Matrix i j and now what is the value over here going to be so let's say I is 0 we now have to get the last columns value in that same row okay so the row stays same but the column changes and essentially it's the length of the Matrix I'm going to do -1 because of the Matrix I'm going to do -1 because of the Matrix I'm going to do -1 because over here we are going to be working with the index values uh so the last index of them is the length of Matrix minus one and we're going to subtract that by the current J value we're on so if J is 1 we're going to get the last but one Matrix and so on and so forth okay and since we are swapping the values this is also so now this is going to get the value of Matrix i j and that should be it so let's submit our solution and as you can see here is the mission was accepted so thanks a lot for watching guys and do let me know if you have any questions
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
1,721 |
Hello hello guys today we are going to solve the middle challenge the question language shopping note se request what do we have to do if suppose our cake gives everyone and extent the can help you stop this node and awareness of national defense that subscribe and Prominent Personalities From This Point To Our Loot And Win From Last 29 Years To Reduce Like This Is Yes Okay Pull Officer Ujala Problem Respectively Financial Profit Account Valuable Lessons In Equal To K Soft Louis Live He To A Temple At Least Not His Name And Influence After Words with love affair pass head and other person NS2 written and now we people this function will start our organization type this remedy 999 hui railways held at least not hurt ok android ok so as we know anyone first thing before sleeping If it is a basic thing then take this liquid of subscription, if it is not done then we will perform all this operation and Hare Krishna, if this is our request then what will we do while passing them to our next and keep them together in the next to two. To my tablet se pooja work hold to account and account 2222 day he got that form updation slapped at road to hell oo ru tu ru loot continue to increase and written for X2 abs on this occasion come Pradeep works fine but latest From The Code Hai Caller Mistake Ok Accepted Question Playlist Kis Latest Rang Se Za Loot Liya Hai Hain Akshar Pet Mirchi Ek Mic Mode On 06 Ki Aap Nichein Hue Slice With Left And Call And Function Reciprocally Inch Tape Suggestion States And Pass Below Tips Number Okay, so see, at the time of making this question, we have the main motive, if we assume that the attendant is our note, while doing this, it has reached our final destination, which will be its purpose, but at this time, we have to What is to be done, what is to be done in our number 66, we will take one last step back from ours and will do this, then what will we do with what we have to do now, we will also remove this point by one step, what should we do from this type of tourists? It is understood that it means that the one which is recording our seconds from the beginning is also ours by joining the seconds from the last one. Simrely, if it will appoint on 30th then this one is the note, the last one is also our last Saturday. Appoint Karega Yes To I Hope Desh Mil Work Latest Meter Code Mein Save Ok Kha Thank You Are Yes Thank You For Watching More Videos I Hope You All Will Understand Video Jewel Ek Inquiry Den Post Comment Section Thank You Are You
|
Swapping Nodes in a Linked List
|
maximum-profit-of-operating-a-centennial-wheel
|
You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100`
|
Think simulation Note that the number of turns will never be more than 50 / 4 * n
|
Array,Simulation
|
Medium
| null |
1,905 |
thank you hello guys so yesterday we had already solved this problem count sub Islands but I felt that you know uh there are some modifications some you know more efficient ways to solve this problem hence a new video I hope you don't mind and you would enjoy this so in this video what I'm going to say that let me just you know start with a brief explanation of the problem so the problem is that we are given two grids grade 1 and grade two we have to when given two grids grade one and grade two so grade one contains zero and one and grade 2 contains also you know it's also a binary Matrix so it also contains 0 and 1. and we need to count the sub Islands so the problem name itself is Count surveillance so whenever you hear count islands and all these things then immediately DFS should come to your mind okay count Island sub Islands whatever is this DFS should come to your mind DFS should flash okay if you are asked to find the you know minimum path maximum path all those things then DFS with backtracking also will come okay so in this case definitely we are going to use DFS because we are having this counts of balance we have to find the count of the islands now let's go ahead and proceed further into the details of this problem an island is a group of ones and island is a group of ones okay connected four directionally is horizontally or vertically okay any cells outside of the grid are considered water cells so these are you know one cells and these are water cells okay these are one cells and these are water cells okay now an island is considered sub Island so see we're not just allowed to count the islands we are asked to count the sub iron so what is surveillance an island in Grid 2 an island in unit 2 this is the grade two okay this is the grade one and this is the grid two so this thing is the grid two this thing is the Grid 2 okay and this is the grid one this is the grade 2 and this is the grid one this is the Grid 2 and this is the grid one so Sublime sub Island will be occurring in the grade two not in the grid one okay so an island in Grid 2 is considered sub Island if there is an island in grade one so if this is an island in Grid one that contains all the cells that make up this island grade two so see this island is contained in this island in red one because all the cells here are there in this island see this island is contained here in this cell see this cell is not you know counted only these two things are counted with this so This cell is not counted and you see this is there this is also there but since this is connected with this bottom cell this bottom one is here as well but this is corrected with this and since this is part of this island so this is not totally connected with totally you know within this you know um this uh Island system is not within this you know a survivalent system so this one is not counted I'm going to say that for this to be counted it's all adjacent Islands you know cells should also be part of the you know uh in the grid one also but see these cells are not there you know in the grid one these cells are water cells these the corresponding cells in the grid one are water cells so they are not considered so with this thing we'll go ahead and now we will try to solve this problem fine so now we'll start so we'll take Grid 2 grade 1 grade 2 doesn't matter both have the same you know Dimensions M cross n so it doesn't matter but since we are going to operate on the Grid 2 so we have you know it's better it makes sense it uh better sense is that we should be you know dealing with grid two we should be iterating about the grid 2. now the thing is if grid one of i j is 0 and Grid 2 of I J is equal to 1. if this is 0 and this is 1 okay then what we are going to do so suppose this cell is 1 but this cell is corresponding cell over there is zero this cells are one but the corresponding cells over there in the greater one are zero so in these scenarios what we are going to do we will start one BFS so suppose the DFS starts at this cell when the DFS starts at this cell it will Traverse all these three cells okay and what we are going to do in the DFS we are going to start the DFS in the horizontal and the virtual vertical directions and will Mark all the cells as water cells will be meaning that these cells have been visited so once they are visited we should not be you know these cells will not be counted in the other cells okay so and one more thing this cell also will be you know considered as water cell uh I meant to say in this scenario because in unit one uh give it i j it is zero okay yeah so this important distinction in grade 2 i j this is 0 and this is one so we need not be bothered about this because we are going to Traverse only on given two and once we are marking all these you know uh cells which are not there uh which are not land cells in the grid one as water cells then you know then what happens that you know the number of surveillance only remain those islands which are actually there which are sub islands of the you know grid one so hope this is clear if there is any doubt please let me know so I'll just write visit grid to BFS okay and then grid i j like this and then at the end of this we'll start this count variable and since you are going to Traverse the you know graph I'm going to say the Matrix again so it makes sense that we do the things like here so now in this case what we'll do that you know this is also one and then we'll do you know plus count before I starting any you know uh any uh traversal and then afterwards you will be returning this okay and then private void grid oh I meant to say visit is red to BSS okay if row is less than zero of the rho is greater than equal to grid dot length because rho is it should be within 0 and the number of sub errors is returned by grid dot length so rho should be 0 and grid dot length minus one it should not be more than these values so all these less than zero and greater than equal to Green Dot length are outside the boundary of the grid call is less than 0 or call is greater than equal to Z of rho dot length are grid of row call is equal to zero then the term okay grid there we go call is equal to 0 and then we will take this visit red rho plus one call so we'll copy this rho minus 1 now is the term of a call plus one call minus 1 so that's it like this will do so basically what we have done that you know this is the pre-processing that we know this is the pre-processing that we know this is the pre-processing that we are handling and in the pre-processing are handling and in the pre-processing are handling and in the pre-processing what we are doing that beforehand we are marking those cells which are not there in grade one we are marking those land cells in Grid 2 which are not there in grade one because in the Final Countdown we are not concerned with those cells they are only concerned with those cells those land cells which are also land cell in the grid one okay so see when we are doing DFS when you are coming for doing DFS over here since this is also there in the grade one so we'll covers this whole island because this whole island is there in grade one so we'll Traverse this is the one Island now once we reach here so because this part is the you know once we reach here then because this part is not there in uh you know this is a water cell so we are not going to bother bothered about that and give it to so we'll be only concentrating on this is there in this so we'll counting this and since it is not horizontally and vertically or horizontally connected with any other cell see this is diagonally connected this is not horizontally or vertically corrected so that's why this is separate Island this one this particular Island where my you know Mouse is hovering this one is a separate Island and this one is also a separate Island so these two are separate Islands okay so these two are separate islands and this is once we reach over here then we are starting our because this cell is there in grade two but the cell is zero in grade one i j is equal to zero but Grid 2 i j is equal to one so this is one and this is zero so that's why we are you know doing one day first reversal and we are marking them as you know visited once you are marking them as visited so these are all you know uh water cells so in the final countdown this will be counted and these whole land cells will not be counted and that's what the answer we want so hope this is the explanation that you wanted and you know now things are clear to you so let me know and uh the final DFS thing uh you know if you see all my you know Island problems list this is the same you know uh same procedure that I have used and I thank possibly akat for teaching me this method of event traversal whatever I know is it is because of algo labs and tausif so thanks a lot to them thanks a lot and I hope this explanation is clear to everyone with this I would like to say thanks if you have any other doubts please post it in the comments thanks a lot
|
Count Sub Islands
|
design-authentication-manager
|
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`.
Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_.
**Example 1:**
**Input:** grid1 = \[\[1,1,1,0,0\],\[0,1,1,1,1\],\[0,0,0,0,0\],\[1,0,0,0,0\],\[1,1,0,1,1\]\], grid2 = \[\[1,1,1,0,0\],\[0,0,1,1,1\],\[0,1,0,0,0\],\[1,0,1,1,0\],\[0,1,0,1,0\]\]
**Output:** 3
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
**Example 2:**
**Input:** grid1 = \[\[1,0,1,0,1\],\[1,1,1,1,1\],\[0,0,0,0,0\],\[1,1,1,1,1\],\[1,0,1,0,1\]\], grid2 = \[\[0,0,0,0,0\],\[1,1,1,1,1\],\[0,1,0,1,0\],\[0,1,0,1,0\],\[1,0,0,0,1\]\]
**Output:** 2
**Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
**Constraints:**
* `m == grid1.length == grid2.length`
* `n == grid1[i].length == grid2[i].length`
* `1 <= m, n <= 500`
* `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`.
|
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
|
Hash Table,Design
|
Medium
| null |
332 |
Hello friends welcome back today we are solving a hard problem reconstruct itinerary we'll start with reading the problem statement and look at some examples to understand the problem and next we'll look at what are oian paths and use high holers algorithm to solve this problem which takes linear time o of e where e is the number of Ages and finally we'll write the python code for it let's get started we are given a list of airline tickets where tickets of I represent the departure and arrival airports of one flight where the first element is the departure airport and the second element is the arrival airport we are also given that all these tickets belong to a single person which basically means these are all the tickets a single person used on his journey and the goal of this problem is to reconstruct his itinerary or journey in order we are also given that he departs from JFK Airport hence his route must begin with JFK if there are multiple valid routes we should return the route that has the smallest lexical order when read as a single string here is an example to understand what is smaller lexical order these are the two routes we are comparing right now the first airport in both the routes are the same let's look at the second airport second Airport of Route One is LGA and the second airport of route two is LGB since a comes before being the alphabet route one has a smaller lexical order than route two the question also states that we may assume all tickets form at least one valid route and we must use all tickets once and only once now let's take a look at these two examples just to recap all these tickets are given to us in random order and the goal is to construct a route using all the tickets once and only once if there are multiple routes possible we need to return the route that has the smaller lexical order in the first example the first ticket is from mu to lhr which is this Edge second ticket is JFK to Mu which is this Edge third is s42 SJC which is this Edge fourth is lhr2 so4 which is this Edge as you can tell already it becomes easier to find the route if we can build a directed graph using all these flights where nodes are the airports and the edges are the flights themselves once we build a graph the goal is to find a route that starts from JFK and visits all these edges once and only once and in example one that route is from JFK to Mu to lhr to SFO and sjsc we visited all these edges only once and that's the output we see over here similarly in example two we start from JFK to SFO to ADL ATL to JF FK JFK to ADL and ADL to SFO that's one route that starts from JFK and visits all the edges let me write down the route here I have written down the route here but there is a second route in this graph which is JFK to ADL ATL back to JFK to sf4 to ADL ATL back to sf4 that's the second route I have written down the second route over here whenever there are multiple routes possible the problem statement says that we have to return the route that has smaller lexical order in this case route two has smaller lexical order because the second airport in route two is ADL versus second airport in Route 1 is sf4 a comes before s in the alphabet hence we return the second route which is the output over here before we look at how to solve this problem if you haven't subscribed please do because it helps us in a big way to make more content like this next let's look at what exactly are oian paths and how do they help in solving this problem an oian path in the context of a directed graph is a path that visits all the edges exactly once which is exactly what we want to solve this problem but the question is can an oian path exist in all directed graph the answer is now for the oian path to exist these three conditions have to be met where all the nodes should have the same in degree and out degree except for these two nodes out of the remaining two nodes one of them should have out degree minus IND degree equal to 1 and the last node should have the in degree minus out degree equal to 1 in this example graph these nodes have the same in degree and out degree and there's one node that has out degree minus IND degree equal to 1 and there's the last node that has IND degree minus out degree equal to one so in this graph there's definitely an aarian path but for the given question we don't need to check if an aarian path exists because the problem statement already says that there's at least one valid route so given a graph like this how do we find an Allan path can applying a plain depth for search yield andan path let's find out we always start depth for search from a node that has one more outgoing Edge than an incoming Edge in this case node a we go from A to B from B there are two possible routes we take B to C to E from E there is nowhere else to go we backtrack to C from C there is one more outgoing Edge which goes back to B but B is already in the current path so DFS does not go back to B again because it's in the current path so we don't explore this path there are no more edges left from C so we back track to B from B we take the other route now to D and from d we go back to C from C we go to E again e does not have any outgoing edges we back track to C from C we cannot take this route again back to B Because B is in the current stack so we backtrack from C to D there are no more outgoing edges from D so we backtrack to B we have explored all the edges from B so we backtrack to a so in this entire DFS we did not explore this path at all hence applying a plain DFS will not yield the aarian path what changes can we make to the DFS so that we can explore this path as well which brings us to high holders algorithm higher holers algorithm is based on depth first search algorithm we just saw but the only difference is instead of adding the node to the output as soon as we get to it we add the node to the front of the output once all its outgoing edges are explored let's see how this works we start from a as before we don't add a to the output just yet because we have to wait until all its outgoing edges are explored before adding it to the output so we go from A to B from B there are two outgoing edges to C or D let's say we go to C from C we got to E from E there are no more outgoing edges we add e to the output and backtrack to C I've added e to the output over here from C there is another outgoing Edge to B so we go to B from B There is a second outgoing H to D so we go from B to D and D to C since there are no more outgoing edges from C we add C to the output and backtrack to D I've added C to the output over here from D there are no more outgoing edges so we backtrack to B and add D to the output I've added D to the output over here from B there are no more outgoing edges so we backtrack to C and add B to the output I've have added B to the output over here again from C there are no more outgoing edges we backtrack to B and add C to the output I've added C to the output over here we're back at B again and there are no more outgoing edges so we backtrack to a and add B to the output I've added B to the output over here similarly there are no more outgoing edges from a so we add a to the output and our algorithm ends here I've added a to the output over here and this is a valid oian path but there is another oian path that goes from A to B to d to C to B to C and C to e this is the second oian path but we still written the first oian path because if we look at the first difference between these two paths which is c and d and c comes before D in the alphabet so we return the first path so that's the final algorithm to solve this problem we start from gfk and run higher holers algorithm to find the oian PATH which is the itary or the route that starts from JFK and visits all the edges or takes all the flights the runtime of this algorithm is speak of e where e is the number of edges because we visit each Edge only once in this algorithm let's write the python code for this algorithm first we start by building a graph which is an adjacency list gal to default dictionary which is a list then we go through all the tickets and add them to the ad jcy list for a comma B in tickets a is the from airport and B is the to airport so we need to add B to the adjacency list of a so G of a append B since we need to return the final route that has the smaller lexical order if we sort these nodes in the adjacency list then we would be exploring the nodes that has the smaller lexical order anyway so let's sort these notes in the adjacency list for key comma value in G do items where V is the list of nodes we just have to sort V Next let's define the output array to store the result and then we start the and then we have to start the traversal from the JFK Airport because the problem states that we need to start our journey from JFK airport so let's start Traverse from JFK let's define this function Traverse airport we need to explore all the outgoing edges of this airport once and only once so while G of airport we need to get its neighboring airport which is Nei equal to G of airport pop zero we're popping the first airport in the adjacency list which has the smaller lexical order anyway and we are popping this from the adjacent list because we can only use this Edge once then we call Traverse on this neighboring airport once we are done exploring all these outgoing edges we need to add airport to the result. append airport only thing we need to do before returning this result is we need to reverse this result array because instead of adding this air to the front of the array we are appending it to the back so we just have to reverse it before returning insert and then we return this resulting route let's try to run the code as you can see the submission goes through I hope this video was helpful thanks for taking time to watch the video take care
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
476 |
hello everyone to this question she's number complement given a positive integer output its complement number the complement strategy is flip the bits of binary representation means first we have to convert this digit to its binary and then when its complement now we will understand this in pen and paper so yeah number is five so now we convert five it's binary digit so five binary is 1 0 1 so now we perform one is compliment 1 0 1 is complement means we can but if it is 1 then we convert it 0 and 0 to 1 so means opposite so now so we return 0 1 zeros in decimal so 0 1 0 decimal is 2 so answer is 2 so basically this is very simple problem you have to convert it into binary the decimal number to binary and then you have to power from one is complement and then you have to again convert it to decimal that's all so 23 binary is 1 0 1 so when it's complement this is you convert 1 to 0 and 0 again 0 so 0 to 1 if it is 0 then we'll convert it so now 0 1 0 means 8 so if it is convert this then it is so now we will move to the coding part first we will take a result variable and store our one is complement do it and then convert our number decimal form to binary this inside this fall would convert a decimal number to binary and then we check its digit in binary it is a if it is 0 then we store in result as one cause will Papa Mia when is complement and if it is one then we store it as zero as I already explained in our explanation and finally we return the result decimal form the convert result in decimal now we run this code and submit it got accepted if you liked this video please give me a thumbs up if you are new to this channel please consider subscribe and don't forget to give a like on thank you for watching this video
|
Number Complement
|
number-complement
|
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `num`, return _its complement_.
**Example 1:**
**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
**Example 2:**
**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
**Constraints:**
* `1 <= num < 231`
**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
| null |
Bit Manipulation
|
Easy
| null |
299 |
hey guys today we're gonna be looking at question 299 elite code called bulls and cows uh it's a fun little question maybe a little bit on the easier side but i think it's interesting nonetheless and we're talking about so let's go through it you are playing the following bulls and cows game with your friend you write down a number and ask your friend to guess what the number is each time your friend makes a guess you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position and we call these bulls and how many digits match the secret number but located in the wrong position and we call these cows your friend will use successive guesses and hands to eventually derive the secret number okay so they're asking us to write a function to return a hint according to the secret number and the friend's guess and we're going to use a to indicate bulls and b to indicate cows note that both secret number and friends guess may contain duplicate digits okay so the logic here is probably best explained through some examples so let's just go through some of those let's start with example one so the input they give us uh the secret code as one eight zero seven and we guess seven eight one zero all right so how many bulls and cows do you have um this eight is in the correct location so that's a bull and we have no more balls because everything else is in the wrong position but the seven one and zero they're all present in the secret code but they're just in the wrong spot so they're all cows so we have one bull three cows the bull is the eight the cows are the zero one and the seven that one's kind of easy but let's do example two so secret code one two three and the guess is zero one now the correct output is one bull one cow okay so let's see how they got there so yeah this one is in the correct spot that's undeniably a bull so there's our bowl but then nothing else is in the right spot so then we look at okay how many cows do we have okay here's where it gets maybe a little confusing is because if you look at this one and the last one the third and the fourth character in yes you could make the same argument for each that okay this character is in the wrong spot but it exists in secret key okay but they can't both be cows and that just goes back to the details of the question um a little nuance right if we say this one is a cow okay so this one's in the wrong spot it kind of consumes the corresponding digit in secret that lets it be a cow so we can't say so once we use up this one and say this one's a cow we can't also say this one's a cow because technically there's no more ones left to give it cowship weird word but whatever okay so yeah they explain here the first one and the friends guess is a bull so this one's the bull right and then the second or third one is a cow but not both only one so that's going to make its way into our solution somehow that once we say something is either a bull or a cow it kind of consumes that corresponding token in the secret code okay and it notes here that we may assume that the secret number and our friends guess only contain digits and their lengths are always going to be equal that's kind of nice okay i'm actually going to give you one more example that i made up on my own just to maybe make a certain point a little more obvious before we start okay so that this example should illustrate why it's best i think there's probably a way you could do it in just one pass but the solution i'm going to use uses two passes of both lists and the first pass is going to address all the bulls and the second one is going to address the cows and the reason we do bowls first is because okay let's just look at secret and guess here so the answer is going to be yeah we have one bowl and zero cows because this one is in the correct spot and then this one is kind of consumed by that bull match sorry i'll just do this so that it lines up nicely so this one in secret kind of gets consumed by this character and so this one has no other one to pair up with to become a cow so if we were to do cows first or if we were to just do this in order in one pass if we were to first address this two and this one and go oh yeah this one here it's not in the right spot but it exists in secret so okay it's a cow if we erroneously say that this thing is a cow then once we get to the next one we'll go oh wait no it's actually a bull so then we have to take away this one cow and we kind of have to do things in a clunky order so it makes better sense if we just do all the bulls first take a breather and then go back and do all the cows okay so let's call this hopefully that made things a little bit more straightforward okay i will i'll make it a bit bigger okay first order of business is we have to make a counter object um for the secret key so pretty much just telling us for every single element in secret what is the count of that um element or character or digit whatever you want to call it um yeah so let's just do that so let's call it bag because it's kind of a bag object so to speak we import oops counter method and yeah we just take secret so if i just run this and show you what it looks like let's print out bag so secret is going to be the string 1807 and counter is just going to show us that we have one eight one zero and one seven okay and the keys here are characters instead of digits that's actually going to be fine that's gonna work for our purposes but if you're really identical about that picky and you want them to be characters i think we can just map into the secret here and then that'll turn them all into integer data types instead of characters yeah let's just keep it a secret though so that sorry let's keep it as character hashes just for simplicity just so the code's as simple as possible okay so there's our bag now what okay we have to make counts for bulls and cows and we initialize both as zero before we start okay and now we're going to go through secret and guess zipped together right we're going to go through them go back here we're going to go through them kind of pairwise so the first element of secret in the first one i guess and then the second l secret the second element of yes or getting ahead of myself here etc so on and so forth the way we do that is we can just iterate a b and zip secret guess so on the first iteration of this loop i'll go back to this example here a is going to be 1 b is going to be 7. second iteration of the loop a is going to be 8 b is going to be 8. so on and so forth so a is going to be the character in secret b is going to be the character and gus so if they're the same right this is going to be oops it's gonna be our bulls pass i'll make that a little more verbose no never mind i'm not gonna do that okay for a be in zip secret guess okay if a is equal to b then we have a bull for sure right and that token in secret gets consumed it can't be used anymore sorry i'll go up here so in the case where a is eight and b is eight and we found a bull we consume this eight so nothing else can match up to it no potential cow so we go um bag at b it's going to decrement by one okay as far as our bowls that's that should get our um the correct kind of bowls and now we go through again once we've done that and adjusted this counter object we can process the cows so it's the exact same but this time it's if they're not the same because we don't want to recount bulls again so for a cow they're not going to be the same but the count at the count of the character and the thing we're guessing if there's one of them at least one of them remaining in the bag in the counter object then it's a cow so then we increment cows and again we consume yeah we keep this again we consume the that token in the gas okay so that's our bulls pass there's our cows pass this is a two pass solution and now we just have to open our answer in uh the string format that they like this a and b a representing bulls b representing cal's format so there's a couple ways to do that you could use string format or you could use f strings i'll show you both so if we just do string format it's going to be what is it going to be that those little placeholders and then you go to format and then we put in bulls and cows okay let's try that out okay but this you can actually be more succinct than this if you just use f strings i've switched over to f strings kind of recently and they're a little easier to write out so you just go what am i doing not one it's going to be bulls cows b and that's it i think okay let's make sure we didn't mess up anywhere i think i just got a bad roll on that one because i've used the same solution before and it's been nowhere near that high as long as i'm not making a big mistake anywhere yeah um anyways that's it that's how i solved it and what i think is an intuitive way just doing the bulls first approach um anyway yeah the runtime complexity of this is going to be well o of 2n but that's still going to be linear so it's an on solution where n is the length of the um well either the secret or the guest they say it's going to be the same so the length of this list is going to be the runtime complexity space complexity um i guess this is it's just going to be the cardinality of the number of tokens possible in each key so i mean they say here it's gonna be digits so yeah it's gonna be constant space we're good to go there anyway yeah hope this was helpful um let me know in the comments if you have anything to add to this problem or solution and anyway yeah bye
|
Bulls and Cows
|
bulls-and-cows
|
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
* The number of "bulls ", which are digits in the guess that are in the correct position.
* The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_.
The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits.
**Example 1:**
**Input:** secret = "1807 ", guess = "7810 "
**Output:** "1A3B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1807 "
|
"7810 "
**Example 2:**
**Input:** secret = "1123 ", guess = "0111 "
**Output:** "1A1B "
**Explanation:** Bulls are connected with a '|' and cows are underlined:
"1123 " "1123 "
| or |
"0111 " "0111 "
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
**Constraints:**
* `1 <= secret.length, guess.length <= 1000`
* `secret.length == guess.length`
* `secret` and `guess` consist of digits only.
| null |
Hash Table,String,Counting
|
Medium
| null |
152 |
hello everyone welcome back today we will be solving one liquid question maximum product sub array given an energy array Norms find a sub array that has the largest product and return the product sub array is a contiguous non-empty sequence of the element within non-empty sequence of the element within non-empty sequence of the element within the array let's take a look at the example here we have the array 2 3 negative 2 and 4. the answer is 6 because 2 multiplied by 3 is 6 and that is the maximum product that we can get from this array how do we solve this problem if all the elements are positive it will be easy because we can just multiply every element in this array and get the maximum product however there are negative numbers in this array and that can become very tricky because if we have a positive number or the largest number here and multiply with the negative number it can flip to be a negative number in contrast if we have a negative number and we multiply with another negative number it can flip to be a positive number and it also can be the brand new maximum number here in other words we have to keep track of the mean so far and the max so far because the mean can flip to be the mass and the max can flip to be the mean and our formula is we want to compare between the current num multiply with the max over or the current num itself because sometime the current numbers is positive number and the previous products can be the negative numbers so we should just take the maximum which is the positive or sometime the current num multiply with the mean so far because the mean so far here can be the negative and the current num can also be the negative so sometimes the negative multiplied with the negative can be the brand new maximum number so this is our formula and we want to apply this formula to both mean so far and the max solver but for the mean so far we want to get the mean and the max so far we're going to get the max let's go through our example here I will initialize the mean so far to become a first element in this array and the max so far also the first element in this array and we also want to get a hold of the result so the result also initialize with the first element in this array then we want to loop from the first element here while looping through the entire array we will use our formula here the mean so far will be 2 the Maxwell 5 will be also 2 and the result also two in the formula the current num is negative 5 multiply with 2 the Max sofa and also the current number negative 5 and the last one negative 5 multiplied with two so if you want to take the max this one is negative 10 this one is also negative 10 and the max here is negative 5 so the max Alpha is negative 5. and the mean so far is negative 10. and for the result we want to get the maximum of the max so far so this is negative 5. let's move to the next element negative two the current number is negative two the max so far is negative five and the current number is negative two and this is negative two multiplied with negative 10 that means so far so this becomes 10 negative 2 and 20. the mean so far will be negative two and the max so far will be 20. so the result is 20. let's move to the next element negative four here negative 4 multiply with Max Alpha is 20. and the current number here is negative four here's negative 4 multiply with negative two so this is become negative eighty negative four and eight the mean will be negative 80 the max will be 8. and the results still 20 because 20 is bigger than 8. next let's move to the last element three here three multiply with the max so far is eight this is three and this is three multiplied with negative 80. and we can see this one is 24 the 23 this one is negative 240 so the mean so far will be negative 2 40. the max profile will be 24 and the result will be 24 and this is our final answer the maximum product that we can get from this array is 24. let's code our solution I will initialize the max over with the first element also the mean so far with the first element in the array and also the result with the first element in the array we will start looping from the first index or the second element until the end of the array while looping we will get the current Max by using math.max between the Max by using math.max between the Max by using math.max between the current number multiply with Max over the current number itself or the current number multiply with the Min so far let me get some space here next for the current mean we will be using the same formula we said we want to get the Min of this formula and next we want to update our Max become the current Max so far and the mean so far become the current min then we also want to update the result to be math.max between the previous to be math.max between the previous to be math.max between the previous result and the max so far here and finally we can turn the result let's check the result here we see that we Loop through the entire array so our implementation for the time complexity is oauth in and for the space is oauth 1 because we don't use any extra space at all hope you guys enjoyed it see you next time
|
Maximum Product Subarray
|
maximum-product-subarray
|
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.
**Example 2:**
**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Dynamic Programming
|
Medium
|
53,198,238,628,713
|
222 |
Hello Guys Software Co * C Problem From Hello Guys Software Co * C Problem From Hello Guys Software Co * C Problem From List Code Called Account Number Notes in a Complete Denial Tree O Pure Problem Statement Simple Governor Complete Binary Counter Number of Units So You Must Be Knowing What is the Complete Binary Tree Yesterday morning the complete binary tree came out Successful Binary Tree Till Fab - One Level End Binary Tree Till Fab - One Level End Binary Tree Till Fab - One Level End Lastly I Will Not Subha Field From Left To Right Choose A Complete Building And This Is Not Completed Because It Is Not From Fluid To Fab So Simple Solution B-2 Account All Notes So Simple Solution B-2 Account All Notes So Simple Solution B-2 Account All Notes By Traveling The Tree And Will take over from times you can we do something better can we use some property of complimentary water purifier viewer flight video plz subscribe hello viewers calculate high end values from do the power - 183 lunar months will be 7 from do the power - 183 lunar months will be 7 from do the power - 183 lunar months will be 7 time complexity to the number of units In Food Additive That Log In To Subscribe To That Giving This Complaint By Ministry Will Just Need To Extract Observatories Thoughts Fool Vanities Let's See How Will You Be Daru Naveen Ko Left And Calculate Died And Similarly You Right And Calculate Par Height To Left Side Is Equal to Floor and It Should Tree to Remember Did n't Heed to Tree Just Calculating Fiber Glue Subscribe This Point is Not Tree to Avoid You Too to Two to That Sister I Will Again Finder Left Height of Left Branch Left Most French and Right Height Of The White Most Bench And Drive See Weather Left And Right Yes Dia Absolutely Adams It Is Full Hindi Dubbed According To Can Directly Account Total Number Of Notes In Directions Tree On 200 Will Return Seven Hair Because That Utensil - And Noida To Right Children Because That Utensil - And Noida To Right Children Because That Utensil - And Noida To Right Children Noble Account Left and Right Sensitive Call 100 Unit Solution Two Minus One Day 300 From a Great 72 From Where You Will Get 300 Seats Will Return Seven Plus 3 Plus One Two Cash Withdrawal Account Channel Also Total Number of Balwant Let's Take Another Example Will Come To Know Which Left And Right Leg First 40 Ishwari Lutkar To The Children In Nine Welcome To Left Children And Will Again Calculate Left And Right Tomorrow Morning Left With 3 And Right Will B C D2 Gave Notice In Advance Tomorrow Morning Loan To The Children Welcome A Distant Since Left and Right Side Call I Can Count Number of Votes for This Tree and Returned 3 I 9 May Vacation Will Come Here and Will Check Weather Left and Right to Recall Dare Not So Will Again and Will Go to Laptop These Children So That You can see ultimately welcome find what is right most mode at last level a site from here your trident one that will return to that and spirit of two plus three less 113 love you to right side it will find left and right so call 100 Vitamin Hair 300 A Total Note Will Be A6 Plus 3 Plus One Latest 10 I Let See The Time Complexity of This Approach A Guru Can See That Wear Calculating Height Many Times So To-Do That Wear Calculating Height Many Times So To-Do That Wear Calculating Height Many Times So To-Do List Same Login Time To Calculate Height One Time Know How Many Times And Calculating Hit The Depend Upon One Time Getting Right Most Mode Of The Last Level Should Invest Which Might Go To Lalit Bhanot So It Will Also Take Login Such Time Cholesterol Bhi Login Into Login Flash Lights To Code Surya IF Functions The Main Function Sundh Checking Main Left And Right The Means Of This Is The Tree To And Calculating Is Part And Support This Village And Research Is Not Vehicle Checking Measures Is Equal To And Effective And Us Of Doctor Idli Calculator Number Note Subscribe My Channel To subscribe
|
Count Complete Tree Nodes
|
count-complete-tree-nodes
|
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.
According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
Design an algorithm that runs in less than `O(n)` time complexity.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** 6
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[1\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5 * 104]`.
* `0 <= Node.val <= 5 * 104`
* The tree is guaranteed to be **complete**.
| null |
Binary Search,Tree,Depth-First Search,Binary Tree
|
Medium
|
270
|
238 |
hey everyone welcome back and let's write some more neat code today so today let's solve product of array except itself so this is another problem from the blind 75 list as you can see it's over here product breaks itself so i'm going to be adding that video solution today and we're getting one step closer to having every problem in this entire list filled out so for this problem we're given an input array of integers nums and we want to return an output array for every single number that we're given where for each value in the input array nums we're basically multiplying every single number except that value and then returning that as the result for example in this example you can see we're given 1 two three four so for example for this value one we would want to return the multiplication the product of every other value so for these three values the product would be two times three times four that's going to be 24 so for the first value in the output we're going to put 24. similarly for the second value we want to multiply every value in nums except for this value so that's going to be 1 times 3 times 4 that's going to be 12 so the second value in the output array is going to be 12. now the hard part about this problem is basically the restrictions that they give us so we have to solve this problem in big o of n time and we have to do it without using the division operator it would be really easy if we could use the division operator because what we could basically do is take the product of all of these values and then and we know that would basically be 24 so if we wanted the first value so if we wanted 24 we would take this total product and divide it by one right that would give us 24 if we wanted what the second value would be we would take the entire product 24 which would be all of this and then divide it by 2 which would give us 12 which would be over here right because the division is basically taking the entire product of the entire thing without multiplying by this dividing this would do exactly that but we are not allowed to use the division operator so if we wanted the product of every value in here except the three one way we can break it down is basically get the product of every value before three in the input array and get every and get the product of every value after three in the array and then multiply these two values together and then that's going to give us uh the value that we would want to put in this position in our result so it would be helpful for us if we want to do that for every single value in the input array if we basically just compute the prefix product for every single position in the input array right and then put it in a prefix array and since we're also going to be wanting the product of values after it would also be helpful if we computed the postfix product of every single position in the entire input array right and we can compute both of these in big o of n time it's a pretty simple algorithm right we basically start at the first position okay this is going to be one so if we're adding this value we're just going to take the previous value and multiply it by two so this is going to be two similarly we're gonna take two multiply it by three we're gonna get six here four multiply it by six we're going to get 24 here and for post fix we're basically going to do the exact same thing and do it in reverse order so here we would get four here we would get three times four here we would get two times 12 and then here we just get one times 24 which is just going to still be 24. now for every single values for example 1 we would want the prefix of every value before it now since there are no values before we can just say okay the prefix for that is just going to be a default value of 1 to keep it neutral and so we'd also want the postfix of every value that comes after it we can get that in the position to the right of 1. so we'd want to multiply those together so 1 times 24. so in the output for this we would get 24. that makes sense because if you multiply all these together except for this one we do get 24 and then we just repeat the exact same process for every value so over here we'd want the prefix of the values that come before it and we'd want the postfix of the values that come after it so 1 times 12 is just going to be 12 that's going to be the output again repeat the same thing for here the prefix is 2 postfix is 4. we're going to get 8 as the output that makes sense if you take 24 if you take every value in here multiply it except for three we do get eight and similarly for this four we'd want the prefix six and the postfix there are no so we just assume that there's a one over here so six times one this would be the output so this is a very valid solution this is a big of n time solution we're not using any division operator but the downside is this is also big o of n memory but we can actually use this idea because what they tell us is the output array does not count as extra memory so we actually don't need these prefix and postfix arrays because we can compute these and we can compute these prefixes and postfixes and then store them in our output array and that is going to end up making things easier for us because we're not going to have to use this extra postfix prefix memory so what we're going to do is we're going to do two passes on our input array nums first we're going to start at the beginning and then go all the way to the end basically computing every single prefix for the input array and then storing the prefix so for example the prefix of this is going to be stored over here right because that prefix is needed to compute uh the result for this position and so at that point what we're going to say is every prefix is going to be in the output basically the prefix over here is going to be stored in the second position the prefix over here is going to be stored here the prefix from this is going to be stored here and remember how for the first position there is no prefix so we're going to put a default value of 1 over here and then after that we're going to do a pass going from the end to the beginning computing every post fix so for example this post fix and then in the result we're already going to have the prefix stored over here this prefix right the first two values is going to be stored over here so what we're going to do is we're going to take this prefix and multiply it by whatever is in this position that's what's going to give us the result that we want for this position so let's start off so far the prefix that we're going to be at is just going to be the default value of one so we're going to put a one over here then we're going to multiply it by what value comes over here one times one is going to stay one so we're going to leave our prefix as it is now we're going to be at the second position so what we're going to do is take our prefix of which it basically tells us the prefix up until this point we're going to take that and then put it in the output so 1 is going to be here and then we're going to take the value that we just reached multiply by the prefix so now the prefix is going to be a 2. so now we're going to be at the third position so what we're going to do is take our prefix up until this point and go ahead and put it in the output so 2 is going to be placed in the output then we're going to take the 3 and then multiply it by 2 that's going to give us a 6 for the prefix so far so at this point we're going to take our prefix 6 it tells us the prefix up until this point so we're going to take it put it in the output 6 is going to be put in the last position then we're going to multiply 4 by 6 which is going to give us 24 but that value 24 is not going to be put anywhere because clearly we have run out of room to put it so we don't need to store it in the output so now we've visited every single value from the beginning to the end computing the prefixes and then putting them in the output array so now we're going to start at the end and go to the beginning and do the exact same thing except we're going to be doing post fixes which are basically starting from the end of the input array and computing the products once again the post fix is initially going to be set to 1 so what we're going to do is take the 1 which tells us the post fix up until this point basically an empty thing and that makes sense because for this value 4 we would want the prefix of it as well as the postfix but there is no postfix so that's just going to be a one so we can take that one multiply it by six so six is going to stay the same so that's gonna be the result value for this position but then we're gonna take four and multiply it by the one in our postfix so four so our postfix is now going to be four so we visited this position now we're going to be at this second position so we're going to take our postfix which tells us the postfix up until this point and then multiply by the two that's in this position so 4 times 2 is going to give us an 8 for the output value then we can take this value 3 multiply it by our 4 which is going to give us a 12. so now we visited this value now we're at the next value two so we're going to take our postfix up until this point multiply it by the one that's here so this is now going to be a 12 and we can also take the two and multiply it by 12 which is going to give us 24 which tells us the postfix up until this point which is going to be useful for us because we know that if we want to get the product for this position we're going to need that postfix so we can take that postfix 24 multiply it by the one that's over here so this is just going to be a 24 now and you know that's the entire result so we basically did the exact same thing that we did with our prefix and post fix arrays but this case we did it without using the extra memory and we ended up arriving at the exact same result so it was linear time complexity big o of one memory complexity now let's jump into the code so the first thing we're going to do is create a result output array so this technically does not count as extra memory in the context of this problem i'm just going to give each position an initial value of 1 and we want this to be the length of the input array so we can multiply it by the length of nums so first we're going to be doing the prefixes so i am going to initialize prefix as 1 and then we're going to go through every position in our input array so for each position in our result output array i we're going to take that prefix and then just put it in that position i right and then after we've done that is when we're going to take the posit the input array value nums of i and multiply it by whatever the prefix happens to be so prefix is just going to be multiplied by this value so that's how we're going to be computing the prefixes as we iterate through the input array nums and we're going to be storing the prefixes in the result output array after we've done that we're going to do the exact same thing with the postfix array well almost the exact same thing so we're going to start at the end of the input array and then go up until the beginning and that's how you can do this in python and so in this case the result of i we're not just going to be simply storing the postfix value because we know that would end up overwriting in the result whatever the prefix we stored was what we're going to be doing with the postfix is we're going to be multiplying it by the value that's already in results because that's simply multiplying the prefix and the postfix together once we've done that we know we do have to continuously update the postfix so with postfix we're just going to multiply it by whatever value happens to be in the input array nums and once that is done we're actually done with the entire problem then we can just return the output array result so this is pretty much the most efficient way to solve this problem as you can see best memory complexity best time complexity as well so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Product of Array Except Self
|
product-of-array-except-self
|
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
You must write an algorithm that runs in `O(n)` time and without using the division operation.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[24,12,8,6\]
**Example 2:**
**Input:** nums = \[-1,1,0,-3,3\]
**Output:** \[0,0,9,0,0\]
**Constraints:**
* `2 <= nums.length <= 105`
* `-30 <= nums[i] <= 30`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
**Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
| null |
Array,Prefix Sum
|
Medium
|
42,152,265,2267
|
345 |
That Welcome Back Points Today We Are Going To Solve Liquid Problem 2235 Will Travel From This Question Is A Specific In Google Sheets Care And It's Just Click On Over Water Question Description And We Will Discuss How Would Want To Solve This Question To Write Function At Its Cost rings input and reverse only give winners of string fact should have much to example share so let's take the example after and from here is the input string practice given to a so you can see in distinctive in the voice of physical ago you later Arrest Sudharak Top Character Show Accuracy Arise Warning Ko Is The Wall And Is The Way Tried So What The Question Singh Bittu Have To Reverse Gear And In Also Aaye Shoot Vikram Half Character Soft Character Shoot Vikram The Last Character Should Welcome Clear Institute Of Aaye Din Inspector will remain in the middle and where Tiku How to put first character is right 100 Basically it is reverse The order of the various types of the question is Sonu How they are going to solve this question from so What they are going to do it Is the will read this inputstream character per character and will check give the character hui yaar tu yaar on is first basically tight to and list 2 directions example like character directors and it can explain you all the same time how they are doing the implementation of will Start Doing Character Package Dropped In For Loop Slow First Will Read And Soul Is Not 151 Friday Or Like So Will Just Go To The Next Character But Some Mix Kar Actor Will Go On This Is So Wherever You See Now Is One Of The World Clear That IF so I will just create one list and they will put director in our list right and in this will keep doing now will go to and you will go to teams will go to see 340 not including your earliest record you will not waste the time when You Reach To Expert Novel Show Where Did So* Very Expert Novel Show Where Did So* Very Expert Novel Show Where Did So* Very Stride And You Will Keep Going To Is Not Love Will Give Went So E Will Again He Did Not Come Into Power Least 100 Ko Koi Have Formed At Least To Front Hindi String Are Right Now What We Will Do It Is Will Augment The Traitor String From Beginning To End And Thursday's A Plate Chest Drama Show Will Attract Now Again From Beginning To And So She Does Not Have Been Serving Food Like Viewers Stringbuilder Flight Stringbuilder Chief Values And Will Just Happen If It Is Not Give Will Just Kept Values And Will Just Happen If It Is Not Give Will Just Kept Values And Will Just Happen If It Is Not Give Will Just Kept Under Character Additive Candy Crush Him Printer Character Edison Now War Next Character High Is Aaye Shok Uther Check Effective 1st Same Way That This Was What We Will Do It Is Will Start Reading From The End Of The Least The Are To you lucky pointer clear and they will put this point a character sirvi putki here right hand work has not and tcatc they are not doing anything for anti vikas 2009 value sahi na hui rich or right heard that when they will also put and pointer ear After two years we and point to next quite clear software going to in reverse direction hindi and english right now with food and hair soft and here from the list and win again mode and pointer to here right where going in reverse direction should e miss you e Will Just That Sort Of A Will And When You Come To Me Two Years Now Going To Broke This Air Tight Instituted Alive The Should Replace Limited Income 34 Poetry Going To Solve The Reverse Values Of String 1600 Solve The Reverse Values Of String 1600 Solve The Reverse Values Of String 1600 Code Implementation Tattoo Have So Abroad Is Created List Of Directors Hits Of Least Known Here For Celebrating Viruddh Breast Rings Character Mein Character And Chatting Effective Wedding Date In To Our List With Character Sudesh And Tough And Also Identified Sunidhi Chauhan His Shoulder Friend Got A Pain Is The Number Of Directors In Spring Gas Right Now you have created one variable called lists of - 20 pointed to the last character in the of - 20 pointed to the last character in the of - 20 pointed to the last character in the list right hand will create a string builder clear Now again you are iterating that so much like trading the itna talking tom alter of any number of characters in these directions Char laung again with kapil character per character and whenever e was just pending list last character and two decrement will be used with last character and will give - - - - - character and will give - - - - - - this is the time complexity of subscribe and subscribe the world has increased in characters That Recording Character So You Can See Hidden Gold Drop In These 10 Complexity As Well As Time Complexity Should Listen Them Due To Here And Mix Or Reduced Taxes And Example That You Have Actually The Institute I To Job Vacancy New Year Greeting The Character Result Here Software Getting Rewards To Observe Fasting On Submit Solution In 15 Per Cent In Channel Subscribe Sure You Can Solve Reverse Values Of Problems Values Of Problems Values Of Problems And Problems In Google Someshwar You Understand Problem The Time Complexity Vighna Solution Laya Times Create Like Video Related To Subscribe Playlist One Act Example subscribe to plus size is that java interview planets difficult flip your preparing for java interview or telephonic interview or coding interview so please check the market and if you like this video please subscribe to our channel and hit the like button your subscription will be like really Thankful For Channel Tourists To More People Like You Worship Him For A Job Interview Please Subscribe And Thanks For Watching 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
|
211 |
hi everyone it's Soren today we have a problem where we need to design a data structure that supports adding a new words and finding a string that matches to the previously added string so basically finding those words so in our case we are going to implement a class word dictionary and it will have two functions add word function which is returning void we're just adding the word to our data structure and uh we also have a function search which is returning Boolean depending or on whether that word exist in our dictionary or not so also we have another requirement if the word that we are searching right if it contains dot it means that it can be replaced by any it can be matched by any character for example in case let's say that we have added math to our dictionary and we are searching for the dot and AD that it should return true because the first character doesn't matter right it can be any character and also we are given an input we are adding we are calling the ad function three times we're initializing our object and we are calling the add function three times we are adding bat that and the mat these three words to our dictionary and then we are calling search function on these three words right so for example the first one is the pad right pad does not exist in our dictionary so we are returning false for this case so how about the bad yeah bad exist in our dictionary so we are returning true for that and how about the next one is that the dot and AD so all the words that we have in dictionary it matches our search so we are returning true in this case the last one is the it starts with the B we have that and the two dots which means that the rest of the character it doesn't matter the size should be three so we have that word and we are returning true also in this case Okay the data structure that we are going to use in this K is try and let's implement the try so how we are going to implement the try so let's visualize that so the root of the our try doesn't matter so we are going to use just add the dash here and we need to add three words to our try right bat that and mat by requirements so let's take the first example that we had so we are first adding bat right we are adding B so we are adding character by character we are adding a and we are adding d right we are adding D so also the next one is that right we are adding D here D a and uh d right that uh the next one is the last word that we have is mat right mat so mat M A and D right so why the TR data structure is convenient because for every character right there could be no more than the 26 possibilities for example meaning that the letters of the alphabet so for example let's say that we are we want to add the we want to add one more word here we want to add one more word to our dictionary let's say that outside of our example right so let's say we want to add map right so we are adding map here we are adding P here right and it's our we are adding that to our dictionary how about the next one let's say that we want to add one more right we want to add mole right mole to our dictionary so in that case we are adding l and the L right we are adding mole also to our dictionary so searching for the word it's um searching for the word is much convenient in case of the TR data structure so that's why we are using try in this case so let's take our example our examples which are our example is pad our example is bad our example is dot add right and our example is B and the two dots so let's search for those words in our dictionary so first one for the P right so we are searching for the P there is no character that starts with the p with the first letter right so we are searching character by character there is no word that starts with the p so we are returning false in this case how about the bad for the bad so we are searching for the first word for the first letter it exist so now let's compare the second one this one and this one right yeah they are equal and how about the last one D is equals to D yes it equals and we are returning true for this case how about the dot and at so we can go we are going one by one starting from the first letter of the alphabet right the we are starting with the B and uh in this case so we are comparing again so that it can be any letter so we are taking this one right it can be any letter so we are taking we are going to the next character does it match yes it does so we are going to the next character and we are comparing the next character this equals to D yes it equals so we are returning true in this case also how about the last one is the B it should start with the B so we are again going to this Branch right where it starts with the B and um we are going to the B is equals yeah B is equals to B we have the b in our dictionary so we are going to the next one and it doesn't matter if we have two letters in our dictionary so it doesn't matter it could be not for example not bad it could be something like um some something like a b let's say right let's say it could be B let's say that this one does not exist right and we have here B right e and e so we have a b here and uh so in this case we are again returning for this scenario for this particular scenario we are returning true okay uh let's take a look how exactly we are implementing our try the first thing that we are doing here we are adding our in our class try node which has three Fields first one is that the data where we're storing our data uh the next one is the Boolean is and it represent that is it the complete word or not so for example let's say that we are adding map we added first character M we added a and the last one we are adding P when we are adding P we are marking this as true because at that point it's a complete word and another one is a children with the array of trode with the size of 26 one for each character of the alphabet right then we are initializing our word dictionary uh we are not in our Constructor we are passing no arguments here and the next one is we are implementing our ad word function so what we are passing here we are passing word and uh now we are starting to add that to our try let's say that we have here map we are adding map here right so we are adding character by character first we are adding M then we are adding a then we are adding P so let's say we are adding M now we are checking so this is the first word that we are adding to our try we are checking in our try does that M exist in our try no it does not exist why we are minus a because zero a we are going to store why we are taking minus a character here because zero in the zero we are going to store a character in the one we are going to store B character and so on in the index one index zero we are going to store a index B we are index one we are going to store B character index two we are going to store C character and so on so we are checking if the M exist in our try so it if it does not then what we do we are creating a new trode and U so we are setting that our current children so at M right so we are creating a new trode for it because it does not exist if it exists let's say that we have added a another word earlier let's say that starts with the m let's say men right we have added earlier and in that case M already exist in our try so we are just pointing that to the m so we are pointing to the m now then we are adding each character after adding M now we are pointing to M so now we are the next one is we are adding a right here we are adding a here and when we are adding a we are again checking that if it is exist or not because in our case since we are adding map for the first time a also does not exist so we are also creating a new TR note for the A and the same we are doing for the P once we add the P so we the last character right so we are as we exit this Loop we have added all characters we are adding e end for the p as true because this is complete word at this point it's a complete word okay this is our add word function and the next one is our search function what we do in our search function so we are calling we're creating another search function and the passing because we are going to pass three arguments and we are going to call that me function or method recursively so that's why we are creating another search method and we are passing word we are passing index and we are passing our root so what is the base case for us let's mark it here as a base case right what's the base case is that so if let's say that our word is the word that we are searching is we have added map right we the word we are searching is AP so by default we can have by the requirement we can have a DOT which represents any character right so let's say we are searching for the A and the P so if we if our index is equals to three so which means that we have recursively call three times and we increased our index it equals to our word length then in that case we are checking if our root is n so which means that if that is a complete word for the P right it's going to be true so we are checking if that is true then in that case we are returning true so and if the index is equals to word length and the is and is not equals to true then in that case we are returning false so this is our base cases and now let's look at the recursive call of the function what's the recursive call so at this point what we are doing here we are so first we are checking that if it's a DOT if it's a dot it means that it can be replaced by any character we are skipping that character and we are checking any children that is not equals to null let's say that we are for the AP right so let's say that we have some other word right let's say that we have added earlier let's say bad we and we have two words we have bad and we have map that we have added to our dictionary so we first we are what we are going to first check for the B right if it's not equals to null so B is not equals to null so index one right is not equals to null and we are recursively calling and uh recursively checking other indexes so at this point we don't check is it exactly equals to our index or not right so because it's a DOT so it can be any index so it's it can be any character so we are just recursively calling and um if that is true so if that returns us true so let's say that if this function return us true right so then in that case we are going to return true also here so how about the next case is that when the character is not equals to dot but equals to character so in that case we are exactly checking that if that character exist in our if that character is not null so if it's null right then we are not so if that character does not exist let's say that we are searching for something like let's say we are searching for something like table here right table and we are checking for the first character t does not it does not exist in our try right so what we are going to do we are just going to return false because T is that does not exist so if it exist let's say that we are searching for A and P not for table for A and P we are going to or let's say we are searching for B right so we first checking that the B exists then we are recursive the calling function then we are checking that is a exist then we are recursive the calling function and so on if it does not so again like in case of the table right we are returning false here okay so this is the two implementation of our Tri data structure what's the time and space complexity of this solution time complexity is of n right n is being the size of our word added word and the same for the space complexity in the worst case scenario we are going to add all the characters right let's say that the in some cases we may not have we may not add all the characters because some characters may exist already but in the worst case we're going to add all characters so it's going to be also off ofn okay um that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
|
Design Add and Search Words Data Structure
|
design-add-and-search-words-data-structure
|
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the `WordDictionary` class:
* `WordDictionary()` Initializes the object.
* `void addWord(word)` Adds `word` to the data structure, it can be matched later.
* `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter.
**Example:**
**Input**
\[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\]
\[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\]
**Output**
\[null,null,null,null,false,true,true,true\]
**Explanation**
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord( "bad ");
wordDictionary.addWord( "dad ");
wordDictionary.addWord( "mad ");
wordDictionary.search( "pad "); // return False
wordDictionary.search( "bad "); // return True
wordDictionary.search( ".ad "); // return True
wordDictionary.search( "b.. "); // return True
**Constraints:**
* `1 <= word.length <= 25`
* `word` in `addWord` consists of lowercase English letters.
* `word` in `search` consist of `'.'` or lowercase English letters.
* There will be at most `2` dots in `word` for `search` queries.
* At most `104` calls will be made to `addWord` and `search`.
|
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
|
String,Depth-First Search,Design,Trie
|
Medium
|
208,746
|
207 |
Hello hello guys welcome to years and I will be solving dat no problem miding challenge hai mera total number of course you need to take a little from zero to name try minus one sum try mein hai prerequisites for example to take 2012 fast track courts vich Express Repair 2017 Total Number of Voters List of It's Possible for You to All Courses in Acquisition Two Cords Broken 1000's Not Possible for this Question is a Plot to Kill Shot Played and Ball Straight Graph of Every Day You Will Take You to You Comes before all sorts i just only when others on cycle in agra a is network through its type in c how they can find a graph cycle a person used business speech which studied for each course how many to city sp liquid form definition is inevitable for length Printed To Whole Deficit Which Will Oo Will Find Adventures Not Visited And Have No Prerequisite Left In Courts Are Defined Devi Marg And Educated And Decrement Vyankat All Is All Values In Courses True Value All Values In Courses True Value All Values In Courses True Value Return Forms Its Yadav Gautam And That Samagra Look Like Share And See How To Front Will Regret Over 1000 Similarly Placid One Will Continue Doing And Tell You Have Traveled A Prerequisite All Courses Will Address Soon She Visited The Relief Length Equal To Record All Will Play With Logic Paun In You Looking For Frequent Flyer Finding Armitage Binu Prerequisite Not Show This Applies To Information Will Take Off Mercedes Benz We Can Do Loop Condition Special Mid Valley In Courses For The 98100 Not Visited Subscribe This Video Not Here A Video Course That Astrological Following Statement Will Foster Mother And Visit Day Will Decrement Person To On With This Depends Upon In This Case Course One Will Now Make Flowers To True This Completes Air Force Station Is Like A True Way Continue Registration Will Benefit Slice 250 Looters Toys With A Smooth Condition In That Encroachment To Set S Facebook Condition Hundredth Play All Three Statements Will Update Your Visit True Decrement Valley Force 2 And Effective True This Completes A Contribution Will Continue Till The Ravana Visit Notes With You Are Requested To That A Different Language Update On Truth Labs Condition Subah Pred Chalu Nau Will Check All Notes In Course Is Hai Vyasya Which Signifies Mist Is Loot Na Graph And Hans Way Daily Difficulties Underground Iberian Value Not Equal To Zero Way Return Forms As Vacancy Old Values 800 Rupa Forms As Vacancy Old Values 800 Rupa Forms As Vacancy Old Values 800 Rupa Ka Note Se Example Which Cycle Course Road Pension One And Course One Depend 0 Winnie Slider Code Hair And Fluid And Definition Of Vegetarian Vinod Check Fuel Satisfied Bodh Condition S Bodh Do Not Satisfied With Red Through Winter In Which Give Any Value Is 90 In Course School Jo Hai Value Way Return False Advertisement Space Complexities To Whip Lassi Where Is The Number Of Course And Which Number For Preschoolers Give Exact Same Pattern Tomato And Share A Link With Java Coding Description Clock Of Thanks For Watching The Video Check Water Into A Job Link Description Below Effect Video Please Like Share And Subscribe Our Channel Check Out Mein Yadav Videos From Interview Problems Video call me with your problems and comment it in the comment section.
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
238 |
hey guys Greg here and let's solve product of array except self so we're given an integer array nums and we need to return an answer array such that each answer at I is equal to the product of all elements of nums except nums at I and so this spot should be replaced by the multiplication of the other ones which is 2 * 3 * 4 which is 24 this which is 2 * 3 * 4 which is 24 this which is 2 * 3 * 4 which is 24 this second spot should be replaced by 1 * 3 second spot should be replaced by 1 * 3 second spot should be replaced by 1 * 3 * 4 which is 12 this should be replaced * 4 which is 12 this should be replaced * 4 which is 12 this should be replaced by 1 * 2 * 4 as it is and this 1 * 2 * 3 by 1 * 2 * 4 as it is and this 1 * 2 * 3 by 1 * 2 * 4 as it is and this 1 * 2 * 3 so it's simply each location is just the multiplication of all of the other numbers in the array and this example just shows that you can have negative numbers as well as zero if you had any zeros in there you're going to get a lot of zeros in the answer if there's a zero here well it's going to make all of the other spots zero except itself cuz this is the only spot where you're not actually including zero in the multiplication hence that's the only spot where you get a non-zero number so spot where you get a non-zero number so spot where you get a non-zero number so the brute force method for this is going to yield an O of n^2 so solution and it to yield an O of n^2 so solution and it to yield an O of n^2 so solution and it basically does exactly what your mind would do which is okay we need to fill up each of the positions in the array let's think about filling each of them up one at a time so we're going to fill up the first one okay well we'll set I equal to the first spot and then we'll send J through all of the indices and you just need to carry on this multiplication such that you don't include the same position so here when J is equal to I we actually don't include that here we get our multiplication it's going to get built up as two and then we multiply it by three so it's going to turn into six and then we again multiply it by four and so we're going to get 24 as the answer right here and you could do that through all the indices I then over to here and we would send J through the other indices so it' be 1 * well not the other indices so it' be 1 * well not the other indices so it' be 1 * well not that position times 3 * 4 and you could that position times 3 * 4 and you could that position times 3 * 4 and you could get that equal to 12 you could code that but it's going to be a very slow Brute Force solution so we're not going to use that now here's where we're going to get an O of n solution so basically notice something is that if you're looking at say this position right here where if you were to multiply all of this stuff together and multiply all of this stuff together well you're going to get 1 and 12 and then you can simply just multiply 1 and 12 and then Therefore your position here your answer is actually going to be 12 the multiplication operation works like this you can multiply all the stuff to the left and all the stuff to the right and then you can just multiply those things together to get your original answer and this is actually going to yield an O of n solution let me show you how now we're going to build up two auxiliary arrays we're going to build up a left and right array so starting with left what is this well it's basically at this position I want this to be the multiplication of all the stuff that's to the left of it and let's just pretend that there's a one outside of both sides because then if you multiply something by one it doesn't really matter so the idea behind this is if you have a left and right array where this is all the stuff that's to the left and this is all the stuff that's to the right well the answer is just going to be the multiplication of those two things as we just specified so we'll set up this multiplier which starts at one and so we're going to immediately place this as the multiplier in this thing's position all the stuff to the left of it the multiplication of that is just one now once we're here we actually need to multiply by this value and that's going to be one so that doesn't really change anything if you look over here we're going to immediately plug this in as our multiplier and this is still the multiplication of all the stuff to the left and simply just 1 * 1 but now left and simply just 1 * 1 but now left and simply just 1 * 1 but now things get interesting because we need to multiply our multiplier by two so we get of course two and now that we have that we immediately plug this in as our multiplier and notice that here from this thing's point of view the multiplication of all the stuff to the left of it's 2 * 1 * 1 which is 2 and left of it's 2 * 1 * 1 which is 2 and left of it's 2 * 1 * 1 which is 2 and once we're here we need to multiply this by 3 so we'll get 2 * 3 which is equal by 3 so we'll get 2 * 3 which is equal by 3 so we'll get 2 * 3 which is equal to 6 we move over here and we plug this in now technically you might multiply our multiplier by four but we're not actually going to use this anymore because we are going to go outside the array so notice that this left array each of these positions it's always the multiplication of all the stuff to the left now we can do the right array by pretty much the same thing we would just go backwards because we'd start from the right we'd have a multiplier starting at one and we'd immediately place this as one but now we have a four over here and so we multiply it by four so now our multiplier is four we immediately plug this in right here but now we need to multiply it by three I'm going to stop writing it down but it's 12 so we have 12 we multiply by two and that gets 24 we have 24 then we're outside of the array okay and then as we said this is actually really easy from here our full answer array which is literally what we want to return is just each of these positions multiplied by each other okay so we can do that by just going through the array one more time that's 24 that's 12 that is 8 and that is six okay and if you were to check that is definitely the right answer okay now why is this an O of n solution well it's O of n because we go through the array once to build up the left array we can go through backwards to build up the right array and then one more time we go through the array so we basically go through the array three times and three is just o of 3 * n it's still o of N and is just o of 3 * n it's still o of N and is just o of 3 * n it's still o of N and so that is going to be a linear algorithm okay so here's our code we're going to start our left multiplier equal to one that's basically outside we know it's just going to start at one and we're also going to get the right multiplier equal to one as well that way we can actually kind of just go through the array once and in a clever way we can build up the left and right arrays at the same time if we get n is the length of the nums we'll get our L array which I'm going to call LR and that is equal to we're just going to initialize it to n many zeros for now and then our array is going to be exactly the same thing and then we can just go through this array once here to build up both arrays so we do for I in the range of N and you can actually get the last index by doing J is equal to IUS 1 okay by last I don't always mean the very last so if you had an array like 1 2 3 4 what's going to happen here is on the first iteration we'll have I as this and we'll have J as this on the last one and then when I goes up it'll actually make J go over here and then when I goes over here J will be over here when I is here J is over here and they both step out of Bounds at the same time so basically it's just going forwards and backwards at the same time forwards is I and backwards is J so as we said we're immediately going to make the value for the array equal to the multiplier so L array at I is immediately going to be the L molt I guess this is called RR I feel like a pirate at J so that way we're using the right index is equal to R malt okay and then we just need to multiply both of those by the current element they're looking at L malt is going to times equals the nums at I and can you think of what we do for our malt is going to times equals the nums at J from there we have both our L and R arrays built up we just need to return and there's multiple ways to do this but I like to do L * R for L and this but I like to do L * R for L and this but I like to do L * R for L and R in the zip of l r and r it's very funny to say but basically we iterate both of the arrays at the exact same time okay and then we just make each position the multiplication of those two values so again each position is the multiplication of all the stuff that's to the left and all the stuff that's to the right and if we are to run this solution we can see that it works so the runtime the time complexity for this algorithm is big go of n cuz we really just as you see here we go through the array and here we just go through them like one more time we just go through both LR and RR that's just going to be o of n the space complexity for this is actually not optimal this is actually o of N and there's actually a very clever uh constant solution which I encourage you to check out yourself I think it's really cool but uh not really in the scope for this question because it's kind of tricky so drop a like if this was helpful and have a great day guys bye-bye
|
Product of Array Except Self
|
product-of-array-except-self
|
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
You must write an algorithm that runs in `O(n)` time and without using the division operation.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[24,12,8,6\]
**Example 2:**
**Input:** nums = \[-1,1,0,-3,3\]
**Output:** \[0,0,9,0,0\]
**Constraints:**
* `2 <= nums.length <= 105`
* `-30 <= nums[i] <= 30`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
**Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
| null |
Array,Prefix Sum
|
Medium
|
42,152,265,2267
|
1,011 |
hi everyone in this video we are going to solve a problem the problem is capacity to ship packages within d-days capacity to ship packages within d-days capacity to ship packages within d-days and the problem number is one zero all right so first of all we are going to clearly understand what this problem says after that we are going to move to the logic part and after that we're going to implement our logs you can see plus by Javan Python programming language all right so now let's see what this problem says a conveyor belt has a packages that must be shift from one port to another within D days so there is a conveyor belt and that has to load some packages from one port to another within given days fine after that their ith package is on the conveyor belt has a weight of heights so guys here we are giving the Bates array and the beta is nothing but the given the weights of all the packages so you can the first package is has a weird one the second package has a way to and third package has a weight 3 and so on up to this right each days we load the ship with packages on the conveyor belt so every day or we can say every day we have to load the ship with this given packages in the on the conveyor belt right in the order given by bits so that means we can't load first we load this package then we can't again directly we have to load second package after that we have to load third package and so on up to this right in the given order all right now this is clear we may not load more weight than maximum weight capacity of the ship now guys there is a limit of weight like if let's say weight the limit is 5 that means we can't load more than five weight on the conveyor belt right so we can load only that number of package or maybe single packages whose weight is less than or equal to five if the weight coming more than five then we can't load that number of package only completed well fine now we have to return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within delays so guys it says that we have to return the minimum weight we have to put on the conveyor belt so that we can ship all these packages so we can load all these packages and we can shift from one port to another in the given days right so what it means if you are not getting this from this particular lines then try to understand with the example one right so here we are giving the ds5 that means we have to deliver or we have to transfer we have to load all these packages and we have to ship all these packages from one port to another let's say from this port to this port and in that five or less than five days fine so now a conveyor belt is there let's say this is conveyor belt when we have to how many number of we can say weight we can put on their convertible and every day it is going to load only that particular number of Weights so if I say we are going to load the output is 50 right so let's say we are going to load 15 only right so you can see the first day it gonna load all these packages five because the sum of all these packages is nothing but 15 right package right so now my error is nothing but this much right all right now I can say I have to I have left with four days I have to load all these packages within less than or equal to four days right so next day I load let's say six and seven I can't load six seven eight because if I load these three we can say package then my sum is nothing but 21 right and you can see I put a maximum weight 15 for now right so I have put them in 50 so I can load this much fine and I have left in the three days so now I in the next day I can load this one I'm left with two days and next day I can loot nine and next day I can load 10 right so I took five days to load all these things right but I took a bit minimum weight that is 50 right so if I take a less than 15 let's say 14 or 10 then you can see that I can't it is not possible to load all these packages to other from one port to another in just five days it gonna take more than five days right so the minimum weight was 15 right all right so now guys how we can solve this particular problem now let's see I hope now you understood this problem let's see the logic part how we can zoom this particular problem so guys for this you need to understand a graph right note I'm not saying talking about graph data structure I'm going to say I'm taking about a graph like uh I'm going to draw a graph or we can say I'm going to write chart all right so now let's make a graph with a we can say weight here's the weight here's a DS right now guys this is a let's say a graph I let me make it a more 4b8 so fine so this is w and this is D fine now guys I am saying that this is nothing but let's say it is 100 and starting from 10 why starting from 10 because I know the maximum value is nothing but 10 in this example one right so I can at Max uh if I have to transfer one package only then I need to at least give a bit of that conveyor belt is 10 right because I can't break the package I'm it's not like the weight is 10 and I have put on the maximum limit or minimum limit five eight so I am going to break this 2 10 into two part it's not like you have to transfer the package without breaking it right so the minimum weight I have to put to a conveyor belt is 10 right fine and the maximum weight it can be the sum of all the speeds that is 55 because I can it's possible that I can transfer all these packages in just one days right by giving a maximum weight 55. so then I put it 100 for now but for us let's say 55 right fine now guys tell me if I am taking a bit let's say 55 only then how many days it gonna take one day right so if I say this is one this is two this is three this is four this is 5 this is six right and let's keep it more so this is seven I have this much killative why I make a small because I don't want to make it less than this all right now guys I have seven this is going to seven and eight is going to ten two hundred five so if I took a 55 then my uh number of days is gonna take only one right it is going to transfer all the package in one day right if we take days let's say 14 then assume that it gonna take because it gonna take uh let's say three days right if I take 15 then we already know that it's gonna take five right but if you're gonna do I'm gonna take 10 you're gonna take six so can't you see that guys this is gonna be a decreasing or strictly decreasing we're strictly decreasing what we can see but a decreasing graph right and we know that if by it is so we know that if we are taking a bit 40 and if it is possible to uh transfer all the package in less than five days or equal to five days then we know that if we take maximum if we take more than 50 or 40 50 or 55 or 100 then we know that is going to take less than five it's going to take not going to take more than five right definitely gonna take either less than or equal to this 45 so here you know that if 15 is going to take five days right if I take any weight more than 15 we know that it also going to take less than or equal to five it's not going to take more than five right so that is the basically logic we are getting a monotonic graph that means if the bait is going to increase the number of days is going to be decreased right so this is a monitoring graph and here if it is monotonic then we can use definitely binary search remember this point guys if we are having a monotonic graph that means we can use a binary search algorithm because here we have something strictly increasing or decreasing right so this is monotonic decreasing graph fine so we know that we are going to use urban Assets Now guys let's try to drag on this code and see why how my message is going to help it right so as we know that low is nothing but 10 and high is nothing 100 right so we are going to use a minus size so it's going to give him we can say mean value mid low plus I divided by 2 right so if we do low plus I divided by 2 10 plus 55 divided by 2 I'm going to take High 55 so it is going to take a 65 divided by 2 right so that is maximum 32. so 32 will come like here and for this 32 our let's say d is going to take 4 right assuming I'm assuming that 4. so I know that for I have a now two part 10 to 32. and 32 to 55 so I know that the in this part 32 to 55 definitely I'm going to get a lesson I'm not gonna take more than this particular days four days right so if it is taking four days then all this made between 32 to 55 it could not also take less than or equal to four but it's not going to take more than four right but my condition is that I can take maximum five days right so I just need to find a bait which can take five days or less than five days the least minimum wage right so I can say 32 is the answer right it is my answer but is there any weight exit on the left side so I am going to decrement my high I'm going to say now my should be I should be this one right 31 32 minus 1 31 and this one I can say this is now nothing but now my search space would be like this earlier it was whole but now it is going to be like this and now I have to try to find is there any value mid value exist who's who can solve my who can transfer all the data Within These given days right so now I am going to decrement high and I am going to move to the left side but if it is not the possible let's say 32 is going to take us 10 days right so now I know that 32 is not possible case so I am going to increment or I'm gonna move to the right side I'm gonna say just find out is there any between this 32 and 55 which can take a less than or equal to my given days so I'm if I'm getting a value which is greater than my days then I have to move to the right side otherwise I have to move to the left side so that was the basically binary set now guys there's a problem also how will you gonna find whether 32 is going to take how many days so we need to use a function in for Mid value that tell me how many days it's going to take for this particular value right so everything we are going to see in limitation but for this part for this logic part you must know what algorithm we are going to using and how this algorithm gonna work and I believe we must know right now okay by now you understood that why we need to use a bunny set and how it's going to solve a problem in just logo and time complexity and N logo and we are finding whether how many days it will not take right so let's move to the implementation part and there we are going to understand how we can do this particular thing right so let's see first of all with the Python programming language now let's move to the lead code all right so here it gonna let me reload this okay fine now guys what we are going to do we are going to say uh first of all we're gonna find a low so I find a low now guys inside of low what will be the low value it should be the maximum value of 8 right fine because at least we need to take that particular weight now after that once we find a low we have to find high as well that is going to be sum of weight right fine once we find high and low we're going to use a binary size that is while low less than equal to high we're going to find a mid that is going to be low plus High divided by 2 right once we find a medium we are going to check a function we are going to use a function right so function name let's say I put it is true and if it is true for Mid right if it is true from it that means we have to move high to low because if we have to move high and that is if it is true that means we can say that is possible so we can say high should be equal to Mid minus 1 move left side and try to find whether this is also a possible answer or not and if it is not the case then you have to move low right low should we meet plus one fine and we are going to use is true function as well so we have to Define that function so what I am going to I'm going to say here let's say Define or Define is true and here is going to take a mid value and we are going to say count is zero count is nothing but let's say d is 0. right now we need just one day right and my sum is totally zero right so we're going to Traverse for Value in me uh in weights and we are going to say d plus equal to or we can say uh S Plus equal to Value right we are going to adding the values right if my S is greater than my mid means it took uh it is greater than the maximum value we can say bit which we have just right now 2 right so if it is greater than our minimum weight then we can say sum is going to be equal to value and you have to increase the day we need one more day to pass this value or we can say pass this particular packages right and then we are going to say return if D is less than or equal to d s means we are able to solve or we are able to transfer all the packages within date given days right so if it is true then it is going to return true otherwise it is going to return fast so if it is returning to that means we have to move to the left side if it is not written into that means we have to move to the right side once we are done this we are going to return our Loop right so let's say to run this code see whether we are getting any error or node so you can see that all the desks are passed now let's try to submit this code and guys you can see that it's successfully submitted right so I hope you understood this problem now let's move to the another programming language that is nothing but C plus side all right so in C plus what we are going to do first of all we have to find a low so we can say low is nothing but we can use a one function that is Max element and we can pass away it's let's say let me fight weights could begin polite and we can say right polite and we can say right polite and we can say right once we find uh here we have to use a pointer artistic as well because this is going to give us it right once we are done with this we are going to find high as well that is going to be nothing but some of the whole weight so we can say use another function reduce and we can pass bait store we can and wait stored and right fine once we are done with this we are going to use a while miss Vanessa while low is less than equal to high so let me get high okay and we are going to say just find a mid value that is going to be low Plus High divided by 2 right fine all right now once we are done with this Mid Valley we are going to use the one function that is nothing but Keystone right so we are going to say is true if it is true for Mid and L we are going to use a function so we have to pass here in C plus weights so we are going to pass the weights and we are going to pass let me write a bit and here we are going to pass mid value as well as this right so if it is true that means where we have to move the left side so we are going to say I should be mid minus 1 but if you denote the case then low should be with Plus 1. I have this matriculate you so we are done with this we are going to return low and we just left with one function we have to Define this H2 function so let's see here I'm going to say it is going to give a Boolean value so Bool is true and here we are going to pass nothing but first of all a vector so let me uh Vector let me write a vector and here I'm going to say enter and let's say weights fine and after that I'm going to take mid and after that I am going to take this right so here I'm going to say first of all I have to Define int D which is nothing but 1 and I have to find some which is nothing but here right so I'm going to say 4 in data on weights I'm going to say add your S Plus equal to data if your s is greater than your mid value so what we can do we can say s is equal to data and our day should be implemented right so we can do press it plus once we are done this we are going to say written just number of days should be less than this right so your day should be less than or equal to day if it is the same case that means it is going to return to otherwise it is going to return fast now let's say to run this code and see whether we are getting any error or not and you can see that all the tests are passed so let's try to submit this code and it also gets submitted right so now let's move to the next programming language that is nothing but Java right so let me take Java and here guys first of all we are going to find nothing here we have to use a manually because in Java I would not able to find out the embed function which can return a maximum or some value right so I'm going to say into low is going to be initially nothing but 0 and in let's say higher also zero all right so let me Define here high that is nothing but 0. fine now guys once we are done with this let me write a zero what happened so all right so we are going to Traverse over this so for yield data in weights let me activate and here I'm going to say uh what I can say low hypotic maximum so I can say math dot Max no comma data right so I have to take maximum value from weights and another thing which we have to take is nothing but a high which is going to be some like High plus equal to data so once we are done this we go to low and I we're going to use a while again low less than equal to 1 is such all right so once we are done this we are going to find a mid value so I can say intermittent is going to be low plus I definite plus High okay and it is going to be divided by 2 fine once we have done this we are going to use is function H2 function which is going to use a weights which also going to take a mid so let me let him meet and we're just going to take this and if it is written true that means we have to move to the left side so we can say high should be equal to 8 minus 1 otherwise we have to move to the right side so we can say low is going to be mid Plus 1. so let me add this so once we are done this we are going to return nothing but low right and here we have to Define this function as well so I'm going to say probably Boolean and I give a function name is true and this is going to take into it let me it waits and it's going to take intimate in place as well right so after that what we can see we can say into D which is nothing but one let me write here one and enter s which is nothing but kinetic sum so it is going to be nothing but 0. so we are going to say enter data in weights all right so we're gonna say something we're going to say S Plus equal to data and if s is greater than mean it then we can Define s is equal to data and we can say count uh your day should be incremented after that you have to return just T should be less than equal to days if it is the case that means it is true right so now let's say to run this code and see whether it's submitting your node so first let's check it right so you can see all the test case are passed so now let's try to submit this code and here are so it successfully gets submitted I hope you now you understood the problem you understood why we use a binary set and you understood the logic part as well and if you have any kind of doubt you can access in the comment section I'm always there to help you if you learn something new in this video don't forget to hit the like button and subscribe my channel meet you in the next video
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
309 |
welcome to july's leeco challenge today's problem is best time to buy and sell stock with cooldown say you're given an array for which the ith element is the price of a given stock on day i design an algorithm to find the maximum profit you may complete as many transactions as you like with the following restrictions you may not engage in multiple transactions and after you sell your stock you cannot buy stock on the next day so that's the cooldown period is a hard problem and i have to apologize in advance because this isn't a solution that i came up with i looked it up and it's one that i don't even completely understand but i'll do my best to explain and see you know what we can get from that so here's the approach we want to do a dynamic programming solution and because there's this condition of the cooldown we need to have two states one for calculating the maximum amount of profit that we could have while we are holding a stock and one for the maximum amount of profit that we could have for when we're flat when we're not holding anything and the reason for that is that's going to allow us to code the logic for these constraints and i'll show you as we start coding this out the first thing we want to do is say well if we have an empty array we'll just return zero because there's no profit we can make let's start by initializing two dp arrays and one for the maximum amount of profit on each day when we're in the state of holding a stock so when we bought something and this for now we'll just say zero for in range of length of prices and we're actually going to have to add one here and i'll show you why in a bit now these two arrays are going to basically be like a state representation of what we could do at each day so first thing i want to do is initialize the very first day and keep in mind that i've made an extra spot there as a freebie so the very first day is actually going to be represented by the second element index one so on the very first day if we were to buy a stock what's the maximum amount of profit that we could have made well if we want to get into the business position of buying a stock the only maximum amount of profit we could have possibly made is actually whatever the stock that we just bought at was and it's going to be negative because we bought that stock so we're losing that money so that's it like if we want to get into the position of state of holding something we have to buy the stock at this day and we're going to be at a negative profit and that's that now on the first day if we want to be in the position of flat well that's going to be zero because we don't having to sell anyway so that's just all there is to that now for every price we're going to use the index point for range of length of prices but we want to start at one because we've already initialized for the very first um holding not hold okay so for hold what's going to be the maximum amount of profits okay so on this particular day if we want to get into position of hold there's two ways that we could have been in this position right either we've already bought from some previous day and we're not doing anything we're just staying flat we're just not making any action so the maximum amount of profit is going to be whatever was the profit from yesterday right otherwise uh it's going to be the price at which we buy today so to represent that we can say hold is going to be hold i and we're going to say plus 1 because we want to represent the um actually start with the third day here because we need yesterday's date yesterday's max profit and we actually need two days before um to calculate for the cooldown period as well and that's the reason we have this plus one here so we want to get the max of either whatever was our profit from being held yesterday or we're going to buy today so that's going to be the profit of not hold of i minus one subtracted by the prices of today and whatever is the max between those two that's what we want to represent as our max profit now for the knot hold we're gonna do something similar but it's a little bit different in that uh if we want to be in a not hold position either it's the max profit from before we were not held so that's going to be not hold i or it's going to be the full position from previous day plus the prices of today now at the very end we want to be in a flat position right so that's going to just be the not hold position and we want to return the last element from that array and that should be the maximum profit so let's run that let's see if we're getting the right answer it looks like we are so let's submit that and there so that is accepted uh we could optimize the solution a little bit and use constant space it's a little bit tricky to do that but i guess i can show you how you could just comment this out and instead of using an array we'll just use a variable say okay this is going to be hold and not hold and we'll need one more we'll need one representing the cooldown as well so to do that we can just be pretty similar except we would start in the beginning and we get the max of hold or not hold minus prices that's still the same here though we'll say the max of not hold but we'll get the max of the cooldown and the cooldown is going to be represented by the um not hold i believe plus prices i'm sorry that's not right it's hold plus price is i so we want to return between these two whatever the max is between the cooldown and the not hold so let me make sure i did that right uh hmm looks like my thing froze uh it looks like that's worked let's go ahead and submit that and there we go so this would be optimized for space but the reason these arrays could help is to track the progress of what's going on otherwise it's kind of hard to follow so that's the solution um you know this is a hard problem and i wish i could spend more time on it to understand it better explain it better because it's one of those things that i don't think comes naturally um i would definitely look into this more but i just don't have time today it's something that i might come back to so thanks for watching my channel i appreciate it and remember do not trust me i know nothing
|
Best Time to Buy and Sell Stock with Cooldown
|
best-time-to-buy-and-sell-stock-with-cooldown
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
121,122
|
33 |
hey what's up guys and quite hear I do testing coding stuff on twitch and YouTube check the description for all my information I do the premium Li code problems on patreon and if you join my discord and reach out to me I try to get back to everyone this is a problem called search in a rotated sorted array it is very similar to one of my favourite problems on per amp which is shifted array search it's actually exactly the same in this problem what we're doing is we are given a sorted array in ascending order it is rotated at some pivot unknown to you beforehand so 0 1 2 3 4 5 6 7 gets rotated so that you it eventually becomes 4 5 6 7 0 1 2 so what's happening is it's getting rotated to the right a few times like 4 times and it goes you know 7 gets put to the front the 6 gets put to the front the 5 then the 4 and what we're doing is we're kind of just searching we're doing a regular binary search but you could see it's no it is sorted and it gets shifted so it's no longer sorted it's a it is if you unshifted than it is or unrotated it is sorted but the problem is that binary search the normal implementation doesn't work for finding a number unless the array is sorted so how are we gonna be able to do this it's basically just find the element so if you don't find it return negative 1 no duplicates exist and yeah we just have to do it in log of n time so we have to binary search in this like I said is just like one of my favorite print problems it's the same thing the array is shifted they call it shifted in this one and you have to find the number and what you do here in this pram plan is you find the pivot you find the point at which the array starts and you use binary search to do this we want to use a modified version of binary search to find where this array was shifted so we want to find the smallest element this pivot point so that we know we can just check against the first element and up to that pivot point or the firt or the pivot point to the end and check which side to search on for example if we find the pivot point is here and we have that index we can check ok are we looking for a 1 okay is one between this element in the last element of the array okay we'll search on this side or is one between you know the first element up to the element right before the pivot then we would search on the left so that's pretty much the idea here we could start to code it out but the main thing is we're doing a modified binary search to find the smallest element because then we can really just treat it as a sorted array check if the element which side this search do a regular binary search on okay so let's get started first if nums the array that we're given is equal to null or nums doubt length is equal to zero there's nothing to search through this is a crap array that we're given so we'll just do that then we'll set up a regular binary search type thing where you just set the left equal to 0 and the right equal the numbers doubt length minus 1 our condition will be well left is less than right in our goal here is to have these boundaries meet at the index of the smallest element so left and right will break this loop will break when we found the smallest element in the array so we calculate the midpoint just like we normally do left plus writes - left normally do left plus writes - left normally do left plus writes - left / - this is just halfway point if you / - this is just halfway point if you / - this is just halfway point if you calculate it's we do it like this for integer overflow if nums of midpoints is greater than nums of right this is the modified binary search part we will make left equal the midpoint plus 1 else we will make write equal the midpoint and what this is checking is okay is the middle element we have this array that it's been rotated is the middle element of this array is it greater than the element all the way to the right because in a sword ray all the elements to the right are always greater right for example if you're looking at the middle of this the element to the right is always greater than the middle element right so if this happens that's pretty peculiar so that's kind of weird and that's a good scenario for us to start to narrow down our search because for example in this if we're checking 7 if 7 is greater than 2 well that's kind of weird that the element at the end is smaller if it's a sorted array so we can start to narrow down our search space by setting the boundary to left equals midpoint plus 1 and we do this because this means that we do midpoint plus 1 because this means that the middle element for sure is not the smallest since this element is group the element to the right is less than it so we know that there's something smaller so we can do midpoint plus 1 not just a midpoint the other one we account for less than or equal to so if numbers a midpoint is less than or equal to numbers of right that's normal so we can just start to narrow down our search base to the left half of the array so that's it when this loop breaks out we can't our left index 4 in this example our loop will break when left is at the smallest index so left would it be at 0 1 2 3 4 in this case so left would be 4 and we would know that's the smallest element in the array okay so we'll set a variable there we'll say the starting point of our array if it was sorted we'll be left and then we will reset our boundaries to do a regular binary search now so we'll say left is 0 and right is equal to num style and minus 1 again we don't have to type them because they were typed up there now we'll do a regular binary search and which side of the array do we want to binary search on though that's like the main question here and we'll decide that so forget this for a second how do we know which side to binary search on well if target is greater than or equal to num zve start so wherever the starting index wherever the smallest element is in less than or equal to numbs and target is less than or head sorry and target is less than or equal to num zve right well then we have perfect boundaries this is a sorted version right here we want to search for the target within these boundaries we can just set left equal to start wherever start is you know we can just do our binary search between those if it's between them then we'll search between them and it's all sorted between this those pairs of indices so that's fine otherwise if it's not well then we don't want to set our left boundary to start we want to set our right boundary to start so that we search on the other side of the array and that's what I was explaining at the beginning we find the smallest index the smallest elements index and then we know that if we're looking for a number between 0 & 2 looking for a number between 0 & 2 looking for a number between 0 & 2 well we could search on this side if we're looking for a number that is greater than 2 and then we could just look on the other side so that's pretty much the idea here so it's just a normal binary search from this point on and I love this problem I think it's a really good I think this is a great interview problem this has come up in an interview for me and I liked this interview problem a lot so it's not too difficult it shows you know what you're doing so if nums of midpoint is equal to target return midpoint because we found the target this is just a regular binary search numbers of midpoints it's less than target well then targets on the right side right target's greater than what we're looking at so we want to say the left is equal to midpoint plus 1 I'm just explaining binary search now though and otherwise it's gonna be on the target is less than numsa midpoint or equal to so we're gonna do num since equal to a midpoint minus 1 and then we're just going to return negative 1 I don't even know if I made a mistake this time I usually make one mistake per video so we'll see I made no mistakes this is history in the making guys so that's the idea here thank you for watching I didn't fullscreen the freaking screen but hopefully you guys can deal with that I'm sorry thank you all for watching find the smallest index and then choose which side to sort on because after you know the smallest index you know that it's sorted from one side to another and then from this the beginning to that index so that's the main idea thank you for watching I appreciate you guys I love you guys I you know freaking thank you
|
Search in Rotated Sorted Array
|
search-in-rotated-sorted-array
|
There is an integer array `nums` sorted in ascending order (with **distinct** values).
Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= 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,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`.
Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 0
**Output:** 4
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\], target = 3
**Output:** -1
**Example 3:**
**Input:** nums = \[1\], target = 0
**Output:** -1
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* All values of `nums` are **unique**.
* `nums` is an ascending array that is possibly rotated.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Medium
|
81,153,2273
|
863 |
hey guys this is josh from lead dev where we explain programming questions as simple concise as we can today we'll be talking about the problem o nodes distance k in binary tree this is a popular question asked by amazon facebook and google we're given a binary tree with a root node root a target node and an integer value k the goal is that we want to return a list of all value of nodes that are k away from our given target node and the answer can be returned in any order so what does that mean in example one let's just say we're given this tree our target is and then our k is 2 meaning that we want to find all nodes that are 2 away from our target node in this example that is from 5 and 2 away from it is if you go down 2 you can get seven and you get four but you can also go up to three and then down one to one and that would be our other input you know binary problems if you want to solve them we have to use recursion now remember our target and that we have two ants three answers which is seven four and one because they are a distance of two away from our target like all binary tree problems we start from our node and then we explore the left child and our right child until we find our target node once we find our target node we actually have to start doing something more complicated because this problem requires us to find the k distance not just of child nodes we also have to find possible cadences of parent nodes we need to do a couple things the simple part is we need to continue searching downwards to see if we have k nodes apart so what we might do is we would just search down here so this is plus one and then we just pass a number down we continue incrementing it so plus two and two whenever we had a value that equals our k value then we know we had an answer so that's how we find seven four what's more interesting though is how do we go back up because binary trees only have a link to their child nodes not back with their parent so what we have to do is you have to pass the value back up to our parent nodes and then explore the left and right child to see if we hit our a equals two so from here we pass in one so at this point we have one and then we have two things we can do once we're back at three we can first explore because we have something that's not invalid we actually have specifically we have one we can explore the other node which means we since we came from left we want to go to the right and we go down right and we add 2 and that would give us our other answer the second thing we can do once we're back at node 3 is that we can take our existing one value and pass it back to its parent specifically increment r1 and change it to 2 and pass it back up unfortunately there is the parent node of this whole entire tree so there is no other answer and that is the high level intuition of how we can get the answer to this problem to formalize what we just discussed for recursion problem we have our base case in our recursive case we have two base cases here the first base case is if our node that we're traversing becomes null for example if we were to go right instead of left first eventually we'll reach a null node right here and then we just return negative one because we have to turn something back our second edge case is when our node is equal to our target and this is what we saw in our high level walkthrough we go left and then we eventually find our target five and then when this happens we have two things we want to do first we want to explore downwards to find all the k distant nodes and that downward brought us to seven and four the second thing is we want to percolate or just pass back one so we can find all the cadence and nodes that are above that's what we did over here we passed one up and that brings us to our recursive case we did the first thing where we explored the love tree for target that's when we were back up here at three so now we pass back 1 from our 5 which is the target so we get something that's not equal to negative 1 which is our null case then we want to search the right tree specifically we pass down our current one value plus number one and that gives us two and then once we reach one we fit an answer and we can add that to our answer list the second thing we can do in our recursive case is that we would also pass the value back up so that we can potentially find any parent node that might be equal to which in this example there's no parent node the next step is after exploring the love tree we can also explore the right tree and do the exact same thing the only difference is when we don't get a negative one value instead of searching the right tree we now search a left tree with our value to see if we can find a k distant node and then we do the exact same thing and we pass the value back up to its parent node otherwise if our left and right node did not find our target node we just return negative one and we continue searching the runtime of this algorithm is o of n because at the end of the day worst case scenario we'll explore everything in the tree the space-time complexity of this the space-time complexity of this the space-time complexity of this problem is also o of n because potentially depending on the size of a tree worst case scenario we might have a situation where every node is our answer so we have to store every single one of the node now in the live coding section the first thing i want to do is i want to create some field states to save the given inputs that we have so we don't have to pass down every single time after defining our fields and calling our recursive function we get the answer and then we return it let's define our helper function as we discussed we have two base cases and a recursive case in our base case if our node is null specifically meaning we travel all the way down to the bottom of our leaf nodes we return negative one because we didn't find a target now if our node equals our target node that means we must have found the node which in this example is over here and we want to search downward the generic helper function to find all nodes that are k distance apart and we start with zero in our current node otherwise we have to do a search down left with a one starting value and a search down right with a one starting value and after we search all of the nodes that are below our target we just return one back up so we can start finding any nodes from the parent and its other child to see if we can find any k distant nodes now let's define a recursive case so in our recursive case we first check our left node to see if we can find the target value which we do and so our if our left value is not negative 1 meaning that we did not hit a null case when we're cursing through our left tree and we must actually hit our target the value we get is the distance that we are currently away from our target node so in this example that would be one so our three would be one of white for five and then now if our left value that we received is equal to k that means that the current node we are at is an answer otherwise if it's not then we just search the right subtree and we would pass our value plus one and of course we haven't defined this yet we'll do that later otherwise we increment our left by one and then pass it back up to the parent we do the exact same thing with the right tree except instead of exploring the right node we would explore the left node and then otherwise if we don't have any answers we just return negative one because that means we have not encountered our target node yet now let's define our search down helper function this helper function is just a another recursive function it's very similar to our previous recursive function where we have two base cases one where we're at null one where our distance equals k and then finally our recursive case where we just continue exploring down until we hit our k or no and then the recursive case where we continue exploring the left and right subtree until we hit one of our base cases and that's it for this problem let's quickly walk through it all right so we started our root node three and we just pass it down and go to our helper function three is not null so we don't do it so we don't enter our first base case three is also not our target so we don't enter that base case either and so we enter our recursive gate the first thing we do is we explore our left node so we go to five and at this level we check again is five no is five equal our target yes it is so the first thing we need to do is we need to go down again starting with a value of zero and see if we can find any nodes that is k away from our target so we start here at zero in our search down method our current node 5 is not it's not null so we don't return it's also not equal or distance so we don't add it to our answer and so we just continue searching the first thing we do is we search our left subtree which is with the distance of one it doesn't hit our base case so we explore its left and its right which is both null and so we have not found any valid answer over here and we just return back up and then back at five again we try searching the right node and we hit two now at two we will search its left and its right and we get seven which is two distance away so it hits our base case and we would add it into our answer map then we go back up and we try searching our right subtree which will be which is four and is also two distance apart so we add that back up and at this point we tried every single possibility and then we finish our search down helper function now back in our base case at five where we found our target value we need to pass back up to the parent its length away from the target node which in distance is one we pass that back up and so we exit out of our left of our helper function with the value of one and because one over here is not equal to negative one that means we found our target node and we need to see if we can find any other nodes that is k away from it if our left is the same as our k value in this instance it's not so we enter our else case and we search the other node we came from our left node so we search our other sub tree which is our right subtree so we go down here with passing two and then we do our search diameter again except in this instance we found our base case already where our distance is the same as k and so we add 1 into our answer list and then we go back up now since we finished looking at all of our left cases we just checked the parents we don't bother checking the right note at this point because we no guarantee that there's only one target and that target is from the left of the dream however if we let's say we didn't find it we would try searching our right subtree to see if we can find the answer and we basically do the exact same logic and then finally if neither our left or our right subtree found anything we just return negative one because clearly whatever sub-tree that we're at clearly whatever sub-tree that we're at clearly whatever sub-tree that we're at like let's say if we went right instead first it does not have our target answer as a child and that's basically it let's submit our problem and there you go this is how we would solve the old nodes distant k in binary tree problem it's an interesting problem that tests your ability to search down on nodes and then percolate values back up if you have a firm understanding of this you should have a good grasp of handling any sort of binary tree problems now if you have any questions please leave them in the comments below otherwise if you found this video helpful consider liking and maybe even subscribing for our daily updates otherwise i'll see you in the next video and have a great day
|
All Nodes Distance K in Binary Tree
|
sum-of-distances-in-tree
|
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._
You can return the answer in **any order**.
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2
**Output:** \[7,4,1\]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
**Example 2:**
**Input:** root = \[1\], target = 1, k = 3
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 500]`.
* `0 <= Node.val <= 500`
* All the values `Node.val` are **unique**.
* `target` is the value of one of the nodes in the tree.
* `0 <= k <= 1000`
| null |
Dynamic Programming,Tree,Depth-First Search,Graph
|
Hard
|
1021,2175
|
1,732 |
so this question is question number 1732 find the highest altitude there's a biker going on a road trip the road trip consists of n plus one points at different altitudes the biker starts his trip on point zero with up to equal zero you're given integer array gain of length n where gain i is the net gain in altitude between points i and i plus one for all the i's that are between zero and n return the highest altitude of the point so let's give an example and start with that so if you have something like minus 5 1 5 0 minus 7 you start with 0 and you say okay this is the gain 0 plus minus 5 is minus five and then um so the net gain is the uh gain in altitude between points i and n plus one so zero is the i plus minus five it will give you i plus one which is minus five and then minus five plus one would be minus four then minus four plus five will be one plus zero would be one again one plus minus seven is minus six so that would give us the whole uh altitudes um but which one is the highest one between them okay so for that what we want to do is first of all uh start with a starting point so what we want to do is basically say start equals to zero and then say let's say alps equal to these are the heights uh and i'm gonna start with zero here okay um yeah okay so let's do this and we wanna say for num in gain okay so what we want to do is say uh alt dot append we're creating an array here that would store all the altitudes inside so uh what we want to do is say um that starting point which is zero um start plus the number so this will give us the alt the next point then i want to say that start equals to start plus no yeah so if you print this out um let's say um it gets like this uh this is out that's why when this out you'll get through minus five minus four one minus six so this is the same as here as we uh calculated okay so what happened here was that we went through the whole loop of the gain now the whole array of the game and then we added start zero plus that gain information so zero plus minus five then we put minus five as the starting point the next one and we added it again and again uh so that gave us this one here okay so now we want to look through this whole thing by the way we started the else from zero because it said start with zero so that's why we have zoom inside it that's important to have it inside because otherwise it will give you the wrong answer um so make sure that you're adding that because of all the examples you see that they present zero here uh this one okay so the next thing is that um we want to loop through the vernon in uh the x and let's say we have m max value of equal to so the max value would be the let's say it's um of zero actually yeah we'll just give it uh the first value here and i'm gonna say this one like this okay for nothing else uh m is less than no if this isn't less uh we want to put m equals two no we can actually say out here because this is the one that we're going to print out i'm just going to say out here yeah so then so this is done saying that if this is smaller than the num we're putting that number as the maximum and then you're returning that maximum which is out returned so that should work here yeah it works for this case and it should work for all the cases i think yep it worked i just want to say that um here let me just explain this part one more time so we started with putting the first one as the maximum value uh and then we checked through the rest of the array uh here this one and saw if any of them is bigger than that maximum value put that as the max value and then return that's it that's what we wanted to do and that's the solution to number 1732 find the highest altitude
|
Find the Highest Altitude
|
minimum-one-bit-operations-to-make-integers-zero
|
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i` and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100`
|
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
|
Dynamic Programming,Bit Manipulation,Memoization
|
Hard
|
2119
|
461 |
okay what's up guys this Isa here and let us continue with the next question of our binary um what is this bit manipulation playlist so next question is the Hamming distance let us read the question so the Hamming distance between two integers is the number of the position at which the corresponding bits are different right so let's say you have been given X = to 1 and y = to 4 the B represent of 1 = to 1 and y = to 4 the B represent of 1 = to 1 and y = to 4 the B represent of 1 is 0 1 and four as 0 1 0 you can clearly see that the last bit here is different right and the third last bit is different right and that is why your output here is two you basically we need to return the number of places where the corresponding bits are different right so what we'll do here is uh we will start traversing from the left hand side right and we're going to need to check while one of the bits uh what we need to check that if should X greater than Z or y greater than Z right so if any of the number is not greater than zero right we need to run our y Loop and how do we check if our how do we check if the current bit is set or not right so we can check it as x uh and one right X and 1 this will give you your current bit is set or not I will equate it with equals to Y and 1 right if it is not equals to this then definitely I will say count Plus+ right definitely I will say count Plus+ right definitely I will say count Plus+ right once we have checked our last bit I need to move to my second last bit right so we'll just right shift each and every both X and Y right so right shift is equals to x uh equals to X right shift 1 and then Y is equal to Y right shift by one place you can also write here x = to one place you can also write here x = to one place you can also write here x = to X by2 both remain same and similarly for y = to Y by2 great so that is how this y = to Y by2 great so that is how this y = to Y by2 great so that is how this question will be solved so at first if it will check X and one so at the last question it will check if it is equals to one and Y and one so what is actually happening is so I'm just doing an operator with one so rest of the bits will be zero and since these bits are zero and we doing an and operator so all these bits will be zero and since here it is one and we are doing an and operator so this answer will depend on whatever be it's set or unset in the given number right that's how the things are working here so let's switch back to the code now okay so that is our code in Java so we'll have a while loop while X greater than Z or y greater than Z so if any of the number is greater than zero then definitely we have to process it right okay so until and unless both of the number finishes we need to process the loop so that's it we are checking if the both the last bit if it is same then if it is not s that me answer Plus+ then again to check the answer Plus+ then again to check the answer Plus+ then again to check the last bit that's the second last bit so we are um doing one left shift right one right shift great that is it so what would be the time and space complexity so we are moving till uh first of all we are doing y = to Y by2 so it will take log of Y y = to Y by2 so it will take log of Y y = to Y by2 so it will take log of Y right and what whichever be the maximum so if x is maximum or Y is maximum then we are going for that Loop right to whichever is the biggest number so that is why maximum of log X comma log y so that is it so we have got the sumission for this Java code let us see the C process code as well so it's the same as we have done in Java and drun let us wait for the submission great so few last thing that's my DSL repository uh where all the sub Mission uh got pushed so you can start un foke this repository to uh get help with the source score and if you have understood the problem and the solutions so do like share and subscribe till then uh let's meet again in the tomorrow's video the next question or the next question and until then keep learning key ring bye-bye and take care guys
|
Hamming Distance
|
hamming-distance
|
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different.
Given two integers `x` and `y`, return _the **Hamming distance** between them_.
**Example 1:**
**Input:** x = 1, y = 4
**Output:** 2
**Explanation:**
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
**Example 2:**
**Input:** x = 3, y = 1
**Output:** 1
**Constraints:**
* `0 <= x, y <= 231 - 1`
| null |
Bit Manipulation
|
Easy
|
191,477
|
49 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem number 49 group anagrams let's read the question prompt given an array of string strings group the anagrams together you can return the answer in any order an anagram is a word or phrase formed by rearranging the letters of a different word or phrase typically using all the original letters exactly once so if we're given this example input of strings eat tea tan eight nat and bat we should return bat as one group nat and tan is another group ate eat and tea as another group let's see how they got those let's focus on ate eat and tea well if we remember what an anagram is basically we're taking the letters of a word and if we can form another word by rearranging those letters and using all of them then they should be an anagram group so in this case we have a right and there's one a there's t and there's one t and there's e and there's one of them right and we see that's the case for eight eat and t so that's why it's in a group then if we look at this group we see that we have you know one n we have one a and we have one t so that's why nat and tan are in the same group because they have those counts for the letters and bat it's on his own because there's no other group that has you know one b one a and one t so that's how they derive the groups now let's think about how we might make a general use algorithm to solve this problem okay so we've read the question prompt and we've gone through the example but how exactly do we do this in a generic way well the approach that we want to take here is actually to figure out the count of each character and what we're going to do is we're going to represent that as a list of length 26 and the reason we're going to be using 26 is because there's 26 english characters so that means for every position in our array here the index will represent the count for that character so for example the zeroth index will represent the amount of a's we have the first intex will represent the amount of b's we have and on for every single character in the english alphabet then what we're going to want to do is we're going to want to go through our word here for each you know word in our input array and we're basically going to form one of these arrays here for each word so for example we have the word eat so we see an e here right so we would increment you know this i guess this would be this one so this would become a one we see an a we see a one and we see a t so we'd make it a one here and then all the other values would be zero now we need a way to actually store this and we need to make a group well what if we had a dictionary so we have a dictionary where the key will basically be this you know array that we've just constructed so you know this will be here as the key and the value is actually going to be the string that we're working with and we'll store it like a list of these because there can be a group here right so we'll put the string eat here and then you know if we get the word t then you know we'll do the same thing we'll see that t you know this will be a fresh array now we'll see that there's one t there'll be one e and there will be one a so we would put it again for that key and we would input t here and then what we would do okay we get to tan now tan is gonna have one t it's gonna have one n uh one a and one n so this would be a new key because obviously this isn't the same one so we have you know the second value here and then we would have basically tan and on we go through and that's how we're going to form our groups now you may be wondering okay how are we going to hash these lists because you typically cannot hash lists because they're mutable right dictionary keys have to be immutable so to get around that we're actually going to cast this entire um list every time we make it into a tuple that way we can use it as a dictionary key because tuples are immutable so that's how we're going to get our keys so we basically just need to build this array of length 26 for each of the uh words we have here and then we're going to cast it to a tuple and use that as our key so obviously t and eat are gonna have the same array here and then when we cast it to the tuple they will represent the same key in the dictionary so we can add them to the you know the value list for that you know tuple value here where you know at the zeroth index there's a one i guess at the what is this the fourth index it would be an e and then at whatever index is for t there'd be a one here so that's how we're going to derive it and that's the general idea and once we do that you know we'll have all of our groupings and you know some values here and all we have to do at the end is actually just return the values of this dictionary here which will be you know uh the list of lists that we're looking for so let's go to the code editor and put this into code it should be a little bit more clearer when you see the actual code implementation i'll see you there okay we're back in the editor now let's write the code remember that we need a dictionary to store our results here for the groups so let's define that so we're going to say groups equals collections.default dict list so collections.default dict list so collections.default dict list so basically i'm just creating a dictionary whose default value is it list so that way i don't really have to check whether or not something's in there if it is it's just going to initialize an empty list and i can just append straight to it that way i don't have to do checks for whether or not a value is in there this is something exclusive to python this default dict although other languages probably have a similar implementation you can use a standard dictionary here if you want but you're going to have to check whether or not a key exists this default dictionary actually just lets me avoid that but it's just syntactic sugar you don't have to use this if your language doesn't support it anyway getting back on track so we need to iterate through all of the strings and calculate that you know array of the counts for each letter so let's do that so we're going to say for string in stirs we're going to say characters so this is going to represent the character array so remember we need to keep the count for each of the english characters so we're going to define an array of length 26 and initialize every single element to be zero so that's going to represent the count for each english character so now we need to go through the string character by character so we're going to say for char in string we're going to say chars so now we need to increment the count for each letter but how do we actually derive the index value for each uh specific letter well python has this nice function called ord which basically takes a character and returns its ascii value now the problem here is the ascii value is actually going to be greater than 26 for our characters so what we need to do is normalize it by basically subtracting the ascii value for a that way we will always have a value for our characters here that is between 0 and 25 which is the indexes of our list if you don't understand how this works go look up the ascii table and go look up how ord works uh in order to understand this so this will give us our ascii position um you know normalized to the basically the start of our 26 length array here and we're going to increment the count for that character by one and we're going to do that for every single character in our string now what we want to do is we want to add this array as a key to our groups here so that way that any character or sorry any string that's an anger anagram will have the same you know character array uh that way we can group things by you know group and that's why we have a list of values because you know multiple anagrams will be having multiple words but the same anagram will have multiple words to it so what we want to do is we want to say groups but remember that lists are not uh immutable right so they are mutable data structures which means that they cannot be used as dictionary keys so to get around that we need to cast our you know list here to a tuple so that way we can use it as a hash key and then we can simply append to that hash key the string that we were working with and in the end like we said all we need to do is return oh i cannot type say groups dot values geez oh my god group stop values so let's do that and submit and cool we see that it works now let us talk about the time and space complexity so what we're doing here is we're going over every single string in the you know given input and we are going through it character by character so that is going to be an o of n operation to go through all of the uh you know strings here and then for each string what we're doing is we're iterating through all the characters so we're going to say that our time complexity is going to be big o of n times big o of k where k equals the length of the longest string right so this is going to imply that we have a runtime complexity of o of nk similarly we're going to have to hash um all of the you know groups here and this is going to be you know dependent on the length of basically the longest string that we have here so again we're going to have o of n k for the space and that's basically the time and space complexity for this problem if you've enjoyed please like comment subscribe and check out my other videos if you're prepping for on-site if you're prepping for on-site if you're prepping for on-site interviews at any of the big tech companies this will definitely help in your preparation happy coding
|
Group Anagrams
|
group-anagrams
|
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** strs = \["eat","tea","tan","ate","nat","bat"\]
**Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\]
**Example 2:**
**Input:** strs = \[""\]
**Output:** \[\[""\]\]
**Example 3:**
**Input:** strs = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strs.length <= 104`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters.
| null |
Hash Table,String,Sorting
|
Medium
|
242,249
|
44 |
okay lit code number 44 wildcard matching this task has appeared before in the lead code tasks in the first 10 or 15 something like that the question is pretty much the description is the same as it was before with the minor differences we have a string we have a pattern string and we have to match them now the pattern contains a question which means it can match literally any character it can contain characters that have to match to the characters in the string and it can contain a star and in this type of in this description the star means literally any string in the previous one there was a star with the letter behind it which would mean that it can match any number of letters this time the star gen just means much anything literally so just like the previous task so this task has limits of 2 000 and the previous test limits were until something like that so a classic dfs approach which basically means try all the possible branches of the pattern and see whether if you can find one match at least and if you can find one mesh that means the answer is true otherwise it's false now it's 2000 so that solution cannot work but generally that is the only solution so if we combine the recursion solution with the memorization to save some processing power we get dynamic programming okay so how would we approach this one okay so let's say that we have a function f initially let's name our strings s and p as for the string and p for the pattern for simplicity let's say we have function f ing which basically says it is it will be a bool which would be our answer whether we can match it or not and i and j mean that can we match a substring or a prefix of string s with the length i with the pattern prefix with the length j now these are all the pretty much the prefixes that we've matched here so our final answer would be f of the s dot size and p dot size which would give us true or false depending on the answer and our question is to fill this f formula fully based on some base case answers that we can calculate by hand so what is this going to look like in a more let's say a visualized way right so i will make a small box here and i'll also use an example here right now i would like to use a more abstract version of it so let's say that we have a couple of lines here just want to make the grid which really challenges my drawing abilities okay this looks well more or less like it so let's say that our characters the prefix of s in other words would be represented on the vertical axis and the prefix of p would be represented on the horizontal axis so s1 s2 s3 those are the characters first character second third and so on and the same goes for p so i would say p1 p2 p3 and so on so this and this means the empty string which means uh nothingness right and it is it's also important to take this into account because this is going to be our base case so basically if we can represent this formula the f i and j by using all the previously calculated values of f and we can have some base cases which would mean some constant number of cases that we can calculate by hand we can solve this okay so initially we have this grid which we don't know what it represents but we can know by hand and feel it that we can match the empty string with an empty string so that's true okay so we can so we cannot match empty pattern with literally any type of a string at all if it's not empty so all of this would be false so we can match an empty string with a pattern which starts with a p1 only if the p1 is a star if this is not a star then that means that the p1 is either a dot or sorry a question mark or a character and the string is empty so it would be false in any cases here but if p1 is a star then it'll be true otherwise it defaults so what this is going to look like is something like this so f let's say um anything literally so let's say i and 0 on all the cases where i is not 0 is false so f 0 is true so f 0 and let's say another i where okay i'll call this j because j is usually used for the columns so if j is not 0 then it can be matched only if the j so let's say let's keep it like this so if p j minus one for the indexes is a star and if 0 j minus 1 is true so if at any point it is a star the current character is a star then the previous matching will help us to decide whether we can match it or not so in this case the previous match is true empty string measures the empty string if p1 is a star then it would check the previous match it's true it will still be true if p1 is not a star it will be false and after that if there is any other star that is present it would look at the previous value which would be false again so this way we can feel our initial first column and first row okay so now the question comes ready for all the other cells that we have to fill one by using all the previous answers that we have obtained so for that just give me a second i will no i will just uh save this i will upload this also in the post okay we have it saved so now let's make a new one okay again the same grid is gonna be present so no okay those are bad drawing skills maybe sketchpad is default in grease that i can use but i never checked it so let's consider that it doesn't for now some more lines here i don't think i need this many but okay so again so s1 s2 is 3 and so on and p1 ctrl c here p1 p2 b3 and so on this is empty true and so on okay so now for each cell let's take the iron j cell and see how we can calculate the answer for that considering that for each i and j we have all the previously obtained solutions all from here right so for uh for a cell f ing how can we check based on all the previous answers okay so if both of them let's say s i is a character is always a character and if a p j is a character so i can write the flow in this way so let's say like this so we have the p j actually minus one for the index but this really doesn't matter so if the current if the end character of the pattern is let's say letter or a question mark then the flow is going to be something like this right so this is our f i'll say okay so if it is a letter or a question mark then if it is a letter and s i minus one i think i will use the sub indexes to save some space here okay so if the character matches that this is our flow and if it is a question mark then it doesn't matter what the character is then the answer would be just to match those two correct those two characters which is the last character pattern the last character of the string and take the previous answer which would be the same f i minus one j minus one which means we match the last two characters okay so now let's dump these two characters and get back to the previous matching that we did okay so if the pj minus one is a star then what are the two flows from here that arise okay so one flow is that the star itself we are treating as an empty character which basically means that we are discarding the star and our answer would be regardless of the value of s i minus one our answer becomes matching the same pattern the same string f the same string with the pattern up to the point of this star not including the star so this would be j minus one so if we could match the previously so we can treat the star as an empty string and say okay we don't need the star because we matched it previously okay or another branch of this would be let's treat the star as i would say here like a small comment a dump star or let's match the star with the last character of the s which is the si minus one itself and say okay let's match the star with the last character and then check the previous answer again with the star being at the end of the pattern itself which would be f here and it should be i minus 1 and j so if it is a star it will take the value either from here or from here and this is going to be or not an end okay so what does this mean right so the second case which is the trickiest case in all of this so if we match some kind of let's say a string which is s1 s2 si and we have our pattern string p1 p2 pj right and the pj is a star so if we match the string with the si we pretty much are ending up with the same matching solution with s 1 until s i minus 1 with the very same pattern p 1 p 2 and the star and we have already calculated the answer for this so whatever the answer for this it would be taken into our new answer in here with the i added to the end of the s i hope that makes some kind of a sense i'll also save this to upload in the site someone might need it somewhere okay so now it would be the typing time let's see the dynamic programming tasks are kind of like this if you can understand the solution typing is easy if you can't well it doesn't matter how much you will type all right so let me define first of all the borders i think i can use one extra probably well okay i might not need the one extra but okay so p does say so n would be the rows and yeah and would be the columns so our dp would be vector char dp which would have n rows m columns all of them zero would be in defaults at the end it's going to be return dp and m okay so what are we looking for here okay so i think i will need some extra spaces here okay so let's see first of all filling up by hand the uh the first row in the first column so the first column is would be kind of easy so let's say the first thing is dp00 is one empty with an empty i should have started one oh i actually need one more of his slots okay so till n okay so the first column i think i should have used j okay it's fine okay so the first column all of them would be false zero equals false is zero oh what am i doing this so everything defaulted to false okay so the first row would be something like this so if i were to go over the first row and this time i'll use the letter j g is less than m plus j okay so it is pretty much going to be like this so if it is a star then which means that our p j is a star then just match it with the previous answer oops not return dp 0 j would be dp 0 j minus 1. this is the only possible way to fill it with potential ones if there is a star if there's no start we remain false just like in a default value all right so now for the main loop will start from one let's plus i plus j okay so now the simple logic goes like this so sorry if so if we're going to check only the pattern value of this so if the pattern the last character of a pattern is not a star then the matching is going to be only like this so if it is matching in a sense matching would be if it is equal to a question mark and okay don't forget the minus one where is the or it matches the character because it is the same character i minus one pick some styling here okay then our answer would be to match these two characters and take the previous answer which is tp ij would be dp i minus 1 j minus 1. okay so otherwise else i don't want to write this in the one line because it would be very confusing otherwise it would be false it didn't match these last characters didn't match okay so this is pretty straightforward now if it is a star i'll put a continue here to avoid the block okay so if we are in this block then we matched it with a star so if it is a star then our answer is going to be this so either we match the star with the last character and if we do that then our ij becomes matching the star with the last character which means it would be dp i minus 1 we meshed it and we are keeping the same prefix or we are discarding the star and we are using what we have left from the previous match which would be the same one but j minus one so this card in the star okay this looks pretty much it unless of course i screwed up somewhere okay i think it's time to test some errors potentially okay samples passed wrong answer here oh yeah there is a index mismatching here it should be -1 -1 -1 these indices are always tricky submit okay and we are done
|
Wildcard Matching
|
wildcard-matching
|
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`.
| null |
String,Dynamic Programming,Greedy,Recursion
|
Hard
|
10
|
264 |
they know that today's li coding challenge question it's called ugly number two we want to write a program to find the ends our claim number the ugly numbers are positive integer numbers whose prime factors only includes a limited number of prime factor numbers 3 2 & 5 so giving example is that we want 2 & 5 so giving example is that we want 2 & 5 so giving example is that we want to find the tens ugly number in the sequence so we can just generate the sequence of ugly numbers according to the province definition it will be 1 2 3 4 5 6 8 9 10 12 so 12 years that ends on a sequence we return 12 so the little note here says well 1 is also a ugly number so it's going to be the first one in the sequence of ugly numbers everything else is some kind of a multiplier between products between the numbers of different numbers of factors we have in a set so including 1 as well so if we look at if we think about how we are actually going to generate this by ourselves we're going to take one more put multiply 1 by 2 3 & 5 januari more put multiply 1 by 2 3 & 5 januari more put multiply 1 by 2 3 & 5 januari to swing more ugly numbers and post put that on to some kind of a temporary container and then grab the smallest one from that container so it will be 2 we push this to on to the put the 2 as the second number in the sequence after we done that we used two to be the multiplier on the left hand side x all the factors that's gonna be on the right hand side so we've got to have to multiply to 2 x 3 2 x 5 3 more new larger ugly numbers and we push those onto the container and then grab the smallest one from there it's going to be 3 and then just rinse and repeat this same procedure we multiply 3 by 2 well 2 3 by 3 multiply 3 by 5 yeah adding those to the temporary container so there is just one thing that we need to handle is that the duplications when we get a 2 out we multiply that by 3 the second time when we deal with sweet we multiply 3 by 2 we get 2 and we get 6 twice so we want to do some deduplication otherwise we will put two six two copies of 6 the sequence of ugly numbers so that's already pretty clear we need a set do this duplication the other thing is since that we are always grabbing the current of smallest amount that temporary holder for the generator ugly numbers a prior to queue is a min priority queue is very good for this papers so that's the straight forward generation message to generate all those other numbers so let's just cut this thing up so we have known factors 2 3 & thing up so we have known factors 2 3 & thing up so we have known factors 2 3 & 5 and we have a priority queue initially it's just a single number one that's the first other number we have we haven't pulled out of the temporary holding container yet the sequence of our key numbers generator is going to be stored in the list noms and we have a set that's telling us the number the ugly numbers we have already generated here so that's one so we could have just run a loop for n times and then what we do is to pull the current to smallest a number from the primary queue so that's PQ and then push this on to the sequence the other thing we need to do is to use this as the left hand side to multiply with all those factors to generate a bunch of new ugly numbers and push that back to the priority queue of course we do some duplication all the way so what happens here is that we generate new ugly numbers tester having already generated this already or not if it's not generator that we remember yet it's the first time we see it and also we push this back onto the priority queue so with that we'll be able to about generate all the generative the required ugly number so the very last the number that we generated is the one that we need because we run the loop n times so this I but I really matter so let's see if it works throw some more test cases three five seven it looks ok so let's submit this yeah it's accepted the problem was this simple straightforward approach is that the prior to kill signs can be a problem because we run this loop n times well n is large of course we push more stuff on to it and every generation inside this loop we multiply the number by the different number of factors we have so if this is not three but some relatively large number we can end up by generating and multiplied by K different numbers and push those all on to the prior to kill so the hip hop and push become more and more expensive as the N and K goes larger so we call this K is this the time for this can be a lot of NK so that would be not idea but and also that it's indicative of a bigger problem that is we actually generate a whole bunch more number than what we really necessary what's really necessary the ITR scenarios led to every iteration we just generate one number the next number in sequence so how will you do about do this that will be the full upper question which is this one 313 super happily number I have a video about that so if you want to see the detail you can check up out and check out the from there the big idea is that then the ugly numbers are actually coming from sweet different line so k different lines every lie is a factor so when we generate a number we grab the generated the priors current to smallest ugly number we generated and multiplied by a on the right hand side a factor so that multiplication can be sorted or organized in line of in terms of the right hand side so we have a line for all the ugly numbers that can be generated with the factor two as the right hand side so the number here is basically you know the left side multiplier is basically the sequence of ugly numbers and it's just growing one at a time the second line is the factor the aggregate numbers that can be generated with factor sweep on the right-hand side and the left-hand side right-hand side and the left-hand side right-hand side and the left-hand side multiplier is again the sequence of ugly numbers so all we need to do basically is to maintain the three different head nodes inside this sweet linked list k link the listening if more general so every time that we want grab the next number we just look at the smallest among key headnotes so if we do that the priority queue will be of size K exactly k so that's going to be fast faster so if we you interested in this solution you can check out my video got I put a link over there that's the super ugly numbers so yeah so to in order to achieve that you will really put a node object or some kind of resemblance for that node object onto the private key which is nothing but what's the number inside the cycle here what's the left-hand side or where here what's the left-hand side or where here what's the left-hand side or where can I find the left-hand side number and can I find the left-hand side number and can I find the left-hand side number and what's the right-hand side number so it what's the right-hand side number so it what's the right-hand side number so it will be this nodes value the index for looking up the four from the sequence of a number and the right hand side factor multiplier so the next time if you want to generate the next number you can do is to look up at the next number from the sequence by it by index so it will be 5 multiplied by 2 you can update this so the code is basically grabbed the current of smallest dollar among the K head nodes in the Kade sort of list put that back down to the ugly number that it generated and advancing those head nodes as necessary so that's that the big idea behind it so you'll be faster because the priority queue size does not increase too much it's constant it's always K so that's that the other thing that I think I want to mention briefly is the solution page for this it's been thing something like a dynamic programming for solving this and it may appear that this can be better based on the time space analysis here but it's not the case it's not really the case compared to if use if used this solution the reason being that this is not dynamic programming this is just a button upper tabulation so it's essentially that you use a list to hold cake head notes and everytime you want to grab the next to smallest you actually do a hard minimum pool comparison for running on all the key notes you have so it's a it's actually worse than then than this prior to cue solution so I don't recommend this and it's totally not an animate program it's just tabulation so if you interest again if you're interested in this kind of follow up a solution can check out my video or 313 so that's it but this one I think it's okay because it leads to optimization if you analyze the problem about the priority queue and then dig into the details about how the numbers are generated in a little bit more detail you can realize all you need to keep track of the K different headnotes so that can leads to either the tabulation where you just have a list of the head nodes and every time you do a minimum among all the K head notes and do advancing the other way is still really use a priority queue to hold the K different head nodes so that's it for today I'm sorry that I should be integrating those into the video but I just don't have time to do that today so I highly recommend to check out my videos researching
|
Ugly Number II
|
ugly-number-ii
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return _the_ `nth` _**ugly number**_.
**Example 1:**
**Input:** n = 10
**Output:** 12
**Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Constraints:**
* `1 <= n <= 1690`
|
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
|
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
|
Medium
|
23,204,263,279,313,1307
|
5 |
what's up everyone sam here from byte by byte calm and in this video I'm going to show you how to implement the longest palindromic substring problem so this is a really popular interview question as well and we're going to date into it right after the intro and if you haven't already make sure you hit that subscribe button and the bell icon so that you get notified every week when we release new videos alright in this video we're gonna solve the longest calm the longest palindromic substring problem and so what we're trying to do here is we're just trying to take a string and we're trying to find the substring that is a palindrome and also that it's the longest palindromic substring in this string and so in this example we can see that adda is the palindrome we also see da D is a palindrome although it's not as long as a DDA and so our longest palindromic substring would be a DDA or would be length four in this case and so as always we want to make sure that we're properly defining our function and in this case we're actually looking for the string itself and so this is a great example of where you know just being clear of what we're looking for is key because in a lot of these other problems we've been looking at just like what is the number so we would be returning this four but in this case our function is gonna look something like you know we'll take in a string and we're also going to return a string and so the return for this would be a DDA and not four and so again this is just why all these times we just want to be careful because I can't tell you how many times is an interviewer I've interviewed someone and they just haven't done it right and it just rubs me the wrong way because I know they weren't listening carefully and it makes me concerned that when they're our project specifications or anything like that at the actual job that they're not gonna pay close enough attention and that there's gonna be like merge conflicts and different things because they're not paying close enough attention and so it's really important that you get this piece right and so let's look at how we could actually solve this problem so you know the easiest solution this is hopefully going to come as no surprise but our easiest like brute force solution to this is gonna just be to look at all of the different possible sub strings right we could look at all the sub strings and then we could easily write a function that would determine whether two strings or subs are whether a string is a palindrome or not right because like you know super easy way to do it is that if s equals you know s prime so if s equals the reverse of s then there palindromes we can also just do you know count from the end of the string and the beginning of the string into the middle and say are the characters equal we can start in the middle of the strain count out words there are a lot of different ways that we can determine whether it's a palindrome and then if we find all of the different sub strings you know we would just find B we would find ba food fine ba D etc eventually we'd find adda and then we're basically going to say you know is it a palindrome and so we'd say you know this one's a palindrome this one's not a palindrome and this one is a palindrome and if we're tracking the length then not too hard right so what's gonna be the complexity of this though so finding all of the sub strings is going to take us o N squared time right because we basically have a nested for loop and then not only that it's gonna take us N squared time to identify each substring but then for each of those sub strings we also need to copy it right because we're going to need to make a copy of the string it depends a little bit on what language or we're using here but like for example if we were doing this in Java strings are immutable and that means that if I say you know s substring whatever it is this is gonna take me Oh or if it's I guess I might and J this is gonna take me of j- i time which in the gonna take me of j- i time which in the gonna take me of j- i time which in the worst cases uh and right because the worst case is that i is zero and J'son and so the worst case is when I'm doing this generically I'm just gonna say it takes me all event time just to find the substrate and this is true for a lot of language I think C is the main exception in this case where C it's you know you're just using an array to back it but if you're doing this in Python I believe it's the same issue where it's like you're actually copying the string and so you want to be very aware of what the time complexity is of that and so what that means is that we have oh of N squared different sub strings and then we have to copy each of them and then we also have to determine whether they're palindromes or not and so to determine whether they're palindromes or not we're doing you know it takes o then time to compute whether something the palindrome we have o of N squared strings and so again like it's gonna basically be this times two because we're gonna have the same thing for computing whether they're all palindromes and so we're gonna get an o of n cubed time complexity here for actually doing the approaching the problem this way and so then of course the question becomes how can we do this better well let's look at our first of all let's look at our best conceivable runtime so our best conceivable runtime here is o n because the best possible scenario is that we just iterate over the whole string ones we're definitely going to have to iterate over all the characters at least once but we don't know whether we can do this problem by only iterating over all the characters once and so that's our best conceivable runtime so we know that we can at least strive for something better and so let's think about this well we're let's look at and let's look at our but optimization here so where do we have bottlenecks in this solution well one of the bottlenecks is that we are actually and computing or like finding and storing all of the different sub streams right and so that's a bottleneck because that's taking us this event cubed time and if we could get rid of that then you know it's still gonna take us all event cubed time because we then also have to compute all of the weather all the strings are how our palindromes or not but that's the other question we can ask is do we actually need to do that do we actually need to be like looking at all the strings and whether all the strings or palindromes or not and the answer is that you know there's a lot that we can do to sort of limit our search to what is actually going to be a palindrome and so I think that the easiest way for us to look at this problem is that you know how do we know whether a string as a palliative and the answer is simply that we compare the characters on the left side with the characters on the right side and see that they match up and what does that mean so in this case let's assume that we had the string a is a palindrome right because it's a single character and so the first you know it's the same in both directions and now if we added characters on to both sides so let's say we put a B on the beginning of the B on the end then is it a palindrome yes it's still a palindrome as long as those characters are equal right and so we can add characters going out this way and as long as the characters are equal then it's a palindrome but as soon as the characters are not equal then it's no longer a palindrome and so in this case you know we see that this is the palindrome but we can do this we can determine that this is a palindrome and determine that all of these inner strings are also palindromes by just expanding outwards from the center right and so this is the key insight here I think that with this problem and with palindromes in general you can either go from the outside or you can expand from the inside and so the point that we have to the keynote thing to notice here is that you know if a is a palindrome then as long as these two are equal that's a palindrome as long as these two are equal the whole thing as a pal and we can keep expanding out until they're not equal and so how can we apply this when we are actually looking at our string here well it's actually super simple this is a little bit tricky to code up but it's simple in theory and so all we have to do is just say for each character let me try and expand out in both directions as much as I can and so I'll copy the string here we're going to start with the B we're gonna try and expand out and we see that you know this is the end of the string so we can't expand out in that direction so we're not gonna expand out in the other direction here either so we have B we come to the a and we try and expand out in each direction but these are not equal and so that it can't be a palindrome right and so we have a we come to the D we try and expand out in both directions they're not equal so we get D we come to this D and we try to expand out in both directions they're not equal so we get this then with the a we see that we can expand so we get a palindrome that's like this and then with the D again we're at the end and so that works if our palindrome is of an OP length but now we also have to consider the possibility that our palindrome could be of an evenly and so what we do is we could do a second pass through here and essentially look for anytime there are duplicate characters right because if a palindrome is that even lengthen the center two characters have to be the same so we need two of the same character next to each other and what we see is that when we come to this D oh they're the same so let's try expanding out in both directions from here so okay now we get this length four and so the question becomes then of course what is the time complexity of doing this and it turns out that in this case our time complexity is going to be a lot better because instead of having to go through everything so many times we're really iterating over the whole thing once and then for each character we're doing it most o Levin extra work right so we're doing oh then to iterate over the whole thing or technically off of two n because iterating over it twice right to find the pair's and then individual ones where they even and odd palindromes and then were expanding out and the process of expanding out can take as much as Oliv n time right and so what we're gonna do is we're gonna have this x oh then which gives us an event squared time complexity and then in this case you know just looking I'm trying to figure out hey like is there anything better that we can do here is there a way that we could do this in linear time and so I might take a few minutes to sort of look at this and see you know are there any bottlenecks is there anything that we can do really you know at this point the bottleneck or the limitation is the fact that we have to iterate over everything and we have to explore all the palindromes and there I don't see a better way to do that and so I'm gonna I would assume if I was solving this that this would be optimal even though you know this is a case where despite our best conceivable run time being all event we're not actually able to achieve that but so this is how you would approach the longest palindromic substring problem and there this problem also has a bunch of different ways that you can approach it and I believe actually there is an O of n there is an algorithm to solve this an o of n time but I don't it's not something that many people are familiar with so it's not something that you would be expected to know in your interview at all but this would be a good approach and I look forward to seeing you in the next video thanks so much for sticking with me through this video if you enjoyed this and are looking for more you can check out our free 50 interview questions guide where we go through 50 of the most common coding interview questions and if you like this video make sure you hit that subscribe button and the like button let us know what you thought and check out some of our other videos we have a ton of other content like this and I look forward to seeing you in the next
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
1,091 |
hey everybody this is Larry this is me trying to do the first day of June the code daily giant hit the like button hit the Subscribe button drama and Discord let me know what you think um well as long as soon as it loads anyway uh yeah welcome everybody if you haven't watched it uh hopefully yeah uh I'm in Armenia right now in diligent um so maybe it's a little bit slow but um yeah we'll be doing this if you're new here we will be doing this all uh or month uh we've been having a good Street going I guess so it's gonna happen uh and yeah and let's take a look Jay's Farm is shortest path in a binary Matrix uh 1091 so okay so we're gonna clear binary path so you can go from upper left to lower right and you could go a diagonals and the length of equip half is a number we visited so it just seems like a shortest path right of oh wait do we just go through zeros or the Wizards itself azure that's a really weird phrasing Maybe okay I mean I think you can just go for zero I think the all the wizard itself is rear phrasing um but yeah there are multiple ways to do it this is just the shortest path problem seems like you're going you know just from through zeros is the uh it's the things you can pass through and yeah and let's get to it then right so the idea here is just by first search for me um yeah so let me turn negative one if there's no uh path and then Q is a deck right and then we have a let's say NQ function that just do uh or maybe with a distance and then distance of X bar is equal to D and that's right uh and then maybe if Justin X Y is not equal to Infinity then we return so we don't actually care so maybe it's a maybe mq if you want to call it that um some Infinity number and we just have the Matrix zero let's just say infinity times C in range of R right so basically this gives us a r by C Matrix of distance of infinity and we want to end Q zero uh ZIP at you know uh what number which is Wizard itself so this is actually at one for whatever reason um and then yeah let's get to it then x y d is equal to Q dot pop left I guess D is actually not in here which is equal to distance of X Y right and you set up the directions and direction is pretty straightforward but it's all eight directions so you don't have to really do anything that funky as long as you remember to do uh all of these you can also just write two for Loops I don't know how I feel about it this is just like um this is just like uh what do we call it uh muscle memory at this point to write but um the advantages for this particular piece is that uh or maybe not for this particular piece but the fetish is that the advantages that um if you write things to write the same way given if sometimes it's a little bit wordy um you know you get to uh you get to kind of build on that right and if things look different then you can you know but and today practices practice right so it just depends on how you want to go about it there is something to be said about um there's something to be said about like flexibility as well right so but I guess technically we already checked this is a maybe NQ but foreign and that should be pretty much it this is unless I really misunderstood the problem huh oh whoops that's why that is silly okay one two three four why am I doing three okay well this is just negative one oh man I'm just being dumb of course uh we have to do uh we never checked anything so yeah oops uh again all right there we go right that's like such a critical part oh no I've been sloppy oh Lazy I'm sorry friends I'm trying to catch her first right afterwards but yeah uh that's just watching it a little bit I suppose to be honest but yeah uh but it the algorithm is straightforward you have to think you have to be careful about the education and advantages the first time I screwed that up but uh maybe I was watching a little bit too much and I was talking too much while uh coding but yeah I don't really have much to add to this one um this is regular breakfast search um you know other than you have to be a little bit careful or a lot careful and just a little bit careful uh yeah uh let me know what you think stay good stay healthy to go to mental health I'll see you later take care bye
|
Shortest Path in Binary Matrix
|
maximum-average-subtree
|
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1`
|
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2126
|
1,598 |
Hua Hai Abhivan Welcome to my channel it's all the problem and lock folder delete type unlock your times profile change shoulder and subscribe must subscribe thank you are the meaning of the queen 50 Mondays subscribe this Video then subscribe to the Page if you liked The Video then subscribe to the that main folder after change shoulder operation so instituted after looking back to Amir will see how far away from you for example a given from main road will do Do Subscribe My Channel Subscribe To Step Down From Main Road To Bay Similarly Subscribe One Two Three Do Subscribe In This Dent Paint Parents 162 Aman Folder Disabled Anywhere Else And The Two Will E Do Not Have Also Been Keeping In Fold Subscribe Idli Will Find Difficult Doob Skin Tours Withdrawal Lock Reply Who Is This Is The Case Of Light In Wear Single Dance License Will Just Kunthu Door Change And All Only And Log Ki Notifications Yes Dots Plus One Part Bank Share Also to check if they will give water flow - - check if they will give water flow - - check if they will give water flow - - increase in vid oo main should always have absorbed into the main folder Sudhir and otherwise on health plus 2 directions on Thursday subscribe and subscribe the Channel thanks for watching this
|
Crawler Log Folder
|
crawler-log-folder
|
The Leetcode file system keeps a log each time some user performs a _change folder_ operation.
The operations are described below:
* `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**).
* `"./ "` : Remain in the same folder.
* `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**).
You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step.
The file system starts in the main folder, then the operations in `logs` are performed.
Return _the minimum number of operations needed to go back to the main folder after the change folder operations._
**Example 1:**
**Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\]
**Output:** 2
**Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder.
**Example 2:**
**Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\]
**Output:** 3
**Example 3:**
**Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\]
**Output:** 0
**Constraints:**
* `1 <= logs.length <= 103`
* `2 <= logs[i].length <= 10`
* `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`.
* `logs[i]` follows the format described in the statement.
* Folder names consist of lowercase English letters and digits.
| null | null |
Easy
| null |
1,696 |
what is that guys this is somebody on youtube and uh today i'm going to talk about question 1696 on lead code okay so the question is you have known already and i'm not going to spend time doing that okay the way to solve this question is we need to maintain a dp array a integer array that's called dp and what it does is to store the best score at i right and at the end we can just return the minus one that's our result right that's what dp does okay and uh we will need to use another deck uh data structure right what the deck is basically a space where we keep so wherever we keep we okay so the deck is to keep track of all the options we have so according to our um constraints we the deck is at most length k right and it also needs to be within the range right it also needs to be within the range here inclusive and also uh we're trying to keep track of the maximum score right so any score that is lower we will need to get rid of okay so how do we maintain the stack so we first we will need to okay so because we're populating the deck from this end so whenever uh so that means the oldest element is gone gonna be on the left and then on the right is going to be the new elements so when so each time we'll need to remove some first step remove old options and the second step is okay so this is from the start right because and that's where the old elements are not located okay the second step is we need to remove bad options what is bad that means it is how do we define that means it is um less than our current options right and then it's from the end okay that is our algorithm and this will guarantee that whatever is in front of the deck the first element inside the deck is the optimal solution for our current step okay so now all we need to do is to iterate through the numbers array and calculate the best option at a current step and update the deck to maintain these two rules that we just talked about right all right um all right let me just code it up okay so let me code this up so we know first we need we know we need to use a dpr array right so you go to new int array and the length is n right it's equal to num star links and now here i say right and we know on the first step it is not zero right no questions asked and then we need to keep using deck to keep track of the options right all right and what is the first option we have that is okay here um in index form right so this is um is easier to um calculate the age of a certain element right compared to because we're going to iterate through so it is easier to compare the index to our current index so we can calculate the h that way we know which element to get rid of okay so now we will need to okay so now i need to iterate through the entire nums array and then at each step we'll calculate the cost and store it to the um dp right so there will be the sum the nums i plus whatever is in the um is the best option that we store inside the dp right so it will be um dp and then first right and then we'll need to check while not that is empty and our the age of the element so it will be the age of element which is the index of it minus or in another way is plus k is we're seeing my um a high index range meaning it's um i mean it's outside of my index range meaning it's too old all we need to do is stack dot pull first right we'll need to remove this element and also while my deck is not empty like we said and this element is not our best option anymore so that means my dpi is greater than my current option i mean the old option so it will be my dp um the peak last right because it's in the end and that way we'll need to i'll remove those and last but not least we'll need to add the curl option which is my eye into the deck for our next iteration to use that and we'll just need to return my dpr ray n minus one all right okay so let's do some debugging so my deck the peak first plus k needs to be less than i and also um okay so it's greater than equal to it's equal here too okay here we go right because um if the option if our current calculation and the previous calculation is the same we need to remove it because it is old and then this is because if it's um less than i meaning that cannot reach or just reach i that means we need to discard it because it is too old right and that should work all right perfect let me see if what happens it will get rid of this oh is it still gonna work okay cool so this doesn't matter because eventually in the next situation in this first while loop we'll need to remove it anyways because it becomes old all right that's about it thank you question the space complexity is all of let's see we use a dp array and then size n and also we use a deck right this stack has at most k element in it because uh if it is too old we'll remove them right so there's atmos k element in it so the space is uh o of n plus k and the time complexity it is uh o of let's say we use a for loop so that is n already and inside these while loops we're basically um editing the deck right so the deck is atmos k elements and now we can almost we can delete them all and add a new one and we can do that for each element and actually this each element can be only added once right and they cannot be removed at most 1 so that is another n so n plus n is 2 of n right so that's the space and time complex d
|
Jump Game VI
|
strange-printer-ii
|
You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104`
|
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
|
Array,Graph,Topological Sort,Matrix
|
Hard
|
664
|
327 |
hello friends today let's talk out of ranges on problem given integer rate numbers we needed to return a number of Renaissance at lying lower upper inclusive range some s IJ is defined as the sum of the elements in numbers between index I and J I less or equal than J inclusive naive algorithm below and squared is triple you must do better than that so actually this range ism is the sub-array sound right and so you see the sub-array sound right and so you see the sub-array sound right and so you see the example if the given numbers is negative 2 5 negative 1 the lower bound is negative 2 and upon third is 2 we can return 3 because there are three sub array that there are some lying this scope so how to solve it let's see as we needed to have older zapper racism lying in this scope we can be intuitive solutions to so two older Renison so in order to so to order range sums we need a cut of the ransoms first so how to get all the ransoms the naive solution is we just around chill for loop to get outer suburb reason because we can use this method to get the outer suburb RESA actually we call it a prefix sum the sum is prefix um it's the sum from index 0 to index I so in order to get the index from the sum of the index from I to J we can use the sum from index 0 to J my the sum from index 0 to I so we hear a full loop a queue for loops to care to order ransom because the faster sort algorithm is big old a Logan so in turtle this algorithm needs pickle and squid so can we just use one sort algorithm and calculates this range sounds yes we can just use we can make use of merge sort let's recall what is merge sort merge so two we have two parts one is merge which is linear it compiles Q so to the sub array into one so cheetah large array you can say that and therefore the third part every time it run its left all right part so as we only choose one half of it so it's because Logan and internal is the elgran is bigger and x Logan let's record the merge sort if this array is the original array we get a half of it we see the left part and there are still it has four elements is now to the best case so we cut half of it we choose the left part still it has two elements not the best case we cannot have them we only have four it's just a one element so it is the best case it is sorted and then we see the right part is only had one element it's sorted so we return to the previous function call so no we merge this yeah we return to the previous function code in the we merge it is two Xochitl apart so we get a salty dog a larger sorted array which is for nine and for the right party to SMC we merge these two sorted elements so we get seven nine and we return to the previous function code we merge it and the so and so forth so how do we take make use of this idea um currently let's see the this example this is a given array negative 2 5 negative 1 so we calculate their prefix some first we get a zero net give 2 in 3 we just sum up or negative 2 and the five against three and we saw plus three to negative one so get two so this is a prefix um so our goal is to salt this prefix some endure during this progress we can get the number of the ransoms lying in the lower to upper how do we do that we can do something during this merge sort part because every time we just cut it half right so for the origin of four elements array we carried half we see the left part two elements we carry a house so the 0 1 or DC the index this is the true sub prefix on so folder 0 negative 2 how many their leader render some just a 101 seems you notice that we should do we should a calculate to the valley the range sums between uh sorry before the range sorry before merged because once we do the merge this order is changed so we should calculate the valley the number of ranges sums before the merger function because owning that the left and right groups keep the relative order that means the left and the right keeps their original order because we needed to calculate arrange them so we need to use one terrific sound - another perfect stone terrific sound - another perfect stone terrific sound - another perfect stone to get the ranges on between right so there are other matters so in this case left by right part so this is when you only have two elements is it the right part the same idea and the way we merge the two part we return to its previous function causes is for element part the order still keeps because you see this is the previous perfect some there are negative to still they are in the left part and there are three too although they change older but they still on the right part of this array so that's what matters okay so we always use some prefix on in the right part 2 - the prefix on in the right part 2 - the prefix on in the right part 2 - the prefix some in the left to get a valid or a possible valid orientation as it has a lower bound and upper bound so we also keep the true index to keep the valid or scope we go to starting next and end index let's see the example we use wonderbook hole I in the left part and in the right part we have two index starting next and beginning next I go to zero and the this part it's quite simple because it only has two elements so starting next equal to one and there why ending index you go to two because we know the right party is so tada so in order to get a valley the part we needed to use the prefix um starting next - prefix Tom the prefix um starting next - prefix Tom the prefix um starting next - prefix Tom I if it is less than the lower bound which the movie started index forward if it is equal or greater than the lower bound which has a cube it is what it is now for the ending this if it's less or you call gender low up and we keep it we let it move forward so this end index is exclusive in the starting next in inclusive so in the case we can get to -1 equal to 1 which means we have one -1 equal to 1 which means we have one -1 equal to 1 which means we have one valid range some the same idea to this part the I equal to 2 play firstly and the starting index you go to 3 and in the index you go to web because these 2 minus 3 you go to negative 1 which is in this scope so we can move end index forward so in the end we use an index - forward so in the end we use an index - forward so in the end we use an index - start index would get a 1 okay so this is more complicated part we still loop her from in the left part start from zero and this is a right part first the starting else start from 2 and the 2 minus negative 2 you go to 4 it's not in this scope so we keep it is an ending next first is here in a minus negative 2 also equal to 4 so we do not move it because it is already invalid so in this part we use an index minus start index equal to 0 so this part we do not have very tourism then we let I equal to 1 the story next you go to - at first in the story next you go to - at first in the story next you go to - at first in the tube - there you go true - it is the tube - there you go true - it is the tube - there you go true - it is valid so we do not move it because it E is greater than the lower bound okay in the end the index is equal to 3 so reminds 0 equal to 3 and also previously - here - - they are equal to 2 is you - here - - they are equal to 2 is you - here - - they are equal to 2 is you could end the upper bound or so we can move it forward and then photos 3 - 0 move it forward and then photos 3 - 0 move it forward and then photos 3 - 0 you go to 3 so we keep it so in the end ending there's - starting that equal to ending there's - starting that equal to ending there's - starting that equal to 1 so in the end of this whole function will return 3 ok one thing you need notice is about the earlie the value of this middle value normally we will write a middle you got your high minus low over 2 plus low in case the integer overflow we will use a high minus low divide your right but in our in this question we will use a hype + 1 - lot question we will use a hype + 1 - lot question we will use a hype + 1 - lot the reason is that oh this is 0 we always needed to - it so we want to keep always needed to - it so we want to keep always needed to - it so we want to keep this middle as right as possible and the difference between we plus one or not plus one is when the array have the even lens even number of lens if we plus one the middle will be sorry this is a typo it should be middle should be equal to 2 because high is 3 minus 0 plus 1 divide you plus low will you go choo-choo but if we use low will you go choo-choo but if we use low will you go choo-choo but if we use this formula we will get the middle you quote you one so that's the difference we should have plus one we always want to choose the right one and this is middle this is a middle minus one okay so wipe up we just make use of the merge sort and we return the number of the valid range sums this is a prefix up and then we pass the low index high index and this is the lower bound upper bound the best case if log great oyakodon high will return 0 and then we get the middle value which is the high plus 1 minus load divided 2 plus low and we accumulated this couch this is the left part load to the middle minus 1 the right part middle chill high and this is before this merge function we calculate to it we need a chill index star in s and end index and they either start from the middle value because it's in the right part only the left or right group we read for odor has a capital right so we can use the minus and this I will start from low to the middle minus 1 and the wild is starting next less go there hi this is should make sure the index valid and this ransom is in the scope is if it's less than lower we know we should have moved the Starnet forward in order to get a valid or ransom and the photo ending next if it's valid we just move it forward until we get an invalid or index so in the end of the dance the number of the in the valley the range tom is ending next - starting the range tom is ending next - starting the range tom is ending next - starting Dex so we finally return the account how about the merge function it just like the normal merge sort okay let's write a code we first get an you go to number students as we needed to accumulate some so the so we use a long title in case integer overflow so on plus 1 and a 4 into I equal to 0 I less than an IP I'm sorry I plus the sum I plus 1 you could choose some I plus numbers I and the we return merge some merge result the sum the zero is an because the length of the sum is my n plus 1 so the right valid index Eastham and the lower and upper ok let's write the merge sort we need a long some end low high then that is lower and upper so the best case if the lock rate or equals n high will just er return 0 and then we get a middle value will go through high plus 1 minus low divisor plus low and there's a couch where you go to merge thought some lo Mito - 110 lower/upper palace merge lo Mito - 110 lower/upper palace merge lo Mito - 110 lower/upper palace merge sort some middle high lower upper okay then we get start index you quote you middle and the high index equal to meet oh sorry not high there should be end so for the I start from low and I less the middle I plus while you should make sure the indexing Valley so is less oil for Zen high and there's a some and some start index - some I is less than lower we know is - some I is less than lower we know is - some I is less than lower we know is invalid so we moved her starting index forward in order to gather Valley to render some the ending LSO occurs in high end there some high sorry end index - some i less soil cores and upper we - some i less soil cores and upper we - some i less soil cores and upper we move and index forward in order to get an invalid index so cut will accumulate to the end index - start index ok and to the end index - start index ok and to the end index - start index ok and there we merge to hurt some low middle - there we merge to hurt some low middle - there we merge to hurt some low middle - one middle and high now we return the count so now let's write the merge long some low one high one Oh - hi - we need a help array the size Oh - hi - we need a help array the size Oh - hi - we need a help array the size will equal to the same as the array so it will be high to - low one plus one it will be high to - low one plus one it will be high to - low one plus one and we need the index which means the index in the help array and to another in the index one from low one index - in the index one from low one index - in the index one from low one index - from low - so while index one less all from low - so while index one less all from low - so while index one less all equals in higher one and their index to less or equal to high - if we pick the less or equal to high - if we pick the less or equal to high - if we pick the smaller to the help because they should be so Tschida so if the some index one is less or equal than some index two we let helper index plus you go to some index 1 plus right else their helper index + well you go to some index 2 plus + and + well you go to some index 2 plus + and + well you go to some index 2 plus + and if there are some array left some elements left we moved we assign it to the help array so some index 1 + the help array so some index 1 + the help array so some index 1 + while index to less than hi to help her index 2 + + equal to some index 2 + + in index 2 + + equal to some index 2 + + in index 2 + + equal to some index 2 + + in the end do not forget the - to the array the end do not forget the - to the array the end do not forget the - to the array copy the sauce array is helper star index is 0 the target array is some the star index is low 1 the lens is high 2 minus low 1 plus 1 okay thank you for watching the okay have some problem merge okay let's see what's wrong in the merge oh sorry this should be index the index okay thank you for watching see you next time
|
Count of Range Sum
|
count-of-range-sum
|
Given an integer array `nums` and two integers `lower` and `upper`, return _the number of range sums that lie in_ `[lower, upper]` _inclusive_.
Range sum `S(i, j)` is defined as the sum of the elements in `nums` between indices `i` and `j` inclusive, where `i <= j`.
**Example 1:**
**Input:** nums = \[-2,5,-1\], lower = -2, upper = 2
**Output:** 3
**Explanation:** The three ranges are: \[0,0\], \[2,2\], and \[0,2\] and their respective sums are: -2, -1, 2.
**Example 2:**
**Input:** nums = \[0\], lower = 0, upper = 0
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
* `-105 <= lower <= upper <= 105`
* The answer is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
315,493
|
561 |
hello everyone welcome and welcome back to my Channel today we are going to discuss another problem but before going to forward if you not like the video so please like And subscribe my channel so you will get notified whenever my new video okay so without any further Ado let's start today the question is that array partition question it is a very easy question but yeah I think it is not easy question because you try to understand the concept it is a little bit difficult okay so firstly the question is saying that like given an integer are a nums of two and integer group these entities are into and pairs A1 and B1 A2 and B2 so firstly you want to find the minimum then after that you want to add and return the maximum number so that's the problem okay so let's take a take example like firstly I take a take example of like one four three and two so that's the input and the output is four so I give the output as well as is the uh output is four okay so that's the problem so firstly you want to pair like firstly pair is one and four okay and then second pair is three and two so if firstly you found the pair like this is the first page you found with what is the minimum number is one and you want to add and what is three and two pair so what will be the minimum number is two you want to add two number and the return maximum so it is three okay and then take another like first take another like this is one and four I take firstly and three and two attack firstly and after that I take a like three and 1 and 4 and 2. okay so like three and one and four and two okay so what will the minimum number of first pair is one and add what is the minimum number of the second pair is two what will be the number is 3 it is the same it is uh it is not the maximum number light because all the possible pairing you want to find it the maximum number okay let's take another like one and two and another pair is 3 and 4. so firstly you found the first pair what is the minimum number is one and the second the minimum number is three so what will the output is 4 so that is the maximum number because three are same and the another pairings sum is 4 so you want to return four so that's the problem yeah it is very difficult but you did not understand the concept don't worry about this I will explain you the basic understand the problem and the concept definitely help to implement of your code okay so firstly I like that's the problem is three or like I want to give the space okay one four three two so firstly you want to sort this array so one two three and four and then you want to add the first number and the third number and return four so that's the problem simple like this is the first number and the third number firstly you take the first number then the uh like next number you want to miss this number and the pick up the third number and then sum and the return okay let's take another example like six two six five one two it's my bed I just terminate yeah okay so six two six five one two the first you want to sort this number to one two keyboard five and then six one two is just one yeah one two five six and six so first you want to add first number and the third number is 2 less than the six okay like this is one and this is 2 and this is 6 so the number it will be the 9 so you want to return nine so that's the problem I think you understand very well what is the concept of this problem okay you did not listen don't worry about this I write the code so definitely help to implement of your code so firstly I want to sort this array okay so array uh array dot like uh array dot sort it is nums okay then after that I need any slice the sum it will be the zero okay then after that I am using Loop it is a i equals to 0 I less than numps dot length with increment is I equals to I plus 2 y i plus 2 because firstly I pick up the first number then after it I direct go through the third number second number is missing the next number okay so that's why I'm using uh I'm using the I equals to I plus 2 then after that sum equals to sum Plus numbers I and then I want to return it sum so that's the problem firstly I again explained don't worry about this firstly I want to sort this already and after that I will initialize the number sum it will be zero and after that I am using the loop uh it will be the starting with 0 and less than num dot length we think like it is not increment by one it is increment by two because firstly I want to pick up the first number and then I'll go directly go through the third number second number is missing so that's why I'm using I equals to I plus 2 then after that line number seven I want to sum all this number then line number 10 I want to return some so that's the problem I think you understand very well you did not understand some line so please comment on this video I definitely help you Discord thank you so much
|
Array Partition
|
array-partition-i
|
Given an integer array `nums` of `2n` integers, group these integers into `n` pairs `(a1, b1), (a2, b2), ..., (an, bn)` such that the sum of `min(ai, bi)` for all `i` is **maximized**. Return _the maximized sum_.
**Example 1:**
**Input:** nums = \[1,4,3,2\]
**Output:** 4
**Explanation:** All possible pairings (ignoring the ordering of elements) are:
1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
So the maximum possible sum is 4.
**Example 2:**
**Input:** nums = \[6,2,6,5,1,2\]
**Output:** 9
**Explanation:** The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.
**Constraints:**
* `1 <= n <= 104`
* `nums.length == 2 * n`
* `-104 <= nums[i] <= 104`
|
Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4. How will you make pairs to get the result? There must be some pattern. Did you observe that- Minimum element gets add into the result in sacrifice of maximum element. Still won't able to find pairs? Sort the array and try to find the pattern.
|
Array,Greedy,Sorting,Counting Sort
|
Easy
|
2112,2248,2261
|
367 |
so hey everyone now i'm going to discuss the fifth question that is a valid perfect square from the dsa would come basically category binary search and the question is given that we have given a positive integer num and we have to write a function which returns true if the number is opposite is a perfect square else false and it is also given that we cannot use the square in will library function that is square of this qrt function so after reading the question what first comes to your mind at first it comes like the brute force approach that we will linearly search from uh one to the numbers the number which is given here like 16 and we will linearly traverse and check that the a particular number is matching with the given num that is 16 and you are returning 2 as it is perfectly matching with that given integer right but how can it be done with less complexity right so in that case let me take an example i will take example like here n equals to let's say 9 right and we will start like 1 2 so we can optimize it by applying binary search here so this is the starting pointer of the binary search this is the ending pointer and in the binary search we take the middle element so 9 plus 1 10 by 2 that is 5. and this is the middle element right so in binary search what we will see like we will compare the middle element let's say the we will take the square of these middle elements right so middle element square means middle element multiply middle element and if this multiplication becomes greater than the given number right in that case what is uh what comes to our mind like if 25 square that is 25 is greater than 9 so the numbers after to after five till the end no other number will be smaller than nine every number will be greater so there is no point for checking uh the numbers from middle to end so we will what we will do we will just take our ending pointer to middle minus one right and again we will take our middle so four plus one five by two that's two itself and yeah again we will check here what is the condition what we are getting like m square that is 2 square that is 4 is less than num right so as the middle element is smaller than the num so we will neglect our right hand side left hand side of the middle element means the elements which are present on the left hand side of the middle element so what we will do we will increase our starting pointer to middle plus one here is our starting pointer and yeah and this is our ending pointer then uh 3 plus 4 7 divided by 2 that is 3 we are getting the middle pointer here a middle one here middle element and we will again check m squared which is coming equals to the given num integer right so what does it mean that we have got our square root and hence we can return true as we have got the perfect square root so we can say that it is a perfect square and we will return 2 and if we didn't get this condition then we will at last return false that no this the given num integer is not a perfect square because no square root is present from 1 to the given number so this is the main approach and uh let's code it then it will be more clear so yeah first of all we will take the start would the start will be 1 it never be 0 cannot be the square root of any number and yeah so start and end will be n will be num so here will be the binary search condition and we will again calculate our middle media will be start plus and minus start divided by do over then we will have three conditions if middle square is greater than num then one thing else mid first mid less than number else we don't have to give the condition else that means it will be equal so what we are doing here what we are doing if it is greater then we are doing end equals to mid minus one right so n will be equal to mid minus one and here if it is smaller then it will be start equals to me plus one and if it is equal that means we got our square root exact square root not like that we have uh we have done in the square root of x question uh that 8 and the square root is 2.81 we are 8 and the square root is 2.81 we are 8 and the square root is 2.81 we are taking the integer not like that we are taking the perfect square that means we got the perfect square right so we will return over middle uh sorry we will not return we will return just two means we have got a power square else if it is not written then i will return pulse it's pretty easy let's run it's accepting let's submit it yeah it is submitting so thanks for watching if you like the video then subscribe if you have any problem comment down below i'll see you in the next video
|
Valid Perfect Square
|
valid-perfect-square
|
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_.
A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
You must not use any built-in library function, such as `sqrt`.
**Example 1:**
**Input:** num = 16
**Output:** true
**Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer.
**Example 2:**
**Input:** num = 14
**Output:** false
**Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer.
**Constraints:**
* `1 <= num <= 231 - 1`
| null |
Math,Binary Search
|
Easy
|
69,633
|
263 |
If the error is 16 everywhere, then Aditya, we will solve the problem, the next number in the name of that problem and this problem is the problem number of the court is 203, now we have seen the problem statement, the number is all positivity, definitely ask crime patrol and limited to three and five means next. The number will be that positive interior which has prime factor or Kuttu or free or 5-wicket win a t-shirt and 5-wicket win a t-shirt and 5-wicket win a t-shirt and return proof number. So we have given a number to this number and we must do it. If that number is the next number then it is fine. So look, here we have the condition of having number education and bag number. It is said that if we are given a number and the number is 345 12345 then that number will be our next number. So what happens if I am and this means our number. Now I am here. But here it has come and our number should be 235, that means our number is not there, so now look how will we see for six that we have been given six, is my 2662 equal to ours, then it means you add, then our six pack. And if I shrink and divide, what will I get, I am okay, now I will write again for free, what is free mode on two is my equal zero, if this does not happen, then I will go here, no, okay, now I will for this. I will see that I will divide my free mode exactly and I will get it and this is our next number that when there is no one so it is 12345, so what will we get from here, we will get the liquid from here and now we will put it on the side. If we do then the free mode will be 5000, of course otherwise we will also not go, so from here on, if I divide this thing as ours for free, I will get it from here also, I will see if it does n't happen, but this is one of the 235, see this is mine. The number can be said, who knows, I was already made, so how will we search from here and return it, okay? Otherwise, who knows, it is possible that my number may be given and the CO is not our number yet, okay otherwise? What can happen is that if we know that our factor is on that number then what will we do then whatever phone number we get after dividing it from the input tray, we will now check the number for that whether the problem is next or not. Let's do it here turn on that we will do the same from the week also, so it has happened to me now, when such a day turns upside down till today, saying it in the hearts of exaggeration is a fight, then the next number has not happened, otherwise we For that, we will give that much Twitter and sperm from here, so we will close it and show who is the one for 80, for the next number, we will see like Khatti and Prithu have come, then it is simple, who was our next number? Now I have explained the next number here so that we can use this concept in the upcoming question, so if you liked the video then please like, share, subscribe and do n't forget to comment. Thank you so much for
|
Ugly Number
|
ugly-number
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_.
**Example 1:**
**Input:** n = 6
**Output:** true
**Explanation:** 6 = 2 \* 3
**Example 2:**
**Input:** n = 1
**Output:** true
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Example 3:**
**Input:** n = 14
**Output:** false
**Explanation:** 14 is not ugly since it includes the prime factor 7.
**Constraints:**
* `-231 <= n <= 231 - 1`
| null |
Math
|
Easy
|
202,204,264
|
1,810 |
hello everyone let's take a look at this little problem minimum pass cost in a hidden grid it's a follow-up of grid it's a follow-up of grid it's a follow-up of only code 1778 shortest passing a hidden grid so uh if you have a parentheses problem you can practice it for since they are very similar except that the class in each cell in this problem is just one while in this problem the cost is different okay so it's an interactive problem there's a robot in a hidden grid and we are trying to get it from starting cell to target cell in this grid the grid senses of set and multiply n and each cell in the grid is the empty or blocked it's guaranteed that starting cell and the targets are different and neither of them is blocked so each cell has a cost that we need to pay each time but like we move to still the starting sales cost is not applied before the robot moves so we need to find the minimum total cost to move the robot to target sale however we don't know the grid dimensions starting cell on the target cell so we are only allowed to ask queries to create master objects the green master class has some functions like um can move function within true if the logo can move inside direction otherwise it will return first and move function moves the robot in the direction and returns the cost of moving to that stair if this move will move the robot to a block cell or of the grid the move will be ignored the robot will remain in same position and the function will connective one if target function retention of the robot is currently on the target cell otherwise it will return force so direction can be represented as udlr and our task to return the minimum total cost to get the robot from its initial starting cell to the target cell if there is no value passed between zeros we just return negative one okay so that's a problem and let's take a look at constraints the dimension is can be most 100 so it's not a very big and two-dimensional it's not a very big and two-dimensional it's not a very big and two-dimensional grid okay so what we should do is since it's a hidden grid we need to build this hidden grid so in our main function first we just define some directions udlr and we mentioned this dimension came at most 100 so we can just create a larger grid here i just initialized to 300 multiply 300 then no matter where my starting cell is i can just define set cell as 150 and in my construct grid function our constraints is great so we have a cost for the starting sales and we don't care about this cost since it were not applied so i if currently we're in target we just set this target then we just for loops four directions for each new direction we check this new sale here if this is a new sale has not been visited we will try to visit it i initialize also to negative one so at first they're not visited as long as we visit a sale like we will set some cost for example the concept five we will not visit again so if it's negative one we will try to visit it and if we can move to that museum we will try to move to that direction and we have a cost then we will recursively call and construct with function on that new set and pass its cost so it can set the cost correctly then we need to restore our state is very important for dfs function so first for example for this new cell if we go up to this new cell then we need to go down to restart the state same for if we go down then we need to go up if we cannot move to this new cell then we know it's blocked we can just set it to zero meaning this cell is blocked okay so far so good we constructed our two-dimensional grid two-dimensional grid two-dimensional grid next since the weight is different for each cell so we cannot use a normal bfs for the shortest paths like we can use the priority queue we start appearing the per or excuse the first element it's the position the second element is the cost so initially we approach the initial position 150 and causes zero to our priority queue and mark this position as vested then we just do the shutter pass solution here where the queue is not empty we will every time we will try to get the position that has the minimum cost so far in my queue for set position if it's target which can just retain it otherwise we will mark it as vested then we will try to follow these four directions for each new direction if it has not been visited we will try to visit it if it has revisited the value is negative one we will continue if it's a block uh the value is zero we will continue okay same forces new cell we just push it to our queue if there is a path there must be a point that we will reach this code path and we can get the correct minimum cost if there's no pass finally the queue will be empty and we will just return negative one okay that's it see you next time
|
Minimum Path Cost in a Hidden Grid
|
change-the-root-of-a-binary-tree
|
This is an **interactive problem**.
There is a robot in a hidden grid, and you are trying to get it from its starting cell to the target cell in this grid. The grid is of size `m x n`, and each cell in the grid is either empty or blocked. It is **guaranteed** that the starting cell and the target cell are different, and neither of them is blocked.
Each cell has a **cost** that you need to pay each time you **move** to the cell. The starting cell's cost is **not** applied before the robot moves.
You want to find the minimum total cost to move the robot to the target cell. However, you **do not know** the grid's dimensions, the starting cell, nor the target cell. You are only allowed to ask queries to the `GridMaster` object.
The `GridMaster` class has the following functions:
* `boolean canMove(char direction)` Returns `true` if the robot can move in that direction. Otherwise, it returns `false`.
* `int move(char direction)` Moves the robot in that direction and returns the cost of moving to that cell. If this move would move the robot to a blocked cell or off the grid, the move will be **ignored**, the robot will remain in the same position, and the function will return `-1`.
* `boolean isTarget()` Returns `true` if the robot is currently on the target cell. Otherwise, it returns `false`.
Note that `direction` in the above functions should be a character from `{'U','D','L','R'}`, representing the directions up, down, left, and right, respectively.
Return _the **minimum total cost** to get the robot from its initial starting cell to the target cell. If there is no valid path between the cells, return_ `-1`.
**Custom testing:**
The test input is read as a 2D matrix `grid` of size `m x n` and four integers `r1`, `c1`, `r2`, and `c2` where:
* `grid[i][j] == 0` indicates that the cell `(i, j)` is blocked.
* `grid[i][j] >= 1` indicates that the cell `(i, j)` is empty and `grid[i][j]` is the **cost** to move to that cell.
* `(r1, c1)` is the starting cell of the robot.
* `(r2, c2)` is the target cell of the robot.
Remember that you will **not** have this information in your code.
**Example 1:**
**Input:** grid = \[\[2,3\],\[1,1\]\], r1 = 0, c1 = 1, r2 = 1, c2 = 0
**Output:** 2
**Explanation:** One possible interaction is described below:
The robot is initially standing on cell (0, 1), denoted by the 3.
- master.canMove('U') returns false.
- master.canMove('D') returns true.
- master.canMove('L') returns true.
- master.canMove('R') returns false.
- master.move('L') moves the robot to the cell (0, 0) and returns 2.
- master.isTarget() returns false.
- master.canMove('U') returns false.
- master.canMove('D') returns true.
- master.canMove('L') returns false.
- master.canMove('R') returns true.
- master.move('D') moves the robot to the cell (1, 0) and returns 1.
- master.isTarget() returns true.
- master.move('L') doesn't move the robot and returns -1.
- master.move('R') moves the robot to the cell (1, 1) and returns 1.
We now know that the target is the cell (1, 0), and the minimum total cost to reach it is 2.
**Example 2:**
**Input:** grid = \[\[0,3,1\],\[3,4,2\],\[1,2,0\]\], r1 = 2, c1 = 0, r2 = 0, c2 = 2
**Output:** 9
**Explanation:** The minimum cost path is (2,0) -> (2,1) -> (1,1) -> (1,2) -> (0,2).
**Example 3:**
**Input:** grid = \[\[1,0\],\[0,1\]\], r1 = 0, c1 = 0, r2 = 1, c2 = 1
**Output:** -1
**Explanation:** There is no path from the robot to the target cell.
**Constraints:**
* `1 <= n, m <= 100`
* `m == grid.length`
* `n == grid[i].length`
* `0 <= grid[i][j] <= 100`
|
Start traversing from the leaf. Always go up till you reach the root. Change pointers as asked, make the current node's parent its left child, and make the left child the right one if needed.
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
70 |
hey welcome back today we're going to be doing leode problem 70 climbing stairs and today's solution is going to use something called dynamic programming that's right dynamic programming this concept can be pretty hard to understand so with that being said let's do it together and if you haven't already like And subscribe to the channel it really helps me out okay let's get going let's go ahead and get started by reading the statement You Are Climbing a staircase and it takes end steps to reach the top each time you can either climb one or two steps and how many distinct ways can you climb to the top for n is equal to 2 the output is two because there are two different ways to reach the top 1 plus 1 or two for n is equal to 3 there are three different ways to reach the top and our expected output is three 1 + 1 + 1 + 2 and 2 + output is three 1 + 1 + 1 + 2 and 2 + output is three 1 + 1 + 1 + 2 and 2 + 1 let's keep going with these examples so for four St stairs there are five different ways to reach the top 2 + 2 different ways to reach the top 2 + 2 different ways to reach the top 2 + 2 + 1 + 1 + 1 + 2 1 + 2 + 1 and 1 + 1+ + 1 + 1 + 1 + 2 1 + 2 + 1 and 1 + 1+ + 1 + 1 + 1 + 2 1 + 2 + 1 and 1 + 1+ 1+ 1 and then for five stairs there are 1+ 1 and then for five stairs there are 1+ 1 and then for five stairs there are eight different ways to reach the top now I'm not going to read all the eight different ways to reach the top of five stairs but you get the point there are eight different ways to reach the top okay let's go ahead and dig a little bit deeper into this problem now as you can tell we have a bit of a sub problem right we're just continually adding to different stairs and we're adding all the different combinations we can either climb one or two stairs and essentially this boils down to a dynamic programming problem why well dynamic programming problems always have sub problems and that's how you know it's a dynamic programming problem and this case specifically is a Fibonacci problem right if you're familiar with the Fibonacci sequence it starts kind of like this 1 2 3 5 8 and 13 what's the pattern is let's say I want this number three well I have to add up the previous two numbers 1 + 2 which is the previous two numbers 1 + 2 which is the previous two numbers 1 + 2 which is equal to three and if I want to reach five I have to add up the two previous numbers to that 2 + 3 8 3 + 5 13 8 + 5 numbers to that 2 + 3 8 3 + 5 13 8 + 5 numbers to that 2 + 3 8 3 + 5 13 8 + 5 okay great so now we have a Fibonacci problem we understand that let's dig a little bit deeper what about these two staircase problems two stairs is equal to 2 and three stairs is equal to 3 well I think it would be reasonable to say that if we have up to three stairs we can just return n right because it's the same amount of numbers you can see here it says 1 2 and three so one stair would be one two stair would be three two and three stairs would be three right so let's go ahead and take care of that first Edge case if n is less than or equal to 3 we're going to return n okay what about the next problem well in here we're always add in the two previous numbers how do we keep track of that well let's go ahead and add in a new array called DP and we're going to store those two previous numbers what two previous numbers well we're going to start with two and three right because we know that we can start at index 4 on the next round all the way we have the number all the way up to three right so we have all of this already let's go ahead and get started with this fourth one so if n is greater than three then we're going to start on the fourth index if that's the case let's go ahead and start our four Loop and what we're going to do is we're going to iterate all the way up until n so I is equal to 4 I is less than or equal to n because we want to go all the way up to n and we're going to say I ++ okay now we're going to create a ++ okay now we're going to create a ++ okay now we're going to create a temporary variable we're going to say let temp equal DP of 0 plus DP of 1 and then next thing that we're going to do is we're going to say DP of 0 is equal to DP of 1 and then we're going to say DP of 1 is equal to Temp and then what we're going to do is we're going to return DP of one why so let's take a look at this what we're doing is we're adding up these first two numbers right the previous two numbers and then we're switching it so we're saying two is now going to equal to three and three is actually going to equal to five so we're going to continue doing this all the way until we reach end let's go ahead and run this really quick okay perfect so we got all of our answers back and let's take notice of our time complexity and our space complexity our time complexity at the moment is O of n right because we're just looping through all the way up until n but what about our space complexity well our space complexity is currently o of n as well right because we're continually adding to this array how do we break this up well we can kind of get rid of this DP what I'm going to do is I'm going to say let num one equal 2 and I'm going to say let num 2 equal 3 so I'm going to get rid of this DP array and now all of our DP stuff is going to be from these two variables so I'm going to say num one plus num two and I'm going to say num one plus is equal to num two and I'm going to say num 2 is equal to Temp and then we're just going to return num two at the very end so now instead of O of n space we're going to always have o of constant space okay let's go ahead and submit this okay great so it ran in 60 milliseconds and it took up only 41.8 2 it took up only 41.8 2 it took up only 41.8 2 megabytes all righty folks with that being said that's all I have for today I hope you have a great day and a great rest of your week and if you haven't already subscribe to the channel it really helps me out
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
303 |
foreign mutable given an integer array nums we have to handle multiple queries of the following type we have to calculate the sum of the elements of nums between indices left and right inclusive we have to implement a num array class with the Constructor which initialize the object with the integer array nums and also the query function that could be used for acquiring will be of this format so we have to return an INT and the inputs that we are given are left and right indices so we have to return the sum of elements between left and right inclusive as you can see it's just starting from the left index all the way up to the right by the problem constraint left Android are always larger than zero and right as always larger or equal to left so we don't have to worry about that but it's a good question for your interviewer and it's also always lesser than the length of the array uh we also have at most 10 to the four calls made to the sum range and this is the nature of the elements that we have so we have this range for the elements in the array the important part here is that we could uh for the Constructor we could just uh insert the elements in our array that we hold in a class and then on the querying we could just iterate over the array starting from the left index all the way up to the right index and just calculate the sum in that fashion but that would be that would mean that we will have uh linear driverplexity because we if we range query several times uh from the index 0 all the way up to the uh index n minus one we will it will be proportional to the length of the array and because we have a symmetry here we are only writing once and reading several times we kind of have to shift the word to the right operation to the Constructor and have some optimization on reading one querying to get the result uh faster so this the just iterating over the elements you know on query will not work uh we have to be more creative to solve the problem we will have to use something called prefix sum and let's go to the details what the prefix sum is so you can think of prefix sum the total value total sum of uh numbers before the current index so for example prefix sum for the index 2 in the input array should be the total value for a total sum of the values for all the indices that come before two in this case those are indices zero and one so -2 plus zero will be -2 and as you -2 plus zero will be -2 and as you -2 plus zero will be -2 and as you can see here the minus 2 corresponds to the this is our prefix sum for this array let's say for example for the index 4 we will have all the numbers bit before it so minus two plus zero is minus two plus three is one and one minus five is minus four so for the index four in the original array we will have minus four prefix sum for the uh in the prefix sum array as you can see we all we do have that and here this is the example from our problem statement and these are the queries that we will run on the on this example so for uh for the first case we have zero and two zero is the left index and two is the right and so we start from this number so and end up includes it's encloses so we will also count this number so it will be minus two plus zero plus three which will equal to one as you can see here the second example we have two to five so it will be three minus five is minus two plus two is uh zero and then minus one will be minus one for the whole array 0 and 5 we will have -2 plus 0 is minus 2 plus 3 is 1 minus -2 plus 0 is minus 2 plus 3 is 1 minus -2 plus 0 is minus 2 plus 3 is 1 minus five is uh minus four and then uh plus two is minus two and then minus two minus one will be equal to minus three now this is uh this is easy when as we said when we are iterating over the numbers in the range from left to the right index but can we use the prefix sum that you will construct on the right operation that should only happen once uh can you use it to uh get the result in a constant time complexity so in constant time as it turns out we can so we can use uh the this formula and I will call the prefix sum SP as for each of the queries we can use write plus one minus prefix sum of left to get the total sum between the ranges with between the indices left and right so we can see that on an example for let's say two and five so let me just change quickly the color so two and five this is what we want to get so uh we have this formula so right uh write the SQL to 5 and left the SQL two and if you use the prefix sum it will be PS 5 plus one minus PS of 2 which is equal to this is PS of six so prefix sum of six is minus 3. so minus 3 minus PS of 2 which is uh which is -2 here and this will so we have two minuses which is equal to plus two and this will go to -1 which is the result of 2 and 5. go to -1 which is the result of 2 and 5. go to -1 which is the result of 2 and 5. the reason why this works for all of the cases is that because of the nature of the prefix out the prefix sum for each of the indices represents all the numbers up to that index the sum of all numbers up to that index so for example if you have two and five we are interested for uh in numbers ranging from the index 2 to towards the index 5. so first we can get the total sum so this is like you can call it imaginary index here at the end of the array which basically covers the whole sum that's why we need write plus one and this here index in the pre in the prefix sum it will correspond to this we'll uh basically represent the sum of the whole array so if we wanted to get the sum of the whole array so 0 and 5 from 0 to 5 it will be equal to -3 and 5 from 0 to 5 it will be equal to -3 and 5 from 0 to 5 it will be equal to -3 as you can see here remind minus three but in this case we want to get it from two and five so this uh this index here represents the sum of all numbers from 0 to 5. because those are all numbers that appear before the index six and that's only half of the half of our uh half of the things that we need we also don't want we want to discard the uh these numbers because we want to start from the in index two and we can discard them by just reducing the total sum by the sum of all the numbers that come before 2. before the index 2 and those are number zero those are numbers located at index 0 and 1. and how do we get easily the uh that sum well we can use the prefix sum of the corresponding index we can use the prefix sum of two because prefix sum of two corresponds to the total sum of all numbers before the index two so to get uh the total sum from uh two to five we first include all the numbers uh and then discard the these numbers that are coming before uh before the starting index before the left index to do that we just need to subtract the prefix sum of the left index and that basically solves our social problem let's solve the problem using Java programming language first we will decree our declare a prefix sum as a profit private variable in the class and uh we will clear the current sum which we'll use to calculate each of the elements in the previous summary the altruers over the input array each time adding the current sum to the prefix sum array the next step of the last step of the loop is actually to add the current value uh to the current sum so it can be reflected in the next uh element of the prefix so uh after we are done with the for Loop we have to have an extra addition to the prefix sum which corresponds to the sum of all elements in the input array if you remember from our last example we had the element uh we had the last element at the index six uh was representing the sum of all the numbers and in the input array and the last inputting the input array was actually uh index 5. to and that basically completes our write operation on read we will just get the prefix uh the element that the index right plus one of the prefix sum array and we will to basically get all the numbers up to the right plus one which includes also the element and the at the index right and then we will discard or in this case subtract the effect the sum of the all the elements up to the index left which corresponds to our prefix sum element located at the index left that piece recovers both the right and read operations read operation in this case is constant because we are just uh getting the element inside our array and uh for the right operation we have a linear time complexity because it just takes to iterate over the input array
|
Range Sum Query - Immutable
|
range-sum-query-immutable
|
Given an integer array `nums`, handle multiple queries of the following type:
1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`.
| null |
Array,Design,Prefix Sum
|
Easy
|
304,307,325
|
461 |
what's up guys welcome back welcome to another coding every question on late code so this question is about Hamming distances so it says the Hamming distance is the distance between two integers is the number of positions at which the corresponding bits are different so given two integers one in X is one and Y is four the questions at which the corresponding bits are different is this one and like this one so the number of questions at which the corresponding bits are different is two that's why the output is 2 so the way we are going to solve this problem is so we are going to do a right shift every time before doing like so every time we do right shift we actually consider the most significant bit or the MSB or the uppermost bit we are going to do XOR of this one so if one XOR 0 is 1 which means the bits are different and then we increment the counter so then after like we do a right shift again on right shift on this one and do the XOR on more significant bits and increment the counter by 1 if we get 1 so let me show you that in code let us take a counter let's look through this given number so we increment the counter if the leftmost bit of eggs ik soaring with leftmost bit of Y so this is the leftmost bit of X and leftover sweet of Y we are going to do XR so if the XR is one we don't think we'll increment the counter and we are going to right shift X and right shift pi so one why I am using like right shift to be filled with zeros this one is like it works for both boys two negative numbers okay so let's run this test case oh I forgot given the number what's that so here X is nonzero or Y is not equal to zero okay I think so the time complexity of this is because and because we have only one load and the space complexity is one because at a time we are storing only one grid like only there one counter variable so hopefully you liked this please hit the thumbs up button and stay tuned for next videos and see you again back
|
Hamming Distance
|
hamming-distance
|
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different.
Given two integers `x` and `y`, return _the **Hamming distance** between them_.
**Example 1:**
**Input:** x = 1, y = 4
**Output:** 2
**Explanation:**
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
**Example 2:**
**Input:** x = 3, y = 1
**Output:** 1
**Constraints:**
* `0 <= x, y <= 231 - 1`
| null |
Bit Manipulation
|
Easy
|
191,477
|
690 |
what's up everyone today we're gonna be going over a leak code 690 employee importance now I'm not sure why there were so many downloads for this one but this is a pretty standard BFS grasp graph traversal they give us a custom class that has a ID importance per employee and then a list of integers who are that employee subordinates I drew the graph for the given example and this is pretty much what it looks like employee of one has a value of five and he has employees two and three as his subordinates so employed one has about two and three as his subordinates so he has two and three supporters these guys each have a value of 3 so the question asks if I give you an ID tell me the value the total value of that person and all the subordinates blown okay so this is gonna be solved using BFS of course a Q and we'll be making use of two hashmaps one for the adjacency list of a graph and one for the importance because when we're iterating in the beat and the BFS loop I need to keep track of how much each employee is valued so let's get into it so the first thing is going to be a map of integers in the list of integers this is gonna be the total map which is the adjacency list and then I'm gonna have a map of values which is pretty much gonna be like when play one has 5 2 has 3 and this one is just gonna be the adjacency list we should all know what that is okay so and now we have four employee II through MP we're gonna have map doc put eat , he died yeah is it get map doc put eat , he died yeah is it get map doc put eat , he died yeah is it get no it's gonna be a dot sub luckily it's his the class is made of a list of integers for the subordinates and then it's gonna be value they're gonna be dot put e come on e dot importance Oh II got ID there's a dress sorry e dot ID comma edid so this is gonna build them two maps that we need now we can get into the iteration so list a cute a queue of integers Q's new linked list as the instance instantiation of it and then let's add Q dot ad okay so that they want a result at the end right so let's actually make a inte R is so this is gonna be initialize to 0 this is what we're gonna return at the end of Q dot add ID so this is gonna be the source origin and then res is gonna be incremented by map not map value we have a value map now so let's just get into it valued get ID now while okay and we also need a visited set because this is a binary BFS so set integer r is for visited is new 7 what you guys are smart you already knew that wow the queue is not empty what we're gonna do is we're going to pull each one so int @e is gonna be cube pull and I wonder if I should add it here no the first one has already been added so I don't think I should add it in there queued up pull should be for int J through T met okay not on a map dot get T what I'm doing right here is I'm popping the first the pulling the first person in the queue then going through that person's list of employees and if it's not visited then I will add Q dot add J set or visit vis I called it vis right let's call it yeah there's no add J I added this in there and then I'm also going to increment result by value from the value map dot get J so that's the if loop that's the for loop that's a while loop what this ensures is that I'm not visiting any more employees than I need to I get all the values that I need an increment res and then I just have to return rest okay and that's pretty much how you solve we code 690 if you made it through the video congratulations and thank you if you liked the video please subscribe like and comment below on whatever you want to see Thanks
|
Employee Importance
|
employee-importance
|
You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees `employees` where:
* `employees[i].id` is the ID of the `ith` employee.
* `employees[i].importance` is the importance value of the `ith` employee.
* `employees[i].subordinates` is a list of the IDs of the direct subordinates of the `ith` employee.
Given an integer `id` that represents an employee's ID, return _the **total** importance value of this employee and all their direct and indirect subordinates_.
**Example 1:**
**Input:** employees = \[\[1,5,\[2,3\]\],\[2,3,\[\]\],\[3,3,\[\]\]\], id = 1
**Output:** 11
**Explanation:** Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.
They both have an importance value of 3.
Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11.
**Example 2:**
**Input:** employees = \[\[1,2,\[5\]\],\[5,-3,\[\]\]\], id = 5
**Output:** -3
**Explanation:** Employee 5 has an importance value of -3 and has no direct subordinates.
Thus, the total importance value of employee 5 is -3.
**Constraints:**
* `1 <= employees.length <= 2000`
* `1 <= employees[i].id <= 2000`
* All `employees[i].id` are **unique**.
* `-100 <= employees[i].importance <= 100`
* One employee has at most one direct leader and may have several subordinates.
* The IDs in `employees[i].subordinates` are valid IDs.
| null |
Hash Table,Depth-First Search,Breadth-First Search
|
Medium
|
339
|
1,980 |
hey everyone today we are going to solve theal equation find the unique binary string okay so let me explain with this example so 0 and 01 so my idea is simply to convert these binary strings to decimal because creating and comparing decimal number is easier than creating and comparing binary strings especially creating so for example so we will we get a z as a zero of binary string so typically binary is um just at Zero so we need to add zero until we meet the length of n so it's time consuming and complicated right so that's why we convert this binary strings to decimal number so in that case so z0 is zero right and Z 01 is one so okay so we use set and uh having a decimal number so zero and one and then uh iterates through decimal numbers like from zero to length of input array plus one in that case until uh two 0 one two and then in this case we have so zero in set and we have one in set and uh but we don't have two in set right so that's why uh in that case we need to convert two to Binary string so in the end output should be one Z yeah so that is a basic idea somebody wondering why we need to iterate through with length of input array plus one so the description say given array of strings nums containing any unique binary strings each of lengths n so all possible answers of binary string for this input array should be 0 1 Z 1 one but we have the first two numbers of binary strings that means Z and one right so there are cases where we already have the first few numbers so in that case we need to find a larger number than length of input array in this case two or three so that's why plus one enables us to find the output definitely okay so let's write the code first of all so let's say s and uh use set first of all convert binary strings to um decimal number so for binary string in nums and S add and we use int and binary string and this is a binary so that's why put two here and then um uh calculator length of um each data so n equal now length of nums zero and then uh try to find like a missing number so for I in range so until rength of nums plus one and then if I not in scene so that is a missing number so we need to convert current I to Binary string so return so we is being this is a building function and I and start from two to last and then um Z few and the length should be n yeah so let me explain this part okay so let me explain a part of my solution code here this is a little bit complicated but I'll explain one by one so let's think about this input case 0 and I change this so now we have one and uh so set will have zero and three right so in this case um since we iterate through from Z to length of input array plus one so output should be F missing 01 right and uh look at this picture so left side is decimal number and the right side is a binary number and Z is zero right and one is one and the two is one Z and the three is one so in this case a missing number is one so typically um we return just one right in this case output is correct but if we return just one string like this we will get the wrong answer because uh um output also need length of n so that's why U I do like this so first of all um I convert current decimal number to a binary number with this part and uh when we use a being function the first two character is kind of a prefix so uh which we don't need this time so that's why we remove the first two number and that's why start from index two to last and then we will get a correct binary number and then um but we still have a problem right output needs length of n so to fill the Brank with zero so we use a z F and N is until like how many so in this case uh two right so that's why here we put two so in the case um I think this part we get one and then add zero uh here no space so 0 one like this so until length of two and then we will get the correct um like a format okay so let's go back to our solution code and then we passed all test cases and be 70% then we passed all test cases and be 70% then we passed all test cases and be 70% and the time complexity of this solution should be I think o n Square so that's because we iterates through all numbers from zero to length of n plus one and uh when we find the target number um I mean missing number uh we try to create the binary string with a filling blank with zero so I think uh um in the worst case um we have to put um zero um like almost equal to length of n so that's why I think o n square but um o n Square will happen only when we find the answer number so for the most part we just have o time and the space complexity is I think just o for seeing yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Find Unique Binary String
|
faulty-sensor
|
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_.
**Example 1:**
**Input:** nums = \[ "01 ", "10 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "00 " would also be correct.
**Example 2:**
**Input:** nums = \[ "00 ", "01 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "10 " would also be correct.
**Example 3:**
**Input:** nums = \[ "111 ", "011 ", "001 "\]
**Output:** "101 "
**Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 16`
* `nums[i].length == n`
* `nums[i]` is either `'0'` or `'1'`.
* All the strings of `nums` are **unique**.
|
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
|
Array,Two Pointers
|
Easy
| null |
69 |
hey guys how's everything going let's take a look at number 69 wow it's a good name for good number right okay that's uh we need to implement our own square root function the X is guaranteed to be non-negative so it might be zero the non-negative so it might be zero the non-negative so it might be zero the result this could be just rigged truncated and we need to return the right number which is just a smaller than the possible I'm design than the solution wow this is a pretty straightforward I think actually there are a bunch of numbers are non-negative so zero right one zero are non-negative so zero right one zero are non-negative so zero right one zero one two and go to X we need to just pick the number right equal or smaller than X that square of it so this leads us to the by the research right it's first pretty straightforward so just do it this is ero a j equals x Wow well we need to find the right number which is smaller than it so it we should stop when I and J met right we always keep the possibilities within that range so while I smile NJ yeah constant middle which okay meet math which one should I pick Peggy we're from the witches floor or sill let's say some is a number I and J middle J if because we're we are going to keep the one in our loop ray loop right if I if middle is the square of middle is smaller than X then we should move I to middle or two media plus 1 because middle is possibly that middle E is possibly the solution so we can move cannot move I tomato one plus one but move I to middle in that case we features floor B middle if I mean if I is the J is I plus 1 then we go well bi again so we cannot do that right if we do that it will go it will be infinite loop so which is sill of course we can do the top is the way we will try that later if first which is the seal which means if that means if I equals J plus 1 middle would be J ok and now let's say cons to square equals needle if square is just to write the answer we trade middle square and X what should we do because it's smaller the meet needle might be the answer right we're going to find the right number which is a number which is just smaller than the than a solution so we move I to middle and if you speaker than it because it's bigger than it's definitely cannot be our answer so we can just safely move J to middle minus 1 and so this will just be smaller and smaller if we choose seal we just we keep I to the middle and J to the middle minus one so this won't create a they won't generate an infinite loop and finally the I and J will meet right so the last number in the array is the last number it's the last number which is just right smaller than rice more than the possible solution right so we didn't just return I right yeah let's run the code Kui it seems to work the binary search so the time Wow lock X right it's pretty straightforward hmm okay it's good enough now let's find it out let's try to think of this problem in other way now we're not keeping the possibilities in the wrench in the I J Ranch right let's try to find the number which is just bigger than just 2 bigger than the just bigger than our solution well in that case we just to do similarly we explore right if I see a meter would be I so if now you if we just move set I to middle then you will create infinite so we move our I 2 plus 1 now if it is bigger but it might be the possibility so we need to keep in a wrench so we set J to middle and finally there will be only one number which is just right bit bigger just bigger than our solution so we return J minus 1 right if that if this but this is a possibility before we use I it's okay because I start with 0 it can be only bigger than zero or larger than equal or larger than 0 and now we return J minus one is there possibility that J could be zero let's say I equals zero and J equals 1 and middle would be the middle would be 1 so J would be 1 so there is no possibility that J could be 0 ok we're safe to go let's submit Oh No huh my bad ah yeah because J could be zero the X could be 0 if two zeros it will stop Jay could be zero okay this is a rare case edge cases for effective for our lease see sealed same problem as are the floor solution so X and X more than one return X if you seek 0 return 0 submit again if you work this time if J is 1 in our solution it will stop at one oh we made a mistake why because if J because Jake took a seal a floor ah yeah because we took the middle to the floor we took the floor there is something wrong with our solution yeah which is the floor and if it's smaller we set it to plus one so I will be J right but actually for 0 1 & 1 actually for 0 1 & 1 actually for 0 1 & 1 we haven't checked the J yet yeah I really don't like the way I do it should be X but seems our solution doesn't have any problem here yeah it's accepted so the edge cases for one hmm it's not that arrogant than the first solution right we don't have any edge cases here the old problem is becomes J minus 1 y aha I know for any numbers that bigger than 1 it will be 0 1 2 like 4 - right than 1 it will be 0 1 2 like 4 - right than 1 it will be 0 1 2 like 4 - right so - 2 cannot to the square of 2 could so - 2 cannot to the square of 2 could so - 2 cannot to the square of 2 could not be 2 so we can safely just divide it by half but for 1y itself is 1 yeah this is the edge cases hmm so I remain recommend using the first one this one is much we just keep it straightforward just do it in a straightforward way we keep the possibilities always keep to keep the right answer within our range and finally when I meet Jay it must be that number act but in a second solution we find the next number if we find next number we need to care whether it has the previous number or not hmm this is our lesson yeah that's all for these problems see you next time bye-bye
|
Sqrt(x)
|
sqrtx
|
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well.
You **must not use** any built-in exponent function or operator.
* For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.
**Example 1:**
**Input:** x = 4
**Output:** 2
**Explanation:** The square root of 4 is 2, so we return 2.
**Example 2:**
**Input:** x = 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
**Constraints:**
* `0 <= x <= 231 - 1`
|
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
|
Math,Binary Search
|
Easy
|
50,367
|
235 |
to look at a legal problem called lowest common ancestor of a binary search tree so company binary surgery find the lowest common ancestor of two given nodes in the binary search tree so basically we're given a two nodes p and q as the lower lowest note in t that has both p and q right so we want to find the lowest um lowest parent right the lowest ancestor um that both contains p and q as um as the kernel's descendants right so you can see we have a tree and this is a binary search tree so we have p and q the lowest common ancestor basically six because six contains uh two and eight as the as its sentence right and you can see we have another example like this we have two and four so the common ancestor can be the descendant itself right or in this case the either p or q right so you can see node two um contains a child note of node4 as well as it also contains the current node's node 2 which is equal to p so this will be the ancestor for both p and q right we also have example three you can see we have uh p is two q is one so the common ancestor is basically two right so this question is really similar to the uh lowest common ancestor for uh a binary tree so that problem um because that problem is not a binary search tree so what we have to do is we have to do a pre uh postwar traversal to traverse the left towards the right to see if one side has a commonest uh has a descendant if one side has a descendant and the other side doesn't then that means that the other the left side has the lowest common ancestor right and if both side has a descendant then in this case the current node is basically the ancestor right so in this case what we can do for binary search tree is different is we can be able to solve this problem by using binary search right and the thing about binary search is that we can be able to um control the range right so for example what we can do is that we can use a pointers right or sorry in this case we can just navigate based on the range in this case we have a range right the range is basically the smallest value between p and q and the max basically or the right is basically the maximum value between p and q right so what we're going to do is that once we have our min and max we're going to say while the root is does not equal null just like binary search right we get our current value we check to see if current value is bigger than min and max if it's bigger than the min and max right so for example if p is two four is uh q is four right and in this case um they're all smaller than the max let's start smaller than the current nodes value then we had a surge on the left side right if the p is eight and then q is nine then we have to search on the right side because they're all bigger than the current nodes value so what we can do is we can be able to change the route right change the current nodes pointer so root if it's all bigger than if it's if the min and the max are all less than the current notes value then we can just search on the left side if p and or if p and q they're all bigger than the current roots value or the current dose value we can just search on the right side we just get root is equal to root.right if we have a is equal to root.right if we have a is equal to root.right if we have a situation right where we are where current node's value is equal to min or current node's value is equal to the max or if we have a situation where kernel's value is between min and max then we can just break and return the root right so we're basically just performing our binary search and trying to solve this problem trying to find the lowest common ancestor right and you can see that for this algorithm the time complexity is basically big o of login right because we're um searching using we're basically using binary search to search so the time complexity is log in and it's base complexity in this case basically constant right so we're just using pointers uh or just pointer to manipulate right so we're using the root pointer to control which side we want to search right so there you have it and thank you for watching
|
Lowest Common Ancestor of a Binary Search Tree
|
lowest-common-ancestor-of-a-binary-search-tree
|
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
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 = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8
**Output:** 6
**Explanation:** The LCA of nodes 2 and 8 is 6.
**Example 2:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4
**Output:** 2
**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[2,1\], p = 2, q = 1
**Output:** 2
**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 BST.
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
236,1190,1780,1790,1816
|
1,786 |
hi everyone welcome back to the channel today let's solve a very good question from the weekly contest number of restricted path from first to last note and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic legal questions with clear explanation animation and visualization now let's look at a question in this question there's an undirected weighted graph and we are given a positive integer n which denotes that a graph has a notes labeled from 1 to n and an array edges where each edge h i is u i v i and weight i it denotes that there's an edge between the node ui and vi and its weight is equal to weight i and here we define a path from no start to node n is a sequence of nodes from z 0 to z k such that z 0 is start and z k is n and there's an edge between every adjacent node and the distance of a path is the sum of the weights on the edges of the path and we use distance to last note x denotes the shortest distance notice that it has to be the shortest of the path between node n and node x and we say a restricted path has to satisfy that distance to last note zi has to be bigger than distance to last note z i plus 1. and we have to return the number of restricted paths starting from node 1 to node n which is the first and last node in a graph the question statement is not very clear and a bit of confusing so let's take a closer look of example one we have five notes and the black number in the circle is a no number and the number on the edge is the edge weight and the blue number in a circle is the shortest weighted distance from this node to the last node so for example for node 1 the shortest distance from node 1 to a node 5 which is the last node is 4 which is this path and then the shortest distance from node 4 to node 5 is a 6 which is this route 2 plus 3 plus 1. and the first restricted path in this example is path one two five and why this is a restricted path that is because the distance from node one to node five is four is bigger than the distance from node 2 to node 5 which is 2. and the other restricted path is path 1 2 3 5 and the distance respectively is 4 2 1 and 0. and they are in monotonic decreasing order and the last restricted path is path 1 3 and the distance is 4 1 and 0. so for this example there are three restricted paths in total to solve this question there's a two-step approach the first there's a two-step approach the first there's a two-step approach the first step is we have to find the shortest path from every node i to the last node n in the graph and we can use the keystra algorithm to find the shortest path in undirected weighted graph and next step is to use a dfs that first search with memorization to find the restricted path the total number of restricted path with the constraint now let's look at the code okay the first part of the code is to build a graph based on the input edges and here we will use a hashmap adjacency list to denote the graph and next we will create a dikestra function which will generate a distance array based on the dagistra algorithm and the distance array represents the shortest distance from each node to the last node and lastly is a dfx function and a dfx function will return an integer which is a number of restricted path and the base condition of the dfs function is if the input start is equal to n the last node then we would return one it means that we have found a path to reach to the last node and in the dfs function we will iterate through every neighbor of start in a graph and once we found that distance start is bigger than distance neighbor then it means that it will be possible to find a restricted path and then we will dfs into the sub problem and return a rest at the end now let's see the coding action for example one with the given input edges we can generate a graph hash map like this and in a hash map the key is a label of each node each vertex in a graph and then a value is the adjacency list and in the list each item is a tuple and the first item is a tuple is the weight of that edge and then the second item is uh its neighbor of that note so for no one it has neighbors uh two three and 4 and the weight of the edges is 3 and 2. and with this graph hash map we can generate the distance array with the keystroke algorithm and the distance array is 42160 it means that the shortest distance from node 1 to node 5 is 4 and the shortest distance from node 2 to node 5 is 2 et cetera and once we have the graph hash map and distance we can start to run the dfs function so we will start from dfs 1 which is the first note in a graph and then we will iterate through every neighbor of no one so for its first neighbor node 2 we found that the distance the shortest distance from node 1 is 4 which is bigger than the shortest distance of node 2. so it means that this can be a possible restricted path so we will dfs into the subproblem and remember that the base condition of dfs is if start is equal to the national end then we will return one so dfs at the end will give us the number of total restricted path so following this process we can find these three restricted path one two five one two three five and one three five so the output for this example is 3 and this will conclude the algorithm finally let's review so the intuition to solve this question is a two-step process question is a two-step process question is a two-step process the first step is to find the shortest path from every node i to the s node n in the graph and this can be accomplished by dicastra algorithm and the second step is to use a dfs with memorization to find every restricted path in a graph and the time capacity of this approach is from the dikestra algorithm which is big of m times log n and space complexity is big of m plus n to build the graph hashmap and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one
|
Number of Restricted Paths From First to Last Node
|
count-the-number-of-consistent-strings
|
There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`.
The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A **restricted path** is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`.
Return _the number of restricted paths from node_ `1` _to node_ `n`. Since that number may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2,3\],\[1,3,3\],\[2,3,1\],\[1,4,2\],\[5,2,2\],\[3,5,1\],\[5,4,10\]\]
**Output:** 3
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The three restricted paths are:
1) 1 --> 2 --> 5
2) 1 --> 2 --> 3 --> 5
3) 1 --> 3 --> 5
**Example 2:**
**Input:** n = 7, edges = \[\[1,3,1\],\[4,1,2\],\[7,3,4\],\[2,5,3\],\[5,6,1\],\[6,7,2\],\[7,5,3\],\[2,6,4\]\]
**Output:** 1
**Explanation:** Each circle contains the node number in black and its `distanceToLastNode value in blue.` The only restricted path is 1 --> 3 --> 7.
**Constraints:**
* `1 <= n <= 2 * 104`
* `n - 1 <= edges.length <= 4 * 104`
* `edges[i].length == 3`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= weighti <= 105`
* There is at most one edge between any two nodes.
* There is at least one path between any two nodes.
|
A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force
|
Array,Hash Table,String,Bit Manipulation
|
Easy
| null |
1,703 |
hey everybody this is larry this is me going over q4 of the bi-weekly me going over q4 of the bi-weekly me going over q4 of the bi-weekly contest 42 uh minimum adjacent swaps 4k consecutive ones uh so hit the like button it's a subscriber and join me on this card let me know what you think about this problem uh so the short answer in case you're wondering how i got this so quickly is because i've solved this form before and not only have i solved this problem before i actually wrote an editorial about it so um so it's a little bit uh lucky on my end i suppose some holiday spirit um but i'm gonna do my best explaining it but the live portion is probably not as interesting because it's just me copy and paste and then making some minor adjustments for this problem um or like for the input but yeah so the first thing that i would i think thought about when i opened this form today uh was that okay there is some sliding window we know that we have to get you know given k consecutive ones i mean i think the and if you're not familiar with sliding windows i definitely um recommend practicing that for a few times uh because this is a hard problem to learn sliding windows on so uh so now for the rest of the video i'm going to assume that you're very strong at sliding windows otherwise um yeah because this may be a long explanation so i don't want to describe just the sliding window portion but let's say you have a window of um let's say you have a window of all the consecutive one of k consecutive ones right and you know let's say you have already have the window and we have um yeah and that's basically the idea um and then the idea after that is okay how do you know you could figure out how much it costs because um and this is uh done in other similar leeco problems so it's a little bit tricky but the idea is that okay the minimum smop will be the one that you know you move uh toward the middle element right and you could kind of prove this because um well first of all you know let's say you have this uh window um well you never want to swap two once because it never makes sense so you only want to swap zeros and once because if you swap two months you didn't change anything instead you just get more moves so you only want to swap zoom once and as a result you always want to move the median um if k is even then you can also do the map it doesn't really matter that you know as long as you choose a number uh location in the middle then you swap to the middle um i'm not going to explain that part too much um because it'll be one of those exercises i left at home type thing try to prove that if you move the ones toward the median that'll be the minimum for that window so then the tricky part is okay now we have a window we know the cost function um how do we translate the sliding window as we slide right because the tricky part is okay um with sliding window almost like a dynamic programming problem but not really not in the same way is that okay um with a sliding window problem let me scroll down here so i could do some visualization um ideally sorry about that my computer is being a little bit slow right now ideally you know you have some string i mean i'm just gonna write them as you know whatever man like i apologies for this lag my computer is actually i don't know why it's been so slow okay there it is but it's my chrome mist maybe my i don't know what maybe some stuff is running in the background but yeah but now basically if you look at a sliding window now i'll uh highlight that by drawing a segment and you know so basically as you move from left to right uh keeping the number of ones constant my apologies for how long this visualization is taking but uh but yeah but basically well so the two parts of a sliding window that uh i would think about which is me drawing this ascii all right no uh okay right so basically um what we want to do is we want to reuse the middle part the overlapping part of the sliding window as we move from left to right so the overlapping part we want to make sure that we want to reuse it or in a good way and then we want to have a efficient way to remove the left and then we move the right um there are other ways to solve this but this is my the way that i did it the last time i did this uh with the sliding window so then basically the way that i did it is that okay if you write out the formula for median you have you're going to have um you know uh x sub m minus x sub i for all the eyes that are like the indexes right and then you know you minimize that but another way that i don't about it is that is thinking about it another way um and this is a little bit tricky hopefully i can draw a little bit better okay this draws a little bit better not that much better um but basically let's say we have uh you know let's say that is the median number uh let's say you know this is our window um i'm gonna add a little bit more zero so that doesn't look like it's too regular okay so it's something like that right um let's draw a little bit on the left as well so let's say we have something like that and this is our median right well what i did is i count okay you know the next one is one zero away the one the next one uh zero after that is two zeros away right and in a way that's basically all i'm going to keep track of as i move the windows from left to right um as i pop off i go okay let's say i move the median from here to here what does that mean right well that means that if i put things in a stack um i'm going to pop up the two and then now it's to be one and a three on the left side of the stack and uh and on the right side i have zero and then also you know let me draw this visualization to be more explicit um on the right side of zero and four oh sorry one zero and four zeros right so then now you can think about it uh the way that i thought about it is that okay if i have these as you know my zeros are stacked i have a two and then one on the right side and then a three and a one on the other side two and a one on the left side and a three and a one on the right side right um and then now we change it to let me just put it here because it's a little bit maybe better for visualization i don't know uh a lot of ascii art but um but yeah now on the new median now you can see that web one three on the left side and one and a four on the right side right um so now hopefully this builds a visualization that you can kind of see where my intuition is at and the rest of it is just figuring out the formula um so basically you know you have a queue of sorts or a stack of sorts and then you know we pop off this two and then we add on a four and i just do some uh a lot of tracking on what's on the left and on the right and i do some formulas to get the answer and we're gonna don't worry about um you know i just want to go over the visualization first now we're gonna go over the code together and you'll see what i mean hopefully in a clearer way um cool so basically yeah i keep track of the left index and the right index and i actually have really good comment on this code if you see this during the contest because i as i said i wrote this editorial so i left the comments in but yeah so basically the count of zeros that are closer to the left so we basically create um you know these numbers to the left and we wrote the sum of the distance to the left um again because so basically the way that i think about it is that for example this has a two and a one so together this one has to uh do one swap to get to the right and this one has to get one and so two swaps to get to the first one and then one additional swap so in that way it's kind of like a prefix sum if you want to think about it that way but that's basically how i kind of collect my cues um so yeah so that so i keep track of my cues uh explicitly on the left and on the right um you could think of them as stack as well but i you know uh but you know i have access to the middle that's why uh you know i use two cues um and then here we track the number of ones in the sliding window and this is just a big man um this is the current number of zeroes that are trailing until we hit a one so that's basically just like uh like an in memory just keeping track of you know the current situation um so if so now if we see a one this is where the magic happens if we see a zero uh we just keep we just add that to the number of zeros right so that's basically what i'm doing here if it is a one well we add the number of ones you know do the number ones and as usual uh we add to the right side of the queue the right queue um the current running total that's just the number zero one total has the number of zeros right so basically that is for example that's just uh me adding the four to the right side um so that's basically what i'm doing here um and then here this is just the count of the number of ones to the right this is the sum of the uh cost of shifting all the numbers from the right to the right this is almost like a prefix in this case a suffix but this is similar to a suffix some that's how uh i'm doing this is that okay you know um the total numbers this is going to be four right for example uh for this four well this running total means that there's five total zeros to the right side and that also means that the new one will take five uh swaps to get to the middle it's a little bit tricky for sure but that's basically the idea um yeah and then now the other part is that okay i mean i think i went over to getting rid of the two well not yet but we do talk about getting the four put in but then the other thing to notice is that okay well this three swap from the right side to the left side so we have to do the math that way this is you know like i said the visualization is uh the hard part once you have the visualization you can do the math it might be slow it you may take a while and to be honest the first time i've done this uh did this problem um it took me a long time to kind of be really careful about the math so the math is actually hard as well um but yeah but basically i moved it to the from the left to the right because these zeros are now you know from the left side to the right side um so yeah the shifting stills are you know the first element uh on the right side now i remove it from that prefix sum as i talked about and these are formulas that you know like i said um you know practice figuring out why this is the case but the logic comes from a prefix sum type solution and then i move that same number to the left um also in a reverse prefix some kind of way but you just move it to the left and then you append the same thing to the left and then of course we want to remove the actual thing to from the right side and put it to the left side and that's what these two line does um and then here we actually pop the at the left side of the code um or left we get rid of the leftmost one and this is just basically um the math that does this uh again this is like a reverse prefix sum so um yeah and then at the very end um but yeah uh basically this is just us uh keeping track of the um uh the left number this is just cleanup uh of the left index it uh i actually don't think i use it that much i don't um i think this is just for show to be honest uh because i actually it seems like actually i don't use this um but the reason is because where because um i like to make things explicit but the reason why we don't use this is that we have an implicit left index because uh we pop things off about q left so this is actually unnecessary but um but it's there and then yeah if the number of ones is equal to k then we um that means that in the window we have the exact number of k uh k ones so then the current cost is just equal to the cost of the left side moving it to the middle and the right side moving it to the middle which is basically this thing and then we take the min of that and we move the right index we return the best answer and that's pretty much it uh i mean i know that i hand waved a little bit over the actual math it's not hard but it's not easy either definitely try to push yourself to uh learn this but the idea is prefix sum uh and these formulas reflect prefix sum you can also rewrite this in a prefix some uh friendly kind of way and i guess that's a pretty requested for this problem as well um but yeah into in terms of comp in terms of complexity uh there's a lot of operations but they're all you only do a constant amount of them even though there are many of them uh because we look at each cell at most constant number of times and constant number of operations this is going to be linear time uh in terms of space it could be all ones in which case um you know these cubes would be you know in the thing so it's gonna be um linear space as well uh so linear time linear space you can shouldn't be able to do that less than that let me know if you have a better case um that's all i have for this problem uh i'm not going to um i'm debating whether i should just show me something during the contest but to be honest is just copy me copying and pasting it and then making minor adjustments to the problem so i'm i might just skip that uh let me know what you think about this problem um and i will see you uh later
|
Minimum Adjacent Swaps for K Consecutive Ones
|
put-boxes-into-the-warehouse-i
|
You are given an integer array, `nums`, and an integer `k`. `nums` comprises of only `0`'s and `1`'s. In one move, you can choose two **adjacent** indices and swap their values.
Return _the **minimum** number of moves required so that_ `nums` _has_ `k` _**consecutive**_ `1`_'s_.
**Example 1:**
**Input:** nums = \[1,0,0,1,0,1\], k = 2
**Output:** 1
**Explanation:** In 1 move, nums could be \[1,0,0,0,1,1\] and have 2 consecutive 1's.
**Example 2:**
**Input:** nums = \[1,0,0,0,0,0,1,1\], k = 3
**Output:** 5
**Explanation:** In 5 moves, the leftmost 1 can be shifted right until nums = \[0,0,0,0,0,1,1,1\].
**Example 3:**
**Input:** nums = \[1,1,0,1\], k = 2
**Output:** 0
**Explanation:** nums already has 2 consecutive 1's.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is `0` or `1`.
* `1 <= k <= sum(nums)`
|
Sort the boxes in ascending order, try to process the box with the smallest height first.
|
Array,Greedy,Sorting
|
Medium
|
1719
|
1,456 |
Hai gas welcome and welcome back to my channel so today our problem is maximum number of vowels in a substring of life length so in this problem you have given name one sting s and one ints k given ok you have to find the maximum. Number of vowels latest in other substituting of s with length of so all the possible sizes of s, I have to see what is the maximum number of vowels, those numbers have to be returned to you. Okay, so what we do here, let us understand through the example. How can we see the problem of K? What is the problem? Okay, so look, we have given a sting S and a wait, that is, all the possible sizes of K, here you have to see how many number of vowels are there in each, so first. So you will see ABC, this is ok, so how many vowels do you have in it, the count is one, so after that what will you see, if you are looking at the remaining, then how many counts are there, the total vowels are one, then what will you see that you will see Yahan pe count kitna hai tu hai, then now you will look at triple I, where your pay count will be three, then you will look at IIT, where your account pay will be 2, then you will look at the ID, how much is your count, yahan pe bhi tu hai def. Now see who got the maximum number among these, if you have got this three, then what will be the answer here, your pay here will be three, from this you see in the second example, what is yours, that is, in the window of size 2, you will get Let us see how many number of vowels can be maximum possible, so A Tu Hoga Ib Tu Hoga I O Tu O U Tu, there are only two vowels each, whichever window you get, now both of them have vowels, kek tu hai, so now see k3. Here you will see Lt, double eye, here you will see two, then you will see AAT, here also two, if you see maximum, ETC, here you will see one, then you will see touch o, less here. There is one, then O, you looked at the ETC, then you look at the code, now the count is one, then you look at the odd, then what is your count, there is one here, so how much have I got till now, if I have got you, then what do you have to do, return you. Now what we have to do is how can we solve this problem, see, so we have just seen what we should do, what we have given is a kind of window and in this window we are seeing what is the maximum number of vowels, so one In a way, it is based on what is yours, on the sliding window where what is the size of your window, is it fixed? Either you are looking at ABC, then after leaving A, you are looking at Bachi, then you are looking at CII. Yes, that is, what are you doing with your window, you are sliding it, one by one, okay, so what we will do in this way, if we solve it with sliding window, then what we will do is, first, we will take the max count, which tells us that the maximum count. How much is it? Okay, we will take a count which will count in the window and your maximum will keep getting updated, after that what will you do? Okay, so how can you check the wavel? To check the wavel, what you will have to do is to put an IF condition that IF C Equals. Tu A I O U So what will happen to you, if it is a vowel then why will we avoid it because it will be a lame code, if you put a lot of if and condition then it will be very long, so what can we do to whiten it 61 Okay, we will take the set and what we will do is store five values in them, we have A I O store five values in them, we have A I O store five values in them, we have A I O U, so now you say, we should not add extra space here because we are taking that file, in a way, it is a constant. This will be the oven itself, now what will we do, we will start from here, now we will compare, will this character be present in this set, yes, it is present, then make our count one, okay, then you come to this BB, is it present in it, no? So here you update the maximum account as one, okay, then you will see in C, what is your wave, what is not, then this will remain your one, then when you come to this, your window has changed, these three are not there. You can see only the remaining part of the size, you cannot include A and the one that is participating in this count is because of A, so you will have to remove it, then we will check whether this is yours outside the window. The character that was there, is it a vel, is it a vowel, is it a partition in the date mains discount, so remove it from here, okay, now check this is where you are participating, in this window, see, is this a vowel, is it a vowel? So do one up, if the game is maximum, then only one will remain, then if you come into it, then you will see here, you will remove B, dog, then check B, people, is this not your wavel, no, this is not date men also participate in one account. If it is not doing then we will leave it, then we will check if it is a vowel, yes, it is a vowel, then what will we do, if you update the count here, then if the maximum count is more than one, then you update it here also. Two, okay, now you will come here on this eye. Okay, if you come on this eye, then CAI was participating here. Now in this window, I will come on triple eye. Now this one will have to be removed, isn't this wavel? Not this wavel. No, date mains was not participating, okay, so I have come, see this one, yes, this is Wavell, so change the account here to three and the maximum count will also be updated to three because it is more, isn't it? Then now you will come to this DP. This DP will come and you will see the eye, that is, you will have to see this eye. Is this a vowel? Yes, it is a vowel. In the date mens, it was participating in the previous window, so now what we have to do is to make it a counted degree. It has three. We will do it okay and we will check this, is this your vowel, is it not a vowel, that is, here in this IIT, the maximum number of world n vowels of yours is you and here the maximum is three is yours. First of all, will Mila operate it or not? Then we will move ahead. We will check A. This will check that. Here only your ID will be there i.e. this I will only your ID will be there i.e. this I will only your ID will be there i.e. this I will be out of the window. So you guys check whether this is a vowel or a vowel. Make it one. So you did one, then here you come, is this a vowel? Is it a vowel? So what do you do with it? Here you do it again, i.e. Here you do it again, i.e. Here you do it again, i.e. maximum till now you got in Id, it is okay, then we will come to F. If we come to F, then this If there is an incident then the account here will become one again and we will check you. If it is not wavell then it will remain one. Here you have only 1. Okay so what is the maximum here right now. If you have got free then the answer here is what will be three. So what do I do, I show you the code also. Okay, so what have we done in the court, what have we taken, we have taken a maximum count of zero, we have taken a count of zero and we have taken an unordered set in which what is yours? The data type is character, in this we have stored A I O U, after that we have taken a loop on one ij0 OK I Less Den Let Dot Size I Plus Now we have put the condition here that if I is your greater den Equals you have done that means you are outside the window you and your vowels count SI - K you are outside the window you and your vowels count SI - K you are outside the window you and your vowels count SI - K If your vowel is then date min what we have to do is remove it from the count then we will do degreement if your SI where you are the current index of your if If there is wave then you do count plus and update the maximum count and finally return the max count here then what will happen to you here also time complexity will be on and space will be completely one so I hope you understand this. If you liked the video then please like it and subscribe. Thank you.
|
Maximum Number of Vowels in a Substring of Given Length
|
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
|
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`.
**Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
**Example 1:**
**Input:** s = "abciiidef ", k = 3
**Output:** 3
**Explanation:** The substring "iii " contains 3 vowel letters.
**Example 2:**
**Input:** s = "aeiou ", k = 2
**Output:** 2
**Explanation:** Any substring of length 2 contains 2 vowels.
**Example 3:**
**Input:** s = "leetcode ", k = 3
**Output:** 2
**Explanation:** "lee ", "eet " and "ode " contain 2 vowels.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
* `1 <= k <= s.length`
|
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
|
Dynamic Programming,Graph,Shortest Path
|
Medium
|
2171
|
957 |
Jai hind is problem wear giver nurses us embassy rimi pimples one of these rocks that android desires will wither chaupai like this a prisoner inside and 10th mp3 there inner inside us but rather condition for preserving occupied is given is so is to-do to-do to-do subscribe Both in this will provide a 231 Hello Busy Ho Birthday Bhi Aap Side Surya Bike Crosby Modified Benefits Like This 800 Of Both Occupied And Net Savvy By Birth Soldier Apne Ring subscribe The Channel subscribe and subscirbe And Do Flash Lights Notes Ko Point To In The First Day of the Input 91 Randomly 100MB Click Subscribe button on left side and subscribe my channel Subscribe Only Very Next Day She Don't liked The Video then subscribe our ke bute MP Buddhi same day Central one will be and superhit darshans to return home From next year will give what is the giver friends subscribe this Video plz subscribe for detail view He never did not feel like you will see what will oo do that sun and this is our benefits night and examples from list code so let's look at This Dainik Yudhishthir Vishisht On Dresses Input A That And Where To Find What Is The State After Day 7 Minutes CP Thakur Sudhir Which Give For Software To Subscribe To Channel From Different From One To 6 220 Chala Straight This Very Never Say Switch Off White A will also improve valid state and this is a valid state everything else invalid choice any words on that side 120 both r rahman's paste absolutely white on global standards next and fights with vikram office on december and 3000 1000 e ki chunari for this only one is The Chopper Hits 200 Run Game Same Thing 0 Only One Never Too Much 1000 Words Will Automatically Comes Next Day It Will Work Only One Beats BSE 500 Share Ko Ando Ko Pad Sudhir Vikram Thakur Fried and Simple Dushman Show Ki Boond C Channel DD Unwanted 72 Wheeler Street Suite Se Instant 7210 Know What Will We Will Continue For All Want To Know The General Knowledge To Be So Lets You Are In The State Government Withdraws From This What Is The Possible Only Possible Withdraws From Distant You Can Go To Subscribe 10 Top 10 Years December Soft Toys 1518 E A Special 000 Not Go To Multiple State With Different Problems Due Consideration Loot Virval From Right From Thee 100 To 100MB Left With 6 Us Annie Besant 12-12-12 Subscribe Only for 12-12-12 Subscribe Only for 12-12-12 Subscribe Only for Administrators 6 Hello How to Beat 64 Not All States Will Valid Suji Raw First and Last Website 204 Let's Take a Look at Small Example Vaikunth All the States Hair 60 ₹10 Note Vaikunth All the States Hair 60 ₹10 Note Vaikunth All the States Hair 60 ₹10 Note Unit Hair Oil It's a B Take Only Three Levels And First and Last Updated On That And First And Last A0 Will Consider All Great Possibilities Person Quite Talented Number So Let's Radhe Only Values 02 A3 Lar The Five Number So Let's Radhe Only Values 02 A3 Lar The Five Number So Let's Radhe Only Values 02 A3 Lar The Five A Six And 7 Others Get Values Not All Of Them Are A Six And 7 Others Get Values Not All Of Them Are A Six And 7 Others Get Values Not All Of Them Are Very Selective Valid This Is Not Valid For This A Great 0 Hain To 3200 Sudesh Dhawan Similarly This Festival Suzy Invalid Similarly Destroyed Seervi Simple Eighth Possibilities Only A Few Are Possible Similarly Subscribe Button More Looking Very Small Number Of Fish Density 400 What Will Draw Tower Approach Will Win And Will Keep A Map of Verbs Pain More Subscribe That Acting Yash Raj's Facility At Events Of Tender For Not Visiting Your Small Number Only Absolute Value 400 Luta Do Subscribe Valid Se Subscribe That And Will Have To Go Heart Temperature For Not Agree With U Will Repeat After every elections where do subscribe forward the fast forward it to this values constitution will be seen civil repeating will find how many times will repeat show window is a that lakshmi tight air waves formed from values and where current is clear is values and where current is clear is values and where current is clear is a great day that mp pandey look Non is today they find value state which already declared date means the rock word from the state governor strictly avoid this world and again after some years game repeat share also form w principal vacancy on which date 28 first cut mannu and noida again cream so what is The Capital Of Length 100 It Will Again E Wish My Blog In Attraction State Will Again Nagark After I Plus L I Plus Too Well And Sonth Mixing All Subscribe Plus Khel 234 I Plus Khel Mein Bhi Technical 210 Arrest 529 And I Also This Loser Left Inch Plus Channel Free Mode On In Unity Will Repeat Actor Will End Just After And Butter In Which Give Me To Us And Will Need To Solve For Remaining Values Which Will Need To Solve For Remaining Values Which Will Need To Solve For Remaining Values Which Will The Mail Show How Many Times Will Solve Vishal For Loop Length Let's 0 On Thursday Subscribe Button Time Complexity of Possibilities to be Invalid Subscribe to That and Will Also Not Reduce and Apni Speed This Pendent on and Apni Speed This Pendent on and Apni Speed This Pendent on That Respected One Value and So Let's See Who Gives All World 's Famous SIM and Important This 's Famous SIM and Important This 's Famous SIM and Important This Explain Tools and First Began Writing Service a Din jab end passion hua hai kar do ki vinod ki twitter ki show will convert elements to string ki anti shatter index of but its first swagger play list quality map ki surya here number please tomorrow morning can convert effective to-do list tomorrow morning can convert effective to-do list tomorrow morning can convert effective to-do list representation brother passing the Big man and traders hua hai ki nav ten acid your presentation of state of all apps software check list hai jakad and not your fit third you have already sold all the next values from actually swift next values from actually swift next values from actually swift ki hai ki suddanli tha already unbroken A hua hai what will be the loop alarms value spoiling your system wind witch presidencies place solan i - place solan i - place solan i - ki main is hai so what is the number for remaining days that remaining days will be and what is the end so let's do the match hai The Software On Tuesday Evening Dozen Lot A Valid For Studying In This Value Is Which Chord And Mixing Stroll And One Should Separation I Plus That Only A Plus B Sensitive So Let's Collide With 80 Money More t90 Subscribe Hour 102 Let's Get Meaning Aaf ki show i plus khel plus hum content its swiss rolls is equal to am s oo will find the receiver this is the number of units sold in - sai pa in - sai pa in - sai pa ki bill vikram ki only plus e not act models as per this period 000 game models K Bill V0 Multiple Of 100 Swimming Left Hand Side C Right Hand Side Vikram Seth - Models C Right Hand Side Vikram Seth - Models C Right Hand Side Vikram Seth - Models Side Of Models Subscribe To The Sweets In Us - I Sweets In Us - I Sweets In Us - I Plain Mode Lo Me Loot 108 Mister Kya Bittu Model Onl9 Tedhi Don't They Are Not Bothered About This Yesterday morning call is dispatch center and fast-forward from Bijnor is I and fast-forward from Bijnor is I and fast-forward from Bijnor is I superhit swift lockheed martin 100 flu alarm set i20 increment is after every situation in her will increment regards welcome's his remaining days last name but subscribe ki sudhi updated state end Capital for next seeds and remaining days do that Sudhish Shuddh's viewfinder lu but before final oo need to calculate the values and final oo need to calculate the values and final oo need to calculate the values and keeping setting on map hua aur sun map not insult ki bill with this and value will be that Idea index and after Insulting will that find next and next voice of that will keep updating and values in this updating and values in this updating and values in this person only ki shoon tu kiski tardah without facility of previous start from one and total six that cigarette this is one of plus we ladies on do tomorrow morning starting from 130 to cancel 2017 sweet will go up to six days second last jal ki abhi a not warid about first and last scene goddess come automatically 0mb 2004 and hear text will be clearly states i plus one previous dead cells 0 ki and they will update hair previous Me Ando The Current This Yes Santosh Bhai Swami Story Meeting Current Very Good Things Will Be Updating And Current Business Sweater Restaurant And Next The Previous Vikram Current Affair Weird And Value Udaipur The Last Updated On And Strong Will Be That You Can Take To Multiple Things You Can Do Aksar A Sourav Previous Next To 10 After Way John Half Negative The Sudhir West Compare And Subscribe To That In This Current Vikram Previous Next Full And Final Year 100 And Sons 720 That Shivir 122 Never Did You Listen And Consider S A First year student fears Bigg Boss is very occupied and very vacant but for 20 days they give Radhe-Radhe only one ever suvivi come for 20 days they give Radhe-Radhe only one ever suvivi come for 20 days they give Radhe-Radhe only one ever suvivi come zero after first from day one all world of words has happened within kar do ke return type this image better without interruptions MB updating 2019 More Return Value Happened And Sudesh Works Let's Check The Second Example A Salute To Solve This In The Given Time But Power Ranger Didn't Matched On Do Tomorrow Must Be Doing Something On Here Uttar Pradesh Current Will Visit Subir Which Is Formed A Number Dennis Amazon Cell Number Thursday Next 100 Years Ago Play List Hai Yakin A Night Messages Sun Let's Submit Ki Hindu Solution Is Accepted Norms Will Do It In Java Infection Hua Hai On Karo Hai Ajay Ko Main Ine Doubleuser Is Daughter In which will convert 182 string were Indian values were Indian values were Indian values that content hua hai hua hai a sweet will return boolean in java you can not assign boolean is not treated 800 you convert print 2012 this previous12next day one 0 Half hour this point can also due that if 108 trick but this trick see Saurav previous that and next Ibadat and Samridh 000 1510 and here message so let's submit a is accepted the invitation for that first hua hai that Anirudh Ali convert and pintu Spring A&B Nitya Sales Soil Jo Mixed Potter Faisal [ Jo Mixed Potter Faisal [ Jo Mixed Potter Faisal On Karo Ajay Ko Hua Hai Loot Kar Do Hua Ki A Ajay Ko Kar Do Hua Hai Kar Do Hua Ki And Senses Didn't Match And Listen The enemy of B is this has happened in infection solution and subject
|
Prison Cells After N Days
|
minimum-add-to-make-parentheses-valid
|
There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109`
| null |
String,Stack,Greedy
|
Medium
|
2095
|
651 |
hey everybody this is Larry this is me doing the weekly premium uh problem uh hit the like button hit the Subscribe button drop me on Discord let me know what you think about this problem uh even if you don't have premium okay so today's spam is 651 for Keys key Point okay let's see if we have a special keyboard with the final Keys a select hold copy and then print Buffalo screen appending it after say what and then we're trying to Max okay I mean that's fine but print buffer on screen appending it after what has already printed let's see what they mean AAA selector Ctrl C and then V re so then now we have okay I mean I guess I get it and then it's at most 50. um okay these ones are always kind of tricky I think there are a couple of strategies you can think about it this is either the two things I'm thinking about right now one is dynamic programming I have to figure out what is the best way to dine it I don't have one ready yet to be honest um but we can kind of figure it out um and then the other is kind of just like one uh or you know manually using a notebook or something like this um one if a small cases and then see if we could get a pattern really quickly I'm going to try to do this with dynamic programming just because it's 50 so it should be straightforward in terms of like not needing um because if n is like really big potentially um then maybe dynamic programming it's a little depending on the constraints and how you know the expense uh how expensive it is to Dynamic program um you know it may not be what you need but here n is equal to 50 should be okay um because sometimes they some problems and maybe not this one because it's lead code and I don't think they do that quite yet but if you do other competitive programming uh like on I don't know like Comforts for example um sometimes these are kind of like okay here's a thing you have to kind of get a pattern and then derive some formula that is uh almost all of One in general or something like this right something to that level I mean it doesn't happen that often either just to be clear but these are things that going in my head just to kind of tell you how what's up uh yeah uh okay so yeah let's try right so basically we'll just see how many uh in theory the way that we want to do is um right and then maybe prices left is how I would do it and obviously precious left would have at most 50 different things right uh because that's the constraint so then now what can we do with one press maybe there's a different state let me think I mean maybe I'm wrong with this by the way so let me think about this oh I almost want to say um maybe I'm a little bit wrong now that I think about it because it's not just the presses it's about how many things you have screened right now right and how many things are on the buffer right now right um I think for this one let me retract this I don't know if I know how dynamic programming for this I was thinking a little bit I might have misunderstood this one a little bit um so okay oops I think this is also one of those things that um that are either base two or base three or something like that's why I'm uh like you're kind of like if I have to guess maybe it's like n over two to the third power or something like this right something like nuts or and over three to the two but you know something like this where like you have some maybe pattern or thing right and that's just like off my head kind of like that's the kind of thing that I'm thinking about I don't even think that's like I don't have like confidence in that exact formula but something like um something of that texture something of that uh feeling and maybe some of that is just experience but yeah n is equal to one then um F of one is just going to be equal to one right I mean you only have one move F of two um you're gonna have two because you just printed twice right so F of three is three and same thing uh you put it and then four what is four right four can you divide it by two right so you have one you copy you paste that's only three so you're gonna write four twice uh like four I mean write a four times right um and then F of five what is it five um so if you do a two you copy oh no you have to cut you have to select or and then copy and then paste so it's not just um I'm almost this actually reminds me of like an n-square type frame n-square type frame n-square type frame um because basically you're trying to balance is that true maybe that's not true hang on I mean I think the other thing that I was saying and I think I said it wrong I said n over two to the third or something but what I actually mean is like something like 2 to the N over 3 or something like that's what I mean um now that I think about a little bit but I think that's what I meant in the beginning but I think I just kind of uh messed up in my head because so my second strategy was something like you know AAA and then you do a control a and then Ctrl C and then everything after that is Ctrl V but that doesn't make sense because um in a way if you have enough moves you know uh for example maybe it makes sense to do another one here right um like we do uh we control all and then Ctrl C and then do it again and that basically doubles this twice um in exchange for three fold type things right so that's kind of so they feels like there's a divide and concrete thing this is only a medium am I making this too complicated I don't know this is why I don't like um having a difficulty because sometimes like I don't know now I'm like second guessing myself everything all right let's figure out for five first right what's five uh so five we can obviously write five A's um we can write three a control C but you can write two A's Ctrl C oh sorry take two operations and then Ctrl V and you only have four so still write five A's you just buy 5X right what's F of six so let's do it uh you know something like this what does this mean right this is it takes two operations to do a copy onto the buffer and then paste face I think now I get it a little bit better and now I think I can maybe Dynamic program but maybe that's not true still um but that's going to be six right uh yeah this is gonna be six in both ways right six A's and also that right and then F of seven is nine because of you know it's an example um I'm thinking about different uh greedy-ish strategy as well in terms of greedy-ish strategy as well in terms of greedy-ish strategy as well in terms of like okay in terms of maybe we can Brute Force the number of A's right like that's just one thing to think of I don't know and what I mean by that is you can say okay how many A's can we get with rewrite 1A and then use Ctrl V Ctrl a whatever for the rest um how many times have we used two A's and so forth Three A's and so forth right so you know for example for f of eight what is the answer here right huh I think I'm right now I'm just trying to get an understanding in general so we know that we can do at least this so basically this is going to be another three so this is just 12 over the last one all right yeah can I express this in terms of the previous functions right I think that's the tricky part and I don't so I have a dynamic programming idea in my head but honestly I'm not sure that it is bounded that's why I'm cure uh that's why I'm hesitating a little bit um oh this is gonna be 12 but can we do better right let's say we have two a's how does that work a c v and then caccv right what is that it that's two doubles four and then eight so that doesn't isn't good enough but I'm just trying things hmm I think one pattern that I'm thinking about is that I mean because that isn't good yet but then now what's F of nine right nine maybe it is ten right because in this case this would be so now we double twice so then went to six and then I guess this is 12 so it's still not yet um because it's gonna be 15 if we well this is 12 because we double twice but if we do it just like f of eight plus another CV that is going to just be 15 right so um but I think like there is a pattern is emerging but I'm really slow on it uh perhaps uh because but basically the idea is that if you double do you wanna um you're gonna use x amount of CVS and it only makes sense to um let me try one more thing first let's think about four A's right what does that mean that means I have CA CC cvcvcv so that means that we did four so this is also 12 so this is still no bueno hmm no this is this mathematical thing is hot um no yeah I wonder when is it up because I think it never makes sense because I think there is a case in which it makes sense that Four A's at some point um because that's fine and even five A's but six A's never makes sense because you can always just use this sequence and then you could double more or something right or just copy and paste the same amount so this is one way to get six anyway so it almost never makes sense to or like the equivalently It doesn't make sense to have more than six A's right and given that can I before said let's say we're only trying one to five A's inclusive how many branches are there right because basically at every point we have really one decision after the A's and it never makes sense to write an eight after the initial A's because then you buy it's not commutative but if you just move the same a to the front then you would get way more benefit so the ace all have to be in the front and then it becomes three moves to double okay I think I have an idea on brute forcing because basically the other idea that I have is that you always want to double in the beginning right because also by um I don't know I mean maybe it's the exchange argument in a way not quite maybe but in a way is like the exchange album of okay if you could double before and then paste more or double afterwards of course you're gonna double in the beginning because you just get more so that means that we so we can move first into a the number of A's up to six maybe and maybe we'll just try more just because I'm not 100 sure on that one and then we put first on the number of doubling each taking three steps and then the rest of that will be Series so that's always going to be the sequence as I will understand it huh this is kind of I mean maybe there's an easier way to be honest but I feel like that's the way that I'm gonna try to code it up and then we'll see um okay so for I don't know I whatever um this of um oh it goes only up to I oh no that's not true it goes up to uh yeah it goes up to uh what should we call it well you need at least one of these otherwise it just doesn't make sense or like you know you're pasting emptiness right so you need at least one of these so then um yeah I'll write this as a while loop J is equal to one right wow I Plus three times J is less than or equal to n then we do some things and we didn't comment okay uh and J is the number of doubling um eyes are the number of initial A's J's are the number of doubling uh Triplets of caccv and then I don't know I guess case uh or number of series we didn't do care yet obviously but uh but yeah okay so K is equal to the number of moves left which is going to be n minus I minus 3 times J right and then now the math for that is going to be um I have to put it best so best we just you know set it to and in the sense that um this is going to be all A's right um I think this gets covered anyway but uh so basically the current uh score and I just call it that is just you go to okay so we have let's start this at one because I don't know that makes sense that's zero either um okay so now we have eyes we have I and then every for every J we double so we times it by J uh two to the power of J right and then we added uh we yeah we add um okay let me think about this for a second uh two to the so basically this is the last thing that's on the buffer all right let me look give me a second sorry so let's say J is one yeah okay so I tried to do in one move but basically what I should do is J minus one is the number of doubling right so this is the last paste or this is the paste size right um because if J is one then the last page size is I okay yeah and then score is equal to um I plus the last uh it's a this last thing is messing with me a little bit um no I think this is this was right plus uh last times k something like this goes to prevent just in case right I'll give it one real quick something's a little bit off um so if we have one double if we have one then it doubles so this is one then just doubles yeah that's right what am I getting wrong from let's see easy to print out I mean look uh okay so we have oh I didn't reset some stuff that's no that's not true so four we doubled it once did I mess something up probably so K is sex that's not right before this uses one and that's already seven did I mess something up oh why is this minus that's the number of moves yeah okay all right so that looks good for this one but that doesn't mean it's good uh luckily for us it's a small test case that we just won 50. a wrong answer so that's not good but at least we uh kind of figured something out maybe is that actually there's a better answer huh so maybe my gritty was wrong wow let me think deities get nine right I don't want to so I mean I know that I'd already kind of cheated by using 50 but at least I'm going to do the one that I know the answer to and just look at my code for it so nine oh it's 16 so actually my fingers wrong how do you get 16 hmm oh I did this math one this is 16 yeah whoops so already before you want to do four that gets it yep I mean I guess that's fine but apparently there's a better answer huh I mean pretend that I probably submitted this I do wonder if my hypothesis that they're ever going to be six A's will ever be true uh what's that where's the two or four of them let's see yeah with five the last one then we did three copies that doesn't make sense does it oh no because we use one more for doubling so then ha do we always want three copies is that it I don't know how I mean this is as Brute Force as I think I can get that's why I'm like a little bit awkward that it doesn't work and that you can do better not missing like a real way of doing it I've been going on for 22 minutes now so that's actually a hmm is it TP man I am really off on this one double 16 times and then do 1K what are the sequences that you know let me get to that I thought I knew this one so that's actually pretty bad but we can actually also check right so three one and three which is this one is 15. so we yeah just yeah this is right hmm three two and zero is 12. so um but then huh am I wrong in some case do we so the only really two things that I thought you know greedy-wise would be thought you know greedy-wise would be thought you know greedy-wise would be true which is either putting all the A's in the beginning I feel like that part is true and I'm putting all the doubling in the beginning oh maybe not maybe that one's the wrong one because I think that maybe you could double no because I was gonna say if you could double copy and then double paste and then double why is that why would that be different than doubling and paste is my math one basically I'm just trying to think whether you want to do this Plus some last number and then times two versus times 4 plus the last time we paced um which is going to be we paste only once then it's gonna be essentially times eight right what about two things left what if we could paste twice do we hmm I think the right way to do it um in light of these is just right uh coding it but I'm also trying to like think if it makes sense um so the IJ and K is going to be right but maybe there's another different ordering maybe there's something let's see right so basically let me just put first saying okay let's say this is the way to do eyes um actually we could even just put it here um and then Chase but the before last before I mean you can also add another like o of n Loop to kind of proof Force when you put in the two or whatever extra uh case but now I'm thinking like if that's wow what if you just like interversed them hmm man this is hard uh well maybe I'm just missing something obvious all right let's kind of hmm all right let me uh try to do it with the proof first way maybe or not before us but just um just kind of dynamic programming he prefers what would that look like so what I would say let's just go man this is a mess but uh let's just get Max or presses and maybe buffer size right so then now we want to return get Max of N and then the buffer in the beginning is zero and then basically we have a few things that we can do um we can uh just press a right so a is equal to get Max of we pressed one and then buffer doesn't change oh sorry press this plus one uh and then we get one in the final thing maybe is that true is that the way that I'm thinking about it because you need to also find account a right maybe and then we're getting a zero but that feels very expensive maybe that's the way maybe I just over thought it maybe there's not that many states I don't know but the thing is that the buffer can be a Unbound number that's why I'm like yeah that's why I'm kind of confused but okay fine there's one a on the screen right or sorry count of a plus one in this case um you can also do control a control C and you need both of them because it doesn't make sense to do either without the other right so presses first two count of a is the same and then buffer is equal to um count of a right no not yeah counter bank right and the score the number of A's didn't change but that's just that and then now series you're gonna get Max of presses plus one um we have count a uh actually count a plus to come uh buffer uh the buffer doesn't change but the number of A's changed and then we I guess maybe I don't even need Calais in that case I can just um well like I don't need the plus one I think the it becomes almost like a search Problem um but can a could be really big right as we saw it could be one million right so 50 times 1 million isn't going to cut it but hmm my recursion isn't even like I feel like I'm just off right foreign count a right I think that's fine and then this is if prices minus two is greater than usual the other one should be fine that's for time oh I thought maybe it would time out but it doesn't that's actually surprising okay yeah and now we just kind of do the magic cache and then see if that actually terminates I'm actually curious about I'm not convinced that this isn't timeout to be honest but I think uh why I implemented it anyway uh is because I want to run it for small ends so then now I can maybe learn from it like obviously because I've done it as well but that's kind of cheating especially like on a contest you will not be able to get the answer right so you know that you don't know the answer oh man I forgot to take out that case the 50 case at least uh how do I take this out or is it because it's running okay fine okay there you go uh yeah remember we limit exceeded some that's not great okay so basically 10 is 20 uh I'm also trying to see like what limits can we push and then we can so at least now I am more confident that our code is correct um but it's not fast enough but that's why I kind of worried about it that's why I didn't do it this way for a while um even though it is very good I think one thing that you can do so now that we have this uh and obviously it's not a full answer because like I said it's 50 right what we can do is actually I have an hour in I guess um what I want to do is uh do I want to do this well what you can do and I don't know if I'm debating it now and if you're still watching thank you but um but I'm trying to think oh yeah but I was what you can do is uh path reconstruction so you can kind of see what is the like for dirty what is the best answer um and yeah but do I want to do that let's see if this kind of works for now maybe 30 is too much printing no actually pretty okay well not okay but um yeah this is useless no I mean I was hoping but uh fine I don't want to do this okay fine um uh so this portion is gonna be less uh teaching is me going to try to figure out if I know how to do it to be honest um that's not true that's not what I'm trying to do foreign my food actually kind of hurts a little bit uh let me try to debug this and try to figure it out if I know an answer and I mean no maybe I'm just you know this is just one of my equip tonight maybe but yeah uh but quit I don't know that's enough to explain it so let me try to get it um okay all right okay yeah okay uh man I really don't know this one I mean maybe it's greedy and greedy ones are hard anyway so yeah uh that's my excuse okay so AAA yeah a-aac a-aac a-aac does that make sense uh yeah I put something wrong why would this ever okay so you have three you take all your copy but you never paste you have to paste did I just find the wrong thing huh I find that hard to believe I mean okay something is wrong with the thing but um to the count of a I guess is this backwards no it doesn't even matter if it's backwards or not right that's kind of weird um where's this uh okay yep eight plus stuff you have one a you have three a H I think I did this a little bit we've been okay fine uh it's okay so you start with 4A what's that what are we looking at no we're looking at this one okay let's look at this one first we start so you have 3A you copy into the buffer but the yeah oh the buffer didn't get updated for some reason but oh then I traveled the wrong one which one am I looking at this one okay yeah buffer uh is to go to count a is what I mean okay I was ticking the wrong path okay um yeah aaac hmm oh no CV is to oh no buffer I mixed them up CA I can't look what did I do why am I oh because I did this in two different orders I got them mixed up I see so count a is we added to the buffer on the paste right okay uh hello so aaac this is still one we copied to the buffer zero County of this is minus oh yeah like I did uh I did everything I mixed them up so whatever all right that's kind of upset okay so this is what we expect yeah okay this is what we expect with three and then we okay so much debugging the debugging okay so nine we have four so that's why it works dirty okay paste we paste um interesting so the pattern that we want is actually a full paste because then the first one is a doubling but this is ridiculous oh I see so basically you want a full operation not just a three operation to double twice how am I supposed to represent that I mean that makes sense but I feel like I'm missing some underlying principle on this one uh I said always at most 4A um let me see hmm still 4A but because we could double twice and for like I thought for it was a good thing but you know I mean hmm and the extra one is the one before the last Maybe that makes sense because this extra CV does it Larry does it did you see we mix it like um so this doubles and then just triples but if you want to quadruple you might I don't know huh I don't know that I know this one um I feel like I'm missing a principle here let me also just print this maybe not this uh let me print I just want to see like the size of the cache a little bit um like can we optimize this for 50 and then go look at the answer or something so I feel like I don't know anything and these numbers don't um mechanisms really um thank you so 35 or yes 400 so that's already a lot of states and I feel like that's the thing right like I feel like I could proof or like code this up like as part of this in a way but I just feel like that's so ad hoc I feel like I'm missing something like simpler like some underlying thing that I'm trying to figure out if I know how to figure out how to do it in an easier way all the time I just stubborn and not you know um if you have four do you always times three is that what you want let's say we keep on taking all the pairs of fours Assemble foreign how many things can well I guess I mean if you put them in groups of fours then you always at most it's gonna have three things in the back so if you want to do brute force on that I guess group of fours are kind of whatever you want and then okay seven is the first one I think of a group of four maybe that's why six is Gucci hmm all right let's focus on getting this right and then maybe we'll uh I don't know see if there's an easier answer okay so if n is less than U to six we just return n fine um I mean we wrote a lot of code um I knew that this wasn't gonna probabilistically work but I just wanted you write this to explore um the problem right and sometimes you know you have to do what you have to do even uh but this gives us a lot of insights right uh now whether we get it more still wrong is another story but yeah so this is seven what do we have an eight no we have a nine what is eight let's see uh we have a I mean uh actually I mean I did it this way and it was fine but apparently you could have also done it with um okay so basically now um you have groups of four and after seven it's always going to be so okay so if n is equal to seven just return nine uh one other way that we could have done it is you know given this um memorization code we could have ran it offline and then kind of just returned away I actually was thinking about that but I wanted to I don't know if this way is much cleaner so I maybe that's a bad idea but yeah so basically okay got four ace so count a is equal to four uh n subtract by four right and then now we have um we have groups of fives is equal to um and mod for because that's just the number of left over and then fours is equal to n minus fives one order obviously um yeah and then basically we double first time so uh count a we double right and then for each five we oh no this is one for each Force we actually we copy paste so that's double and then the second one so we actually times it by three and then otherwise for fives we times it by four and then we return account a right okay this is one universally uh why is that okay because for this one what is nine again nine uh let's do the eight first because eight is four right so H three just four times three right did I mess this up I mean obviously I messed it up but oh this is I'm dumb so the four should be groups of four and the fives well the fives are just a number of fives and then Force should be um four minus fives I think yeah I am dumb I forgot to group them into four actually all right hmm this is also what I meant by like this pattern finding thing but and sometimes you use the machine to help you but um okay this is still wrong though oh no we have it all the way it's still one where this is wow I mean I am stumped and I still like fours and fives how is that possible nine tripling and but that this is actually a uh the intuition that I was talking about of actually it's kind of funny because right at the very beginning I was like oh it's gonna be like n over three to the power three to the end of something like this right and this is kind of mostly already resembled to what I actually expected to be but uh it's a little bit off obviously but I'm still kind of like you know that's what intuition buys you I suppose uh hmm it is wrong for this one which is very sad because uh my DP is not you know good enough is it at least good for these oh it's one for 45 already or 40. can I run 40 real quick I left in the 45 accident down my timeout yeah okay it might still timeout to be honest but I wanted to see what is different from our frame uh do I not return this way oh because maybe I oh yeah because I uh a mock of the a n um I think I can just add that to n okay hopefully that doesn't time out if it does I don't really have a good idea of how to do it okay so four groups of four fives at the end oh fives at the end one two three hmm so if this is zero then it may be better to okay fine uh that is such a and force is greater than or equal to four ten five is equal to four and fourth is that even I don't know that doesn't solve it oh um this has to remove something is a little bit off but um because you don't get you remove one group of four to get 0.5 okay to get 0.5 okay to get 0.5 okay now that's just what am I doing um okay well maybe I just said and back to another maybe that's fine but in this case yeah maybe that's fine let's see still one oh my God so we don't do this is just very wrong right on the other direction yep but we know that we have four fives but we're just doing the full let's count one okay so 5 is equal to four and because of that this is way over counting so maybe I need to do minus one more if four of them so okay that math checks out but this is such like ad hoc thing but this is also the type of thing that um oh no still wrong so that there's something like I don't know how to I mean we could Brute Force this right for the number of fours and number of fives but it's just like at some point it's like oh man we're really uh you know I don't know I think I'm gonna give up um like I feel like we're very close uh okay fine maybe I won't give up I would just do what I said and just hash this I don't want to do it but uh but it is what it is um I'm gonna run this offline hang on um yeah I'm gonna run this offline uh and then I'll paste in the thing uh you could watch me just hang out I guess I don't know uh let's see I'm just gonna paste this code into something local I don't really have to go screen set up but it is just the same code and I'm just writing um I'm just writing a thing for it was it a DOT Max a um the good thing about this is that I think can I cash this more aggressively yeah it may be but it's fine I don't care to do it uh and then maybe we'll play around if this was a contest I probably would have done this earlier just because I wanted to uh you know finish quickly but Funk tools no it's running give me a second I don't know what we're up to actually maybe I should print it some other stuff oh wait I think I have to get rid of some code um all right there you go all right the first 35 and 36 is pretty quickly we'll see how uh the first 40 is done now that I did it you know now it's 41 42 dude I mean of course you know we know the answer we have just went here but it's fine I hope everyone's having a good day hope everyone's having a good uh week and all this stuff uh I'm gonna drink this delicious water I've been fasting all week oh well that been three days but it's still a long time and I'm just excited to like eating is exciting to me 46. I wonder um 46 has 6 million uh items 47 that's 8 million that's probably why it's taking so long it really makes me rethink my relationship with food because I feel like I'm bored and then I'm just like eating and stuff you know uh all right 48 is done but this is how uh you know I think for one of the um DM online judge uh contest won by Josh the DMO other the yac contest I believe um this was a technique that was required even for one of the game theory problems so it does come up from time to time and this is just like I don't know if it's considered reason but like a couple of months ago right so um I'm curious to kind of learn the control real way of doing it um I suspect that the people that are good at math probably have a deeper understanding of how these things divide but I think I just kind of couldn't get it I'm looking at the answer for like 49 and it has a lot of I mean I guess we could have put first that way like I said but I just at a certain point like the math is I don't know but it up to the N is equal to 50. so if that doesn't end I guess uh you know we still can I there we go um all right give it a submit yay we did it friends uh but no I don't know I mean I won't code that solved it but I don't know the answer for this let's say DP then foreign yeah once we use the copy there's no need to aim because we can just paste the buffer instead yeah I mean that's kind of about it maybe I didn't think of it that way though actually but I didn't know I mean we did make that observation so yeah oh I see I didn't know I mean I didn't know this but I didn't I wasn't able to construct a DP from this I mean we could have done the same thing with Brute Force really I mean I think the brute force would have been right um in the sense that where did I have it all right did I delete it why did I delete it hmm uh the one with the Cam4 count five thing um if you just put first the number of count fives you would have been is basically the same thing but I wasn't I think the math was a little bit lazy for me so I didn't want to uh try that but that's a hard problem slash I don't know this is a medium I think maybe I think I try to generalize it a little bit too much um I think if I had a base case that was more clear maybe that would have been okay um well that my states were not quite the same right because I think the better States is kind of what they were talking about which is basically this thing um but instead because I think I try to I don't know do this thing but instead what they're saying is okay this is just not my turn but so let me get rid of some of this stuff what they're saying is instead of this is that we have okay foreign I have a quick Glimpse I don't know that I you know let me see if I can implement it so I understand it right if plus is equal to zero uh that means we have no prices left so then we just Return To Zero um otherwise or whether if it processes I think that's the thing that we will right like the process is less than six we just return the number of presses we did that table um so I think this is right um and then otherwise well we never need to do so what they're saying is basically we want to do the uh copy and paste right once this is get Max oppresses uh minus three um and then we take this and then double because that's just a number of things and we copy and paste in double and then we can also do another series so we do four presses and then we triple and then I mean I guess that's clever I don't know I mean or I mean it's definitely clever thing but I don't know hmm I'm just I just didn't get it like I mean there's really no way around it right um and then maybe even uh I don't know I mean maybe this isn't even necessary but uh because in this case you can just double twice or something like this and maybe that's better I don't know right but that's basically what they're trying to tell you to do um right uh and then here maybe more modifications of because I'm too lazy to add if statements uh yes I should test 50 but that's pretty cute actually I don't know I mean some days sometimes you just don't get certain things I guess um this is a very long video hope you enjoyed it because I don't know I'm tired I'm gonna go eat more things anyway that's all I have for this one I hope you learned from my mistakes and I mean I you told me I mean I did get just to be clear like I guess I got an answer even though it wasn't a solution that they would have wanted um and obviously in an interview maybe hopefully you get a little bit of a hint and get it even though we'll see what happens but um yeah hopefully I even if I didn't teach you this problem hopefully you uh kind of look at how there are still ways to resolve it and you know there's the two ways that we solved it at least or could have anyway already close to it one is kind of just do it expensive and then do a low Guardian cash um and then print out the array like we did and then the other one is you know we found a pattern and I and if I had gone down that path I could have gone it but I was just tired with respect to kind of you know like the count five thing if you kind of um Who falls over it that was basically it really um which is kind of in a way because it never goes to sex um and it for the most part it doesn't ever make sense to even go to three but uh my under like seven or eight or whatever it is so actually um only these two things matter and then in that way you can prove first the number fours and fives and this you know the max input is n is equal to 50. so that actually would have worked but I just would I think I was just too like confused and whatever by then and out also like just didn't have that much confidence you know so yeah let's see I mean this is kind of vaguely what I was talking about um I don't know uh and this is amusing right because this is kind of it's not quite what I said in the beginning but it is an idea of what we said in the beginning so um yeah anyway uh that's why I have with this one let me know what you think let me know if you enjoy my struggle because people always say they do but yeah stay good stay healthy it's a good mental health I'll see you later take care bye
|
4 Keys Keyboard
|
4-keys-keyboard
|
Imagine you have a special keyboard with the following keys:
* A: Print one `'A'` on the screen.
* Ctrl-A: Select the whole screen.
* Ctrl-C: Copy selection to buffer.
* Ctrl-V: Print buffer on screen appending it after what has already been printed.
Given an integer n, return _the maximum number of_ `'A'` _you can print on the screen with **at most**_ `n` _presses on the keys_.
**Example 1:**
**Input:** n = 3
**Output:** 3
**Explanation:** We can at most get 3 A's on screen by pressing the following key sequence:
A, A, A
**Example 2:**
**Input:** n = 7
**Output:** 9
**Explanation:** We can at most get 9 A's on screen by pressing following key sequence:
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
**Constraints:**
* `1 <= n <= 50`
| null |
Math,Dynamic Programming
|
Medium
|
650
|
1,046 |
hey guys welcome back to my channel and I'm back again with another really interesting coding interview question video this time guys we are going to solve question number 1046 the last stone weight before I start with the problem statement guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the Bell icon for future notifications for more such programming and coding related videos and let's get started so basically guys the problem statement says that we are given uh basically an array of stones and each value in the array is the weight of the Stone and we are playing a game in which we select the two heaviest Tunes so for example in this case I can select seven and eight which are the two heavier stones and I smash them together when you smash these tones there are two things which can happen either the weight of the stones is equal so for example if uh both the stones are having weight seven and seven then if I smash them together then nothing will be left and basically you got rid of two stones from this array but in case when one stone is heavier than the other where in this case you can see that eight is heavier than seven you basically will be left with another Stone the third Stone which is having a weight eight minus seven so the heavier Stone minus the lighter stone weight that will be your new stone which you will now add into the array and you will continue playing the game unless you are either left with only one stone or you are not left with any stone at all if you are not left with any stone that means all the stones are smashed you just return zero if you are left with one stone then you just return the weight of that stone so in this example is it is pretty clear guys that we first mashed seven and eight and we get only one because eight minus seven is one so we add that into your array then we Smash 2 and 4 and we are left with two so we add two in our array then we smash one and both the stones are destroyed so we are just in the end left with one and that's the last stone weight and we return one okay if you have got only one stone then you just return one which is in this example and in case if you are having no stone left we just return 0. the constraints are that the length of the stones that means the length of the array goes from 1 to 30 and the weight can go from 1 to 1000. now let's jump to the solution approach now uh if you guys have been watching my video I think you can pretty much think that how this problem solution can go because one of the solution the easiest solution could be just sort the array okay what we can do is we sort the array and after you sort the array you select two stones and once we select the two stones we smash them together and in the last step we will simply add the difference weight in Array okay now let's do a look at the time complexity of this approach so if you are sorting the array obviously it's n log n now if you are selecting the two stones and we are simply you know smashing them together this will not take any this is just going to take order of 1. but remember that you are going to select two stones so you have to run a loop right you have to take turns and every single turn you are selecting two stones right so this although selecting the two stones will take order of one but to run it in a loop this will actually take order of n so selecting two stones is order of one but to run the selection of two stones every single time this will take order of n together and there is a difference in the weight so I have to add that difference in the weight in my array again so when you are adding that into your array you basically are adjusting your array so you have to add it and then you have to sort it again so in that case let's say if I add it and I sort it again the whole thing I literally have to do this for every so for the order of n it means the number of times I'm selecting two stones and then for every single turn I am actually sorting the array so let's say the words case that in every single turn I'm left with a weight difference so every single turn I am sorting the array okay so that's the beginning sort then you run for n turns and every single turn you do the Sorting again because you are left with the difference so if you calculate the time complexity this is definitely not a good one this is a round order of n Square log of N and we know with a quadratic time complexity it's not good we can actually solve it in a much optimized manner how can we do that now if you look at the problem guys it is pretty evident that we are selecting two heavier Stones okay now if we know we have solved problems like K maximum integers or k closest points to the origin all these uh in all these problems you are selecting K minimum or maximum elements from our array and in this case if you can apply the same logic the K value will become equals to 2. so if I want to select the K maximum elements and K is equals to 2 that becomes the same problem and how did we solve that problem with the concept of keep okay so we know Heap has got two operations one is your HEAP dot pole and another is your heapify and when we are selecting any element from the Heap and the maximum element or minimum element it only takes order of one time complexity and when you are adjusting the Heap it only takes order of log and time complexity use the heat we will have a better time complexity how can we do that so it's pretty simple guys if you write the algorithm for it what we can actually do instead of sorting the array we just place the array items you know keep okay when you're placing all the items in a heap then we basically run a loop and pick the two heaviest elements one by one and picking the two elements every single time is going to take only order of one time and then every time you pick an element you are basically adjusting the heat so we will be calling Heap adjust or I would say in Java the Heap will adjust itself and finally you will be only left with the last Stone Gate then keep is empty or has only one element okay now if we start analyzing the uh time complexity of this algorithm is pretty straightforward so first we are running one Loop which is order of n and we are placing all the elements in a heap and we can say that for all the N elements every time you place an element in a heap you are adjusting the Heap and that adjustment will take log n so order of n into our order of log n which becomes equals to order of n log n then we again run a loop for every single element and that Loop will take order of n then every single element we are taking the element and we are smashing it together and then we are having a difference in weight and we are adding it into the leaf and adding inside the element and pulling from the Heap pulling from the heat will take order one but adding inside the leaf inside the Heap will only take order of log n so again the time complexity for this operation will become the kusu order of n log n H so yeah this is the same as that of uh this I have covered in this step okay and obviously in the end when you are left with one stone weight in order one time complexity you can return it so if I talk about the overall time complexity it's order of n log n but not order of n square or quadratic like it was in the Sorting algorithm but if we talk about the uh space complexity guys then phase complexity in this case definitely is order of n because you are putting all the stones inside a heap whereas in the Sorting algorithm you are not actually putting all the elements inside any other data structure so that's one uh trade-off structure so that's one uh trade-off structure so that's one uh trade-off with sorting that your time complexity or the uh definitely is higher but your space complexity is less which is order one but I think we are ready to take that trade off because it will make our uh our solution much better okay so let's uh jump to the solution part now we know that we are designing a heap and in Java if you are creating a mini heap or a maxi fee piece will use a priority queue so I'm just going to create a priority queue of integer here and this will become my Heap new priority Q now inside this queue I have to make sure that this is a Max heat so N1 comma N2 and in this case the value will be N1 minus N2 this will now return as a maxi now as I said first of all we are going to uh take all these stones and we are going to put it inside the Heap so heat dot add all these stones so once my Heap is having all these Stones I am just going to create a first stone and I'm going to put the uh maximum Heap value so the maximum weight of the stone I'm going to pull it out in the stone variable and then after I have pulled out the first one I'm just going to take out all the stones from the Heap one by one so here I will just run a while loop while Heap is not empty so he dot size is greater than zero I will continue to pull from the Heap now here we have first already pulled out the first stone and we know inside the while loop that it is not empty so let's create a different variable and this difference variable will be your maximum Stone so the heaviest tone minus the next Stone in the Heap so Heap dot pole so I'm going to pull it again and the second heavier Stone will be subtracted from the first heaviest two and there will be this difference now if this difference is equal equals to 0 so if this difference is equal equals to 0 we don't actually do anything but if this difference is actually not equals to 0 then inside our Heap we will simply add it so Heap dot add this difference now while running through this while loop if my Heap side becomes equals to empty so if heat dot size have become equals to empty then we simply assign Stone as 0 because this is my last tone variable which I am going to return but if the heel size is not equal to 0 that means we still have certain value inside the Heap then I will just pull out the next maximum Stone and put it in the stone variable because stone is always going to be the next maximum Stone which is available and this will now have the Heap dot pole value and when we will go inside the while loop again it will take the second heavier Stone and subtract it from the stone variable finally in the end either the stone is zero if the heat size has become equals to zero or the stone will be the last remaining Stone so return Stone let's see if this works uh thing that is the error of Lambda expression that is my bad so let's see if this works okay I think the priority queue uh yeah I think this is not a maxi this was a mini which I created and there you go guys now you can see that this is a Max Heap and it works just gonna submit it and yes now it is accepted for all the example cases so as I've discussed about the time complexity already I think that was the algorithm and I hope you guys like the solution if you did like it guys and do not forget to like this video and share this video with your friends if you have not yet subscribed to my channel then please do subscribe and hit the Bell icon for future notifications or more such type of videos if you have any questions comments suggestions feedback for me please write down in the comment section below I would be happy to address them until then thank you so much for watching I'll see you guys in the next video take care and bye
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
449 |
hello everyone welcome to clean coder youtube channel if you are new to this channel i will highly recommend you to subscribe to this channel as i make tutorials related to data structures and algorithms software engineering and system design so today we are going to solve this lead code problem number 449 serialize and deserialize binary search tree so let me go through the problem statement quickly so it says serialization is 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 we need to design an algorithm to serialize and deserialize a binary search tree there is no restriction of how our serialization deserialization algorithm should work we need to ensure that a binary system can be serialized to a string this string can be de-serialized to the original tree de-serialized to the original tree de-serialized to the original tree structure and the encoded string should be as compact as possible now the example examples will go in depth on the whiteboard there are some constraints given uh the number of nodes in the tree is in the range 0 to 10 to the power 4 and individual node is between 0 to 10 for both 4 the value of individual node is between 0 to 10 4 and the input tree is guaranteed to be a binary search tree cool let's uh try to derive an algorithm like how we can solve this problem let's try to brainstorm a bit we are given a bst and we need to convert it into some string which is called serialization here okay this they are calling serialization and then we need to uh bring back the bst again from the string this they are calling it d serialization okay so what could be the algorithm to do this process so the algorithm is quite simple i have written that in the next slide let's go through that so the algorithm is do a pre-order traversal and obtain a string pre-order traversal and obtain a string pre-order traversal and obtain a string we'll do a pre-order traversal of bst we'll do a pre-order traversal of bst we'll do a pre-order traversal of bst and we'll get a string let's call this serialized string okay so once we get this serialized string we use this serialized string to make the bst again this is the simple two-step algorithm this is the simple two-step algorithm this is the simple two-step algorithm using which we can solve this problem so let's see an example in the next slide how we'll solve that in the example test case this is the example they have given to us in the problem statement so the pre-order traversal what is the pre-order traversal what is the pre-order traversal what is the order of pre-order traversal order of pre-order traversal order of pre-order traversal plural traversal order is first root is processed then left is processed after that right this process this is the order followed in pre-order this is the order followed in pre-order this is the order followed in pre-order traversal so if we say this is the root the first two would be processed then one would be process and three would be processed so pre-order processed so pre-order processed so pre-order reversal of this binary tree would be one three okay so this is the process of deserialization and we'll get this two one three as serialized string so what we can do now is uh we'll pick this string serialize string uh two one three and what we'll do is we'll process this string character by character and somehow using some algorithm will be able to obtain this tree back sounds simple right but like there are some challenges involved let me discuss those challenges in the next slide which you will face while uh trying to implement this approach so the challenges which you will face uh the first challenge is how will you separate two nodes in pre-order traversal okay so in pre-order traversal okay so in pre-order traversal okay so let's say this is the binary search rates pre-order traversal binary search rates pre-order traversal binary search rates pre-order traversal is 2 1 3 right there could be another binary service tree like uh this 2 and 13 and its pre-order traversal is also 213. now its pre-order traversal is also 213. now its pre-order traversal is also 213. now how you will distinguish these two trees this is the first challenge and now there is another challenge which is uh yeah same point i have emphasized here there is another challenge how will you know which ones were the leaves when you are deserializing the tree right so this two one three right we don't know whether two whether one whether three was at least right there is no uh special marketing done so the using which will be able to identify which were the leaf nodes so we need to uh follow certain approach using which we can mitigate these two limitations so how we can mitigate these two limitation let me discuss that on the next slide so these are the two simple uh i'll say uh steps using which you can uh solve those challenges so you can separate nodes with space so when you are doing pre-order when you are doing pre-order when you are doing pre-order traversal let's say the tree is that two one three only so when you print the root give a space then write the left node one then again give a space then write the right rightmost node three using which you can mitigate the first uh first challenge on the previous slide but like still uh the second challenge still remains you can't identify the uh leaf nodes while they serializing you don't know whether two was at the leave one was at the leaf or three was at the lead so what you can do to mitigate this challenge it's again simple so when you have this two one three what you do you assume there are dollar character instead of nulls okay wherever there is null put a dollar character now what you can do when you will write the pre-order when you will write the pre-order when you will write the pre-order traversal of this tree you also consider the dollar character in the uh in that pre-order traversal what would be the pre-order traversal what would be the pre-order traversal what would be the pre-order traversal now it would be 2 1 then it would be dollar right then it would be three dollar right this would be the pre-order right this would be the pre-order right this would be the pre-order reversal of uh this tree now if there are let's say a tree like this 2 1 3 what would be its uh preorder traversal using the similar proof so you assume dollar here the dollar would be here right so the pre-order traversal would be so the pre-order traversal would be so the pre-order traversal would be route to reorder traversal would be root two left dollar then right thirteen and again left then again right this would be the pre-order traversal this would be the pre-order traversal this would be the pre-order traversal and you need to give the spaces also so after two you will give a space after 13 you'll give a space okay so using this approach you can solve this problem statement okay let me go to the next slide cool let's repeat the process for this tree as well okay assuming this is the tree given to us so what would be the pre-order traversal so what would be the pre-order traversal so what would be the pre-order traversal of this tree let's append the dollars at the correct position now let's write the pre-order traversal now let's write the pre-order traversal now let's write the pre-order traversal of this tree it would be it is at the root 10 5 1 after that it would be seven dollar after that it would be 20 dollars so this would be the uh pre-order traversal of this binary pre-order traversal of this binary pre-order traversal of this binary surgery so now we can deserialize this obviously there are spaces after each node values there are these spaces okay so we can easily deserialize this string and we can construct this original uh binary search tree from this string how we can do it know how we can process this string from left to right and uh we know that this would be the root this would be left this would be right and then we can do uh skipping also and this process we can repeat recursively and we'll be able to deserialize this above binary search tree i'll show you the code which i used to implement this so the code snippet let me show you the serialization part first so this is the function given to us to serial uh to serialize this is the root of the binary tree given to us i'm using string builder because the strings in java are immutable so if we are manipulating the strings we should use string builder or string buffer i'm using stringbuilder so after that i'm passing this route and the string to this recursive function and finally i am returning the string buffer to string conversion back so this would return the serialized string realized string okay now this pre-order traversal is nothing uh this pre-order traversal is nothing uh this pre-order traversal is nothing uh but like it's doing a pre-order but like it's doing a pre-order but like it's doing a pre-order traversal of the tree so this is the root on this the left recursion this is the right recursion and i am doing all the manipulations before the recursive calls so this is the pre-order traversal so i'm appending the pre-order traversal so i'm appending the pre-order traversal so i'm appending uh i'm appending the trees uh node value uh this needs to be converted to string so i'm using integer.two to string so i'm using integer.two to string so i'm using integer.two string method and am appending a space after that and when i reach the leaf node i am appending the dollar for the reasons i have told you earlier so this is the serialization part let's move to the deserialization part now okay so this is the function which is given to us this is the string parameter which will receive from the above serialization process so here are some base conditions like if string is null there is no bst right i am directly returning null if we have a dollar in that case also we can return a null so after that i am having a index this is uh just for keeping uh the index like between different recursive calls we can uh persist the index so that something similar to pass by reference in programming languages like c i am trying to accomplish using uh this array of size 1 so i am initializing it with 0 and i am passing that to this ct constructory function uh this string and this index so uh let's uh move to the recursive calls first so this tree needs to be constructed right so i am taking a new tree note root with the value well okay what is well here is the value obtained from the parsed string so string and index i have a method power string what it's doing uh it's just picking the value from the string and allowing us to add that value to the or tree node this function is just doing that let's say the string as 100 right so it will pick this 100 value and it will return to us as integer and we'll put that in value and we'll put that value in the tree node after that the process is simple i have put this value here and i am doing left recursive call and after that i am doing write recursive call and this process would be repeated recursively and finally i am returning the root of this tree there are some base conditions also let's check those base conditions as well so if index of zero this is the index of the string so if it's greater than the length of the string or i'm at the dollar indicates leaf nodes right so i am incrementing the index by 2 in that case and returning the null okay so for obvious reasons this is the base condition so let's check the time and space complexity of the solution time complexity of this solution is order of n uh this uh power string method it's not really computational heavy because uh the size of the number is not much uh it's i think about it's still about transfer four only so we can ignore the complexity of this power string method as it's not uh much computationally heavy so it's so time complexity overall is off and only and space complexity is also often as we are using uh additional string to solve this problem so that's all i wanted to talk about regarding this problem statement so if you like my explanation and if you like my code walkthrough do give it a thumbs up and you can share this with your friends and you can subscribe to this channel clean coder once again thanks a lot for watching this video hey guys do check out this instagram channel clean coder community for all the jokes and memes related to software engineering thanks a lot
|
Serialize and Deserialize BST
|
serialize-and-deserialize-bst
|
Serialization is 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 a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
**The encoded string should be as compact as possible.**
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The input tree is **guaranteed** to be a binary search tree.
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
|
Medium
|
297,652,765
|
1,224 |
hello friends firstly Merry Christmas so today let's of 1224 maximum equal frequency we're given array numbers of positive integers when did you return the longest possible length of an array prefix of numbers such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences so when each term says the frequency of an element we will think of use a hash table but let's first the see the scale of these numbers Hector is very small so actually we can use array as a hash table we can we need the couch array and that means how many times this number occurs and we also need a frequency array it means how many number have the same frequency so for example if this is a given array we needed to iterate from left to right this 2 means 2 occurs twice 1 occurs twice and a 5 occurs twice and the story occurs twice and this frequency we iterate from left to right will mean to the first at you we get 1 equal to 1 that means the frequency of a number which only as a means only one number have the frequency of 1 and we meet the signature we should mark to you caught you what that means to because it's true occurs twice so it's frequency is true so the number of the frequency of 2 is just 1 only one number has the frequency of two and meet this one we should increment by 1 so 1 you go to 2 that means there are 2 numbers they are frequency equal to 2 then we'll meet the second one we should increment 1 so them is true you go to 2 that means there are 2 numbers their frequency you caught you two so on so forth so this is the to erase we used yeah we needed you Ketel as long as possible so we either the from right to left once the current term sub-array is varied we return the term sub-array is varied we return the term sub-array is varied we return the result so let's think how many cases can we have actually just true if a current or sub-arrays valley that we have two or sub-arrays valley that we have two or sub-arrays valley that we have two cases one is we exclude the current number because we needed to remove exactly one element so one case is we do not include the current number another case is we include the current number and we remove one element in the previous elements so let's first think of the simpler case we delete a current element what does they mean with delete current element we should the first letter the frequency of the code numbers i decrement by 1 so for example if the code 5 equal to 2 we first needed to letter frequency to decrement by 1 and at the same time we needed to decrement as a counter 5 by 1 and usually notice the order it cannot abuse which you should appear we first decrement the frequency all right then we decrement the count array and if we exclude the current element that means the preceding element should exist in the final result array so we just get a cut of the numbers I minus one times the frequency of the culture numbers immense well if it's equal to i we just return I plus 1 otherwise if we just delete one element or in the previous elements we just get the frequency of the culture of current number in the terms the cutoff the current number and if equal true I return I plus 1 why this is I because for this example currently eyes you could choose ever right because we exclusive it so the length of the array actually is I and the use of the frequency in the culture they are I mean if they're the frequency times are called equal to i we needed to return the sub-array include the current the sub-array include the current the sub-array include the current element is so it should be I plus 1 okay so that's it now let's write a code we first need to array which is the count and the size it just so well you know they're well and then we also need as a frequency correct the size also 1 0 1 and the we also need to uh um you quote two numbers dollars and we iterate the array foster the count of numbers I increment by 1 and the frequency of the code numbers I increment by 1 then we ear from right to left a minus 1 I greater than 0 by miles - one case if we included a - one case if we included a - one case if we included a current element that is if the frequency of the code numbers I times the coat of numbers I you caught your eye we return I plus 1 otherwise we do not include so we decrement the frequency code numbers I buy one and the count numbers I buy one so that means the preceding ammeter should be included so if the frequency of the code numbers I minus one times how two numbers I minus ma one you caught you I will just return I plus one the finally we return one because they said if after removing monument that there are no remaining element it is still considered that every appear the number have the same number of occurrences okay thank you for watching see you next time
|
Maximum Equal Frequency
|
minimum-falling-path-sum-ii
|
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
**Example 1:**
**Input:** nums = \[2,2,1,1,5,3,3,5\]
**Output:** 7
**Explanation:** For the subarray \[2,2,1,1,5,3,3\] of length 7, if we remove nums\[4\] = 5, we will get \[2,2,1,1,3,3\], so that each number will appear exactly twice.
**Example 2:**
**Input:** nums = \[1,1,1,2,2,2,3,3,3,4,4,4,5\]
**Output:** 13
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
|
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.
|
Array,Dynamic Programming,Matrix
|
Hard
|
967
|
1,463 |
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 daughter's I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go hmm so at this point Q for I'm 6 minutes in ish I don't have a good chance to finish a very high rank so this is Q for cherry pick up - so I'm so this is Q for cherry pick up - so I'm so this is Q for cherry pick up - so I'm a little bit I'm not hustling but I'm like okay have a mental clock it's going very well let's get it correct if I get it correct without a wrong answer I'll probably finish in a good place so here I look I read the problem and I immediately knew that the first thing I had to do was pull up the calculator and pull it out I said n is equal to 70 or C is equal to 70 I have what I did was send it to the third power and I also double-check 72 for power and I also double-check 72 for power and I also double-check 72 for power and we in the thing that you'll see later so that's what I'm doing now I have my calculator just to check the numbers just to make sure that data is a feasible algum and once I did figured out that it was a feasible album I start coding on the dynamic programming algorithm initially later on the video because I'm just to think talking over my god process but the idea is that when I'm doing the base case where if the row is past the last world then we return zero because you're not picking any more cherries or yeah cherries right and a and B are basically we're robot one and what about two is right now so and that's what I'm trying I'm setting up and right now more so I think right at this moment I'm pulling up the calculator and check out 70 to the fourth because they sent me to the dirt states that's what I did do the math one but then I was like okay do I need inside this algorithm do I need an O of like how of a grafter we need right and actually turned out it is not n to the fourth but it's n to the dirt but I wasn't quite sure yet how because I think I just don't know but I added an if statement here so because there is a symmetry and what I mean by that is that if you could swap where a and beers and it'll be okay so in that case it is mirrored so then you just choose a to be the first the robot to the left and be to the robot to the right and I'm doing something like mine optimization I think and before I don't that this maybe and n to the fourth but after I voted out I was like ow actually just n cube because for each n or for you to sell we're doing nine units of work if you want to call like that it's all up one obviously so onto the queue oh yeah but basically here we're just in numerating the number of ways a and B can be I'm just kind of winding out that my mental template by now so it's not quite uh yeah oh yeah but after I set up their initial conditions I was like okay what am i doing I'm just thinking about the conditions basically I have to check that a and bi in Bell I was like okay I don't want to copy and paste a lot so that's just given two variables and basically and a we're just well I say the next a that's why I yeah and I mean I thought wait where when they might a case crimes well that's my thinking but I was like okay if n is you go to end B meaning of the robots and the same place we only take one tick to the earth once otherwise we take their worth twice what well not twice but we take two cherries from a and the cherries from B and just to go back to the mirrored conversation here we do we make a left one and be the right one just for symmetry reasons and in theory just should be waiting to go this is about you 11 minutes and a little bit longer maybe 12 minutes by the time I actually submit I get I'm just double checking some stuff I'm looking to see why I'm is wrong and I was like ah yeah because I didn't finish fighting this thing oh I think I got to I don't know what I was distracted by yeah looks good I submit this would've been the 11 minutes in the 11 and a half maybe and I got walk-in so I was like ah why I and I got walk-in so I was like ah why I and I got walk-in so I was like ah why I was feeling confident about it to be honest but I went cold I wasn't sure that was maybe trying to visualize it so basically this wrong answer will end up costing me about eight minutes which would have been the difference between where I am and about fifth maybe six because I guess I'm not looking at Chinese seven yeah basically fifth was sex if I had gotten it right but the short answer behind my bug is that I started to vote but not at 0 and 0 or 0 and minus 1 I start on before that and if you look at the image on example to it I'll complain a lot about it later in the video so I guess you'll see it anyway but basically I misunderstood the picture to be you can go left down or right from the first choice so once I fixed that it was good that you and that I wasn't sure that was white just because from the reading but otherwise it is what it is and I'm oh boy still twenty-eighth if is and I'm oh boy still twenty-eighth if is and I'm oh boy still twenty-eighth if it seems like for the contest so gotta feel good about that anyway hang out of the other Lowry he'll complain about the cube for a little bit more but there's also an explanation so I will see y'all later pick up and that's let's get this started so this is cherry pick up - so started so this is cherry pick up - so started so this is cherry pick up - so this is a dynamic programming problem as you may see from the code which is here I'll go back to it don't worry I'm not skipping it but the idea is that a lot of this is gonna be dynamite you know analysis to see whether it was feasible but the idea is that well if you have two robots you might as well as move them at the same time at them on the roadway and if you do that then you can just then well how many rows can how many car well how many boats out there right there's 70 rows I think because I'm made sure because otherwise it wouldn't work so there's sandy rows each one contains let's call them robot a and we'll buy B and because that's what I have here what about a could be in 70 different places and what about becoming sandy places right so from that we just got brute force where it could be next step and that's pretty much what I did here so basically I for each row well if this is the end of the this is at the bottom we return zero otherwise we go one at a time we basically go okay well but a go left and right or go straight down well by B go left right straight down we do the math this is remember left right straight down no I suppose and then now we just check that both the robots are still in Bell and if they're in Bell we just take the min and max so this is just basically to store the two elements so that you can imagine that there's a symmetric right like if a is in position 1 and B is precision 5 that's the same state as be in possession a and a in position 1 right but Gracie you know swapping the world passes and really matters I what I'm trying to do here and in feely its should save you about half the time or someone like that so I wasn't I was a little bit worried about running time with 7 this is n to the fourth album and this is 7 T to the fourth which is why cutting a little bit closer I wasn't sure because especially with lead code the timing is always a little bit tricky and in the case here is that the cost right the cost as well if they're both in the same space then you cannot both pick up the space right so did that's why there's only one cause and then if they're not in the same space then you add well where they are and add them together and then the best would just be the best place for know this current state is just going for the next whoa with the robots in na and then B plus the cost so I thought that was pretty straightforward I don't I did this pretty quickly as well but the problem was that and I was a little misled by this example because I thought that you start before the 0th world so that you could choose on the first world different elements which based on the first of all you could select which I'd enter 0 or still 1 our civil and minus 1 or 0 and minus 2 I suppose basically I thought that you could have some freedom about it and that's what I got the wrong end so on how do we read it but this diagram was kind of sad face for me and it cost me 5 minutes and maybe a top 10 maybe a top 20 or whatever it is why I end up being top 50 but that's ok little bit sad because I feel like you could've also just have one problem and I would have like one example that would have self that ambiguity I mean I guess to here it does tell you exactly but that like I said the picture cut told a different story which is a little bit and the pastor's system testing and the first try so I guess it gave me a false sense of security and really have to read these things but some of that is of course that but you know people were really fast as well right so and I kind of knew that I was doing it so I was definitely you know like having that awareness and be like okay now you gotta do it kind of fast I can't wait to it that slowly so yeah
|
Cherry Pickup II
|
the-k-weakest-rows-in-a-matrix
|
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Robot #1** is located at the **top-left corner** `(0, 0)`, and
* **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.
Return _the maximum number of cherries collection using both robots by following the rules below_:
* From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
* When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
* When both robots stay in the same cell, only one takes the cherries.
* Both robots cannot move outside of the grid at any moment.
* Both robots should reach the bottom row in `grid`.
**Example 1:**
**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
**Example 2:**
**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
**Constraints:**
* `rows == grid.length`
* `cols == grid[i].length`
* `2 <= rows, cols <= 70`
* `0 <= grid[i][j] <= 100`
|
Sort the matrix row indexes by the number of soldiers and then row indexes.
|
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Easy
| null |
872 |
Hi gas welcome and welcome back tu my channel so today our problem is live similar trees so in this problem statement mein humse kya de rakha hai hume yahan pe na do binary tree ka root note de rakha hai root van end root tu humme kya karna hai Here we have to check whether the leaf note in both the binary trees is yours, is it in the modem, is it of other value, if so, what will we do with it, return it as true and return false, ok, so let us take this as an example. Through this, let us understand what is our problem, okay then we will solve it, so here you are seeing what I have given you in the first example, I have given you two binary trees, what is your binary tree? A tree is a data structure in which what can be Any paint node can have a maximum of two children, what is it, left and right? Either it can be only one, only left, it can also be only right, okay, so the maximum is left, you are right, let us see. If yes, then you are right, if it is a live note, then what is the lift node, is it in the order from, what is the value of, if so, then rent, then whom will you call a late note, the note which does not have even a single child, is not even left. And if you do n't take the right note, then which note will it be because its left child is also null and this is also null, so what will happen to all this? Your lip will be knotted. Now we have to see, left, right, here is six, this is also the first six, then what is 7, then what is here is also four, here is nine, okay here is also nine, here is one, let's come If we come here also, then see if it is from both, then what will we do here, will we return true? Okay, so now look here, what is yours here is three, so here it is not matching, then what will we do in return? We will make false further and we will see that we will not even need it, so see how we can solve this problem here because what we have to do is a leaf note, we have to see what is in which order, so what we have to do with it. You will have to visit this note, otherwise what do we do here, towersal will do it, which travels DFS, which of your comes in DFS, in order, pre order, post order, now you can solve this problem by doing it for anyone, okay. So what we will do here, let us understand through the first example how we can solve it, so see what we have to do here, we will start from the root note, from here we will keep checking whether any note has left and right child. Is it tap? If it is tap then it means what is it? Your lip is no. Okay, what will we do? We will store the leaf note of one trick in one vector. The live note of another TV will be stored in another vector. Okay, what will we do in both? We will do complete order traversal, we can do this order, we can post order, so what I did is pre order it, so I understand you through pay order, okay, so what we will do is we will go to the left because it does not have left right tap, okay Then we will check five, is its left join and right child null, is it not null, then we will go towards its left, are its left and right side null, is it null, then what to do with this note, keep it here. Okay, now this is a tap, because it is a tap, so we will go back because don't even take its left, go back here, we have seen its left side, we will see its right side, now we will look at its right side, so we will see whether it has a left and a right. Is there a child tap? If not then no problem, we will go towards the left, we will get the channels back, then what will you do, put them back. Okay, now you have seen the left side and you will see the right side, if you go here, what is the left and right, child, is that tap? What if it is a tap, so what will you do, you will insert it here, okay then what we will do is its tap, this note, this is also a tap there, we have seen it back there, we have seen it also, look to the right of it, back here, we We have seen the left side, now we will go to its right side, are its left and right style taps or not? If not, then ok, we will go to its left side. Sir, let us go towards F. Are its left and right styles taps? Is it a tap, then this lip No, just insert it here, then what will we do, go back because it is null again, we will go back because we have seen its left side, now we will go to its right, what is your left side and right side null? What if it is tap then what do you do, this is your note here, put it on this side, you will do it inside, okay, like this, what will you do, insert it in this, process from people, meaning you will do it here, okay, so like you will go to the left side of this. Here and then you will go to its left, here and then you will find out what both are, if it is a tap, then people will insult you, then this is a tap, back here, we have already seen this side, then back here, this is a tap, back here, we have already seen this side, then go here, then see, is it left and right, and is it its child? If it is null then we will answer 7 here. In this way, what will we do, we will visit all the notes, we will look at all the leaf notes, we will look at them left and right, then we will insert them here. Now this vector is b1 and suppose this is b. We will check whether b1 = B2, if so, is b. We will check whether b1 = B2, if so, is b. We will check whether b1 = B2, if so, then we will advise the system, if the return is false, then what will happen in this case, V1 will be your 2, 3 and what will happen in this, your will be 32, then are both of them equal, and if not, then the return will be false. If you want to go, then I will show you its name and a code. Look, what is there here, what have we done, two notes, sorry bacteria, that the root has to be returned when you tap, either if there is a value in your root, that is, there is a value in the note and the note. The left side of the note is your tap and the right side of the note is your tap. Date Mains, what is your credit, so what to do, you will insert it into the vector, you will then look at the left side of it, call the option, call on the right side, then people will do this. What will happen with this order, this vector of yours will be ready, so now go here and finally what will you do by comparing people leaf note van equals tu if note tu if these two are equal run tu honor vice dan falls okay then its time come back city How much will it be because what we are doing can take time, so what are you doing here, you are visiting this chunod, right here, in a way, here it will be on, this is the number of notes, okay and there is space in it. If you consider it then what will happen to you? It will be maximum till the maximum height, right? Oh till what happened? Height of tree, height of trick. Why see, how far can you go now? You can go only till the depth, isn't it the maximum? So, what will happen to you? Oh, it will be okay and here you are doing the vector, so the size of both of them will be the maximum, the size of C van and the size of B2, which will be the maximum of both, maybe look, it will be similar so both of them will be the same. It will be okay, if it is possible that one may be less and the other may be more, so we will take it, then it will be yours. If you think that you can add something else in this, then please comment, it is okay, I hope you understand. I must have liked the video. If you liked the video then please like, share and subscribe. Thank you.
|
Leaf-Similar Trees
|
split-array-into-fibonacci-sequence
|
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._
For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`.
Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same.
Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar.
**Example 1:**
**Input:** root1 = \[3,5,1,6,2,9,8,null,null,7,4\], root2 = \[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8\]
**Output:** true
**Example 2:**
**Input:** root1 = \[1,2,3\], root2 = \[1,3,2\]
**Output:** false
**Constraints:**
* The number of nodes in each tree will be in the range `[1, 200]`.
* Both of the given trees will have values in the range `[0, 200]`.
| null |
String,Backtracking
|
Medium
|
306,1013
|
1,020 |
everyone welcome back to the channel and thank you from lead code to any challenge problem number 1020 number of employees so uh you know we will just skip this part and I'll explain you the problem using this example so basically what we'll have to do is we have to figure out the number of ones in this given Matrix which cannot be reached from uh from the borders okay so and how you can reach for example you cannot go diagram you can just go in four Direction which are up down right side and the left side okay so we only have these four directions to move in from any singular tile okay and diagonal movements are not allowed I'm using this we have to figure out how many ones we cannot reach okay so uh the simplest solution I'm the best I would say will be to use a DFS approach file and what we'll be doing in the solution is to basically I'll run a DFS on each border elements for example this is my border right uh first row the last row First Column and the last column right these are my bosses so I'll run a DFS on each of the ones in the Border for example we had a one over here right so I'll run a DFS on this approach and I'll try to check if I can you know move to any other ones or not okay if we will be able to move to some other one then we will uh you know increment in one of our variable otherwise uh you know it's going to be zero so what I'll be doing is I'll count the number of ones we have in the overall Matrix and I'll check how many ones I can reach from the border elements so let's move to the solution okay so I'm gonna follow a very you know the VFS template where you need the number of rows number of columns so number of rows is basically your length of grid okay a number of elements in each sub array of grid is your number of problems right next thing is you want to have a state in which you can use your stroller with trade node so that you know you don't end up in an infinite Loop that's done next is I want to Define how many lamps I have and how many lamps I can reach to from the border elements initially I'll assign these two videos okay now I'll run a loop pin uh the rows and alphabetes from columns okay now what I want to do is I want to check if each of my element in thread and I'll you know we can simply just add on all the elements to number of lines so if there will be a zero at the correct value then it will have no impact right so number of Clan will remain the same otherwise if we found any one then we will increment that right number plan plus equals to uh what is it great column okay this is done next what I wanted to do is I wanted to just the DFS on all the ones we didn't wanted to uh you know run on zero elements right so I'll be writing a condition to check that so if my grid and if the element had this particular index is not zero and I have not visited the element yet and to visit it uh what else and of course like we will have we just run for the first row last row First Column and the last column right so to concise that what I'm gonna do is the row should be in uh what is the possible value 0 and rows minus 1 right and or I think or to T the condition over here or call columns n 0 columns minus one let me just separate out this one to increase the readability of the code okay if we get any if we satisfy this condition then I will run up DFS on let's current indexes okay and I'll add whatever result I'll get from this DFS in my number of teachable impacts okay um at the end I just have to subtract out number of reachable lens from number of total lengths okay but now we have to write the main helper DFS function right so for that we will Define a helper function and we will accept two parameters in it right now uh we'll have to write the base cases as we do in DFS so if minus 2 is less than 0 or column is less than 0 or my number of rows gets equal to rows which means you know we are exceeding the index for column is exceeding the available index or if the current value is zero got into value in zero what else yeah and we'd have to check if we have visited this or not so comma calling and visited so if this condition satisfiles let me break this out somewhere yeah if this condition satisfied I want to return 0. okay otherwise what I want to do is I want to add my current row and column invested right I will initialize my result with the one because of course again uh this should not be one because you know we have already terminated all those conditions where the positivity of results wants zero so it should initiate with one and what I'm going to do is I am gonna check for all the four directions right so which was one cell above below right and left so for that I'm gonna use copy paste this first four times and at the end we will just return Reserve okay so now let's fix this so we wanted to check the next element column plus one previous element minus one element below and element above okay so this will calculate you know this will check for all the corresponding elements and then we can just let's check out the test cases okay double object is set so let's see so the test question for accepted let's perform the evaluation and the solution also got accepted and I would say like we performed decent we are around the half marks so thanks so much for watching out the video and stay tuned for everything once don't forget to subscribe thank you
|
Number of Enclaves
|
longest-turbulent-subarray
|
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
| null |
Array,Dynamic Programming,Sliding Window
|
Medium
|
53
|
338 |
hey guys how's it going in this video i'm gonna go through his legal number 338 counting bit this problem is less as easy but i don't think that's so easy of a problem i think it's a bit tricky actually um this problem was asked by google and adobe in the past six months so what this is asking is to count the number ones in the binary representation of the number so let's say if we're given the input of n of two and we have to go all the way from zero one and two and then find the binary representation and then count the number of ones in that representation so um for example in here uh the binary equivalent for a number of zero is zero and one is for one 1 0 is for 2. so as you can see there are one here and also there's a one here as well so what we need to return is the number ones so the first one has no ones so that's why it's zero and the next two has two ones that's why we have to input one and one in here for the second example n is five and we have to go all the way for numbers the natural numbers all the way from zero to five right so zero one two three four five and uh this is the binary representation we have to count the number ones in this binary representation for example um the binary representation for number five is 101 so there are two ones in there that's why we have put two in there so let's walk through the algorithm to see how can we tackle this problem uh the first thing i did was to list out the binary representation all the way from 0 to 16. okay so this is the binary representation and then i count how many ones in there and then as you can see uh first one has zero ones and all the way to one two three and three for example this one has three ones right so because it's zero one for a number of seven and then after that you kind of find a pattern right when you divide this number in groups right so first one this first group has only one number second graph is only one number the third group has two numbers four group has four numbers um the next group has the five uh it has one two three four five six seven eight numbers so the way that i divide these groups by they are significant bit or leading ones okay and as you can see the leading ones were here over here and the leading ones over here so they are in the same uh column right over here so they all have the same leading ones until it jumps to the next digit where the significant bit is the next digit for example in here 16 is represented by one zero and after we divided by each groups and then we kind of can use the dynamic programming approach to build up uh the array that we did to return right so um so the thinking process is let's say um 1 can be represented by 2 to the power of 0 2 can be represented by 2 to the power 1 plus 0 and 3 is equal to 2 to the power 2 plus 1 and 4 is equal to 2 to the power of 2. so the leading bit increased by 1 in here and then for this chunk it's all around 2 to the power 2 right so for example 5 is equal to 2 to the power 2 plus 1 and the next block is 2 to the power 3 plus something right for example 2 to the power of 3 plus 6 is 14 and then we can use that relationship to build up our dynamic programming approach for example um let's continue this example so 2 to the power of 3 plus 6 the number of leading ones not needing ones the number ones is 3. and then number can be represented by a plus six so the number one in eight equals to one and number one is six and then we have done that earlier right we can look back to the dynamic array that we had before so dp of 6 equals to 2 and dp of 6 is equal to dp of 4 plus dp of 2 and dp of 4s always 1. so as you can see the pattern right dp of 4 equal to 1 dp of a equal to 1 db of 16 equal to 1 right so they are all like for example dv of 4 equals to 2 to the power 2 a to a is equal to the power of 4 right 2 to the power 3 etc and then we plus something so this is our dynamic programming relationship right so we can look back to the calculation we had before by using the current significant bit plus a fraction okay and yeah so this is the main idea to solve this problem and at this point feel free to pause the video and try to solve it yourself and then i will walk through my uh implementation in python okay now this is the implementation and first i have some two edge cases so when n is equal to zero and equal to one i'm going to return uh these two uh list which is one and zero and one and now we have a dp array which stands for dynamic programming i initialize the array to be none and plus the number of possible elements in this array so for example i need a m plus one because we are counting natural numbers so we're starting from zero that's why i need the plus one and the dp of zero and dp of one equals zero and one so basically this is a two uh building block over here and then what we can do is to have a significant bit uh keep to keep track of uh our so remember the number can be respected by a significant bit plus a fraction not a fraction possibly matter so i have a s bit in here to keep track of the current significant the first one is zero next one is going to be four third one will be sorry it's going to be 8 and 16 and 32 etc and then for i goes from the range of c r2 to n because zero and one we have already uh do uh deal with them right so we so the next one will be uh the second one second that's two three four five six all the way to n so here we check whether the significant bit is current right so if the two times the current significant bit is less than or equal to the current number and we are safe to increase the current significant bit by two multiplied by the current significance by two okay so basically we want to see uh which block they are in right so for example the current block is a for this block so this one's uh four and this block is going to be two right so base this the that checking right check if that's the current uh significant bit is that check is that current or not and now we can decompose the number so basically i is equal to two parts that we talked about one is a significant bit and the one is the remain we can rearrange the term becomes remain equal to the right i minus the significant bit if the remain equal to zero and the dp of that will be equal to one basically this one is look is for this line over here this is what line right here and this line right here also this line over here account for um the dp at the significant bit it's always one right so because it's 16 equal to the two one zero for example and a is equal to one zero and that's why at each of those points ep is always equal to one and then for other pawns we can decompose the dp by the dv and a significant bit plus the remain for example um 12 equal to db of 8 plus db of 4 right so we build up our dp array let's run it see it works and it's pretty efficient for time complexity it's going to be big o n and the reason why is it comes from this uh for loop and the for space complexity is b01 uh we didn't use any extra space db is the only array that we're working at working with and uh this is exactly the radar we return at the end so uh this is the end of the solution i hope you find this is helpful if it is please like and subscribe and don't forget don't trust this try yourself thank you so much for watching see you next one
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
386 |
hello welcome to the new video today we're going to solve this problem called let's go graphical numbers 386 it is a medium probably code and I did solve already but I would like to Showcase of like how I kind of solved it and my problem solving process um so yeah let's just get right into it um so we have it I already did it before but when I just do it again right and probably faster because last time I did it last night when I was like really tired I didn't have that much brain power to work with so I was stuck on it for like an hour or two so yeah let's just do this um okay so my problem solving process I just like to First explore the problem kind of read over the problem get the input and output and then maybe ask some questions if I have any concerns um and then go through some examples of the problem uh by hand to Showcase that I do understand it and then now that I do understand it um I can go over some approaches that we can do to solve this problem and then once I pick the most optimal approach or an approach that is doable for me um I'll go ahead and plan out using pseudocode and then review it with the time complexities and maybe some code review Maybe yeah so let's do that Okay so first thing is to explore the problem right so I'm going to read over the problem kind of get its endpoint output so given an integer n return all the numbers in the range one through n sorted unless they call graphical order okay so we know that there our input is going to be a number or integer n and then our output is going to be a list numbers and those numbers are going to be ranging from 1 through n right and then it needs to be sorted in let's go graphical order so sorted in lexicographical order right so one thing that comes into mind like what is I just type it right here so okay so what is lexical graphical order these are some questions I would ask the interviewer because I would have no clue but they'll probably have like an example right but from what I've uh research or just like Googled I should say is that um it's basically like this so um let's go graphical order is basically like this and B right as you can see the A's are repeating uh amount of times right and they're still repeating until they reach like I should say like the last letter so AAA could go to a z but then once we hit a z we have to make this into a b right so a b right just like that but if we want to go through it with like um a basically understanding first we go like a b c d e f g right that's all we know is uh just regular like in order right graphical is kind of different in a way I can't really explain it but this is how I understand it where if we're at the last letter right we kind of we can't just go we wanna okay so once we're at the last letter we can't really increase it anymore so we would have to go to the next letter to the to its left and like okay I wanted to increase you right just stuff like that and then um from there um just keep on going what is a it says a b can be increased to a b a and then it goes on right to a b z and then so on it can go on forever right that's how I kind of understand it um yeah but it's like alphabetical order from what I've understood but if we translate that into numbers um just be like this so we start one then we go up to like 1000 right or and one thousand right I'm kind of going over the example part of it but um that's kind of how you kind of solve this problem anyways you just gotta really understand what let's go graphical order is um and kind of the only way to understand is to Showcase it right and then yeah it's kind of like that then um I'm gonna go like 2 20. 200 and like 2 000 stuff like that three kind of like that I feel like that doesn't make any sense go do your own research but it makes sense to me so that's why I'm showcasing that like what makes sense to me and so yeah so that's what let's go graphical order means um so if we go back to the problem we do understand uh this part but um we kind of skipped over this part where our constraints our constraint is basically must have algo both end time and um must have space of n o one space right so these are kind of the input and output and um we kind of went over let's go graphical order means hopefully the interview would go will help you with that but and then we have our constraint right and so I thought we kind of know this let's go over through some examples even though I kind of went through some examples these are not really like actual examples of the problem they're just kind of like explaining what it means to be let's go graphical so let's go through some examples okay so let's just say that our input is going to be 10 right pretty simple you would think um so our output I'll just put on another line or output so people just think it's like one through ten right like that's lexical graphical order but no as we went through uh what I explained right this is kind of what it is right um we keep on going until we hit the um the end letter to Z but in this case for us it's nine so um one can get incremented to ten right because that's let's go graphical order in that case well it is right because zero is the first letter right one in here um yeah zero is the first number so it kind of makes sense um and then we can go up to 1 110 and then once you hit 10 you have to go back to um the lower number so I guess two and three four five six seven eight nine right because if we reach 10 already um that's our Max right um yeah if you want like an example from here I'll let's say um our input is 19 right in our output it's gonna be kind of similar to that where you have starting at one and then go to ten right and from 10 uh since 10 is not since uh the last digit is not nine right because it's not our last letter which is z because Z is equal to 9 in this case um like in terms of like last letter last number right and so we can keep on going with 10. so 11 12 13 14 15 16 17 18 19. so once we hit the last letter we want to decrements and move on to the number that is increased on the left because we're like okay we reached the max here so and once we reach the max here let's move on to the next number and we can increment that number right so that's why we say um once we hit the 9 and 19 we go to two three four five six seven eight nine right just like that and I kind of makes sense to me because I've also done it because I've also went over it right so yeah um so let's say what about triple digit how would that work I think it would be easier if I just made it like number 120 or something like that let's see our input's like 120. of course I won't go through oh uh I won't go through n of those I'll probably like skip over some so 120 and our output is going to be like this right so start one then we go to 10 and 100. right then from 100 we have to um got to go in order now like just by the order so we go through 100 all the way up to 109 been for 109 you go to um 11 right once we hit this nine um we're done with this nine so we have to increment the next number to its Max right but then we hit 11 and then 11 um we can it's called graphically increase it to 110 right um and then just keep on increasing this zero up to its Max so we'll go to 119. and then 19 will turn into 12 because we're done with nine so we want to increase the next value and stuff like that and so then we hit 120. we still hit 120. oh no we hit 12 oops and we hit 120 right and then from 120 um we kind of already reached Max because it really reached the max here so what we can do is we can just go back and I think I'm pretty sure we have to um go back to 13. I'm pretty sure right am I right I'm pretty sure I'm right because about to keep on increasing the next number so 13 and then that goes up to um goes up to 19. and then um we think and then it would be two finally two and then the whole process would go start all over again right 20. yeah so very interesting stuff I guess so that's kind of um how it is and um and yeah so I feel like we went through some examples um that kind of showcased that we do understand the problem how it works and I hope I'm hoping that me saying that we reached the max or n the max number the max legit of the max number of that digit and reaching n we have to like go on to the next number somehow and increment that instead so I hope that kind of helps you like kind of understand what kind of algorithm we're gonna go for right so now that we do you understand the problem um I'm going to go over some approaches that we can do so approaches um there's not that much approaches in my opinion unless I don't know of any but I think the only approach that we can do because I've done it I can do like oven time right um we're going to basically iterate through the list um oh wait actually we don't want to iterate through the list we want to um once a loop we want to Loop um until n and then um keep adding numbers in place called graphical order um yeah that's kind of the approach and then since we're not doing a for Loop you have to store a current number so initialize acre number thing to keep on incrementing because again if we went through like a for Loop like for Iron Range from 0 to n um how would we get like 10 right because it'll be one two three but in this case it's 1 10 100 right that's kind of why we have a current number um I feel like you could still do that with like a did you do that with a while loop I mean you could do that with a for Loop and like wait I don't even know what I'm talking about I'm just thinking out of my mouth not out of my brain Okay so yeah this is kind of it and then we're going to have like I'll go determining uh basically called graphical order oh just stuff like that so I think that's the only approach we can do so just stick with that so I start it and now let's go through a plan right so what I'm seeing is that we start at one um so we're going to uh append every time we Loop of course but before that um just write that down our for Loop but before that I want to initialize um initialize karnum and uh result list so yeah destination initialize them and then um I feel like Cornell should have to start one because that's our list right um we start at oops we start at um one through n okay so every time we iterate through the list we definitely want to append right so we want to I mean every time we go through n once you append right once you append the what whatever the our current number is so we're going to say res dot append the kernum okay there you go and then okay so in this case let's just say that um n is equal to 100 right as you can see here we keep on incrementing we keep on multiplying by 10 right but in this case right where we have our 13 right if we were to do 13 times 10 it would go overboard so that's kind of a condition so basically make it let's go graphical order so if let's say so if um if kernam times 10 is equal is like is less than equal to um n then we're going to um once you times it by 10 and save it right um so that's kind of good but as you can see if that's not the case because right because here we're at 100 right and we can't times 10 because that would be over our input um so we just kind of keep on incrementing until we hit the max number of that digit that we're on right now so we can say like else then we have to basically increment kernum by one okay but there's a case so there's a case right so once we hit the max num the max digit we're going to um stop with this legit we're at right now because already at Max so 109 we can't go to like 199 or like 191 that wouldn't make sense in let's go graphical order right you have to be like okay we're at our Max number so we want to increment keep we want to keep incrementing at the digit to our left right um there's no term for that I forgot the placement called um but I'm not that smart but I'm smart enough to know what this is so um in that case we reach the max number so if Max number wait important thing is um how would we know like oh this is a huge number right 109 that's a huge number for our brain right how do we extract that nine how would we tell the computer that well we can just say kernam modulo 10 right so modulo basically gets the remainder so 109 divided by 10 that's going to be um it's gonna be 10 right because uh 10 times 10 that's 100 but we'll have a remainder right of nine so modular basically gets a remainder right so if the remainder is nine then that means we want to keep on incrementing the next number which is this zero the zero in this place in this placement all right so how to drink some water so um I think I yeah um so I already forgot okay so oh yeah oh let's see right so if our last digit is equal to nine then we're going to basically um we're into basically um go to the next number and to get to the next number we have to divide by ten right um basically divided by 10 so 100 divided by 10 right that's 10. right and then if you do that boom we hit that now it's 10. so our digits currently at the zero right I want to end up like this 11. that's why we have this current num plus one so that kind of makes sense so um Kerr correnam is equal to her num integer divided by 10. so that's how we kind of get to this 11 from here once we hit a Max right our Maxi should have nine to move on to the next digit to increment so yeah but here's the thing there's going to be a case where um okay so there's gonna be a case okay so let's say we have one and then all of a sudden it turns into like 109 right 199 and our output is I mean then our input is like um where n is equal to 200 right Okay so if we did this with this if statement um it will just turn into where current nums is going to turn into 19. right but would that make sense that's not really let's go graphical order right in this case to be real let's go raffle order like okay reach the max number and here and in this digit so we want to move on to this digit right now we're going to increment this one instead of these two nines so it would be like this two right but if we just had this if statement it'd just be 19. right so we're going to do so we have to make this if flip into a while loop so while kernam while the digit is nine right you would have to it would turn up like this so this would be good very good it works right but let me also show you like some other case that could be wrong right so let's say um just like in this example we went through an input of 10 right as you can see from 10 we stopped at 10 even though it hasn't reached um nine yet well we slept at 10 because um that's our um max number in this list that we can go through with Mexico graphical order right so that reaches the question this is kind of doing the same thing where we reached our Max number like in general so we had to increment the next digit so we're going to do the same thing here but we can also say or I need to put this into like a compound so or occur num is equal to n boom solved so yeah that's pretty much it a really short line of code and we could just um yeah this is like already like code it's not pseudocode but it's kind of pseudocodeish a little bit not really and then we could just return um num or we can return result because that's pretty much it for the plan now for the plan act just copy paste it to be honest I'm pretty sure I can just copy paste it um all right now um that's a bad practice actually so now that I've gone through my plan let's just go ahead and code my plan out right so let's go ahead and Implement my plan so we're going to I'm going to create a main function I'm gonna pass that so it looks nice and within main I'm going to um run the program I mean then within the problem I'm going to run Main and then I'm going to make a helper function that helps us solve this problem so get let's see code graphical numbers and then it's going to take in um an argument of n because that's what we have in our input right where it takes in an integer n right I'm going to pass it for now and then for our test code driver case for our test cases and our driver I'm going to get user input so user input is going to equal to integer inputs because we just want n right and then when I call get xeco graphical numbers and I'm going to give it the argument of what we just got which is easier input and then I know that this is going to return a list of numbers because we said that our output is going to be a list of numbers and let's go graph our order so what I'm going to do is I'm going to print out the return value of this function and then um yeah we can go ahead and just basically copy and paste our plan right here so first off before starting this algorithm we want to initialize current num equal to no equal to one our kernel is equal to one result is equal to an empty list and then for Iron Range starting from zero all the way up to n right we're going to basically uh pen whatever number we have right now as current num so res dot append current num and then I'm just going to basically copy and paste what we said it's already explained it right and also that's not the case so a while or num last digit is nine or current num is equal to n we're going to increment the next number and we're going to go to the next number and keep on incrementing that number let's say one right and then at the end of that for Loop um once we get out of that we're going to just basically return um result list and that should be good so if I were to copy and paste this in the code um I feel like it would work so I'll run answer oh wait what'd I do oh I went through it too fast there you go oh oops okay I keep forgetting all right so it runs um another runs with these cases um I think the only case that really matters is this test case where um or like it's like a four digit number so let's just say it's like 299 run it runs okay um let's go submit this and it works it beats 90 so that's really cool um yeah pretty cool last time it was 80 so taranji yeah so now that we know that it worked let's go ahead and review it um its complexities right so to review its complexities um it's definitely all of n because we're going through um we're going through n numbers one time right and then we're using all one extra space I'm only using current num to do that's why it's all one extra space and it's not over and extra space because we have to return the results either way so that's open extra space um yeah that's pretty much it hopefully you guys kind of understood this problem better than I did when I first started um you did not then boohoo that sucks but keep on going and yeah
|
Lexicographical Numbers
|
lexicographical-numbers
|
Given an integer `n`, return all the numbers in the range `[1, n]` sorted in lexicographical order.
You must write an algorithm that runs in `O(n)` time and uses `O(1)` extra space.
**Example 1:**
**Input:** n = 13
**Output:** \[1,10,11,12,13,2,3,4,5,6,7,8,9\]
**Example 2:**
**Input:** n = 2
**Output:** \[1,2\]
**Constraints:**
* `1 <= n <= 5 * 104`
| null |
Depth-First Search,Trie
|
Medium
| null |
1,992 |
hello everyone welcome to coding culture this channel will contain those programs whose explanation is either not present on youtube or the explanation is present but not up to the mark so without wasting time let's get started so this is a new question of the lead code and it appears in the bi-weekly contest of it appears in the bi-weekly contest of it appears in the bi-weekly contest of saturday for september okay so it's a meeting level question and what we have to do in this question is that we will be given a binary array of one and zeros and what we have to do is simply we have to return uh sub array uh to the array of number of columns will be equal to four and we have to return the top left bottom and right of each of the line like this is one line and okay so what will be the top bottom left and right the boundaries there will be zero and for this one top will be one my left will be one my top will be one my left will be one and my top most left and bottom most right will be two so now we have to return the top left corner and bottom right corner so we have to return it in our 2d array the currents will be four and yeah we have to return any number of lands we found okay so this is uh just a variation of the question number of islands i hope that you must all have done the number of islands question and we will simply do a dfs and yeah so okay so now let's try to discuss the approach which we will be going to do it is that every given uh this matrix and i will run a loop and check if my ij my land i j equal to 1 so i will simply go into a dfs and in dfs what i will do is i will first of all make this one as a zero okay yeah so i will make this one as a zero and i will store the maximum of the my i and maximum of the g and those will be our boundaries like we okay so if we already know the top left corner we only need to know the bottom right and bottom right corner will be what maximum of my i and j the maximum which we have traveled okay i will make it as one and check if it's uh anything left right side our bottom is one or not no it's not so it's a bottom right will be equal to top left and the both will be zero then i will go and okay so now i will get one here i will make it as zero okay and then i will check for my bottom left my maximum of ing okay so here i will be same and column will be plus one column so yeah my i have got the new column so i will take it and make it as zero similarly make it as this zero also so here my row is same my row is different but column is same here my column is different but my row is in here both are different and both are maximum my row and column both are maximum so i will take it and yeah my row and column new row and column will be our bottom right corner and i will store it and then move on and further there are no one remaining so there will be only two 2d in that 2d matrix result there will be only two rows and four columns like i think you must be getting what i'm trying to say like here there are two lines the number of lines will be two and columns are going to be four always like here the number of lines is one here the number plan is zero there is no one here okay so one is representing the farmland and zero is presenting forest land so we have to return the coordinates of the farmland so without wasting time let's try to code it and first of all what i will do is make an address since we don't know how many number of yeah we don't know how many number of lines will be there so i have to make a arraylist not to we can't make it directly uh okay so interest in teaser and let's make address equal to new arraylist okay and now i will simply run a loop okay and i will simply okay so yeah this question is just a variation of the number of items i've already taught so i will check if my land of i j equal to one yeah so now i will call that dfs okay and the dfs in vdf i will just pass the land my control and kind of okay so now there is intuition okay so now let's talk about uh yeah there is a bit intuition here so and what the intuition is that's simply my okay whenever i will find my one that will be my top left corner so i will store now first of all let me make a arraylist i will make arraylist whenever i will get one and let's name it as tmp equal to new arraylist okay and i will add tmp.add my new i okay and i will add tmp.add my new i okay and i will add tmp.add my new i okay and my new j yeah simply and here what will be my bottom okay so yeah let's make two global variables in bottom and right yeah so at this point i'd like to look at this point my bottom right will be also be bottom will be i same row and my right will be same as the column j okay and then i will move on to the dfs and in that during dfs i will check i will update my bottom and right to be the maximum of inj and at last i will add it into my dmp so after doing the dfs i will get my bottom right i will simply add them bottom tmp dot at right okay so yeah this was it and at last i will simply add mp to the result okay so now what the only thing remaining is to make a dfs call and you must all will be knowing that you how to make a dfs call if not i will tell you no problem so yeah private and the return type will be wide and the dfs and the arguments here but with the arguments here will be my land r and c okay and i will mark it as zero and i will take my bottom is equal to math dot max bottom comma the current row okay and similarly i will do for the right equal to my dot max okay so i should take it as a row okay yeah because the r is already taken so yeah row and my c column okay and next what i will do i will simply call the default okay so now there is one more intuition and that is like we don't have to check our upwards and leftwards we would have already checked as we are starting from the zero and moving forward so we need to check downward and right word okay so dfs i plus one j for the downward and i solu plus one comma less than 0 or is line i and row and c equal to if it if equal to zero then i will simply return as its of no use okay and yeah so yeah and after doing it i will simply convert to my i relate my registration to a result adding two daily i think you must already be familiar with this okay so no problem at last okay so let's try to run this code and check if it is running successfully or not because connection here is a bit weak so yeah it's again okay yeah one more one bracket is extraordinary yeah that's why it is advised to always use the variable names as it is because yeah you must might have a controller okay now let's try to submit it should run yeah it's running okay and the other type of opticity and space is also so what we are going to be doing it is very simple like we will be taking two global variables bottom and right to check our maximum row and our maximum column yeah for a given line and i will store it into tmp and at last i've written dmp and it is a general classic bfs you must always be moving it you all have done the problems like number of eyelashes yeah so that's it that was question if you if this solution has helped you in understanding this question i think the channel must deserve to subscribe so please subscribe my channel and if you have any doubt asking the comment section keep on going bye
|
Find All Groups of Farmland
|
sort-linked-list-already-sorted-using-absolute-values
|
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape.
|
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
|
Linked List,Two Pointers,Sorting
|
Medium
|
148
|
304 |
all right let's talk about rinse some curry 2d immutable so given a metric 2d matrix so you just have to calculate the sum of the elementary inside the rectangle defined by its upper left corner and lower right corner so this is like you have to define in the entry and this is from upper left to lower right so two one and four three right so i just calculated the sum of it so this will become two plus one plus three and i think this is become four five eight right eight and there's another rectangle one two so one two and this will become 11 yes correct so by using the previous method so if you look at the questions 303 and you will be able to know we use the previous song technique so i calculate for every single um every single element and then i mean the sum of the element for every single cells and then i will just using my uh 2d array to calculate what is a little bracket solution and if you look at the solution this is pretty much it so i'm using this technique so if you want to calculate the ad on the abcd rectangle you grab everything from od and subtract ob subtract oc and since you subtract twice on all on oa right you need to plus or a and this will become the best solution and if you're using some range right this will take you all of one because you already traversed all of i mean times and right or n squared doesn't matter so this will actually uh give you the best performance so let's just stop calling and if you have any questions uh you can ask later so in 2d right three sum i'm going to say in m equal to negative and also unable to next we add first position and i'm going to traverse so before i traverse i need to initialize that so please go to the new end and plus one don't forget you need to you need extra space for the reason why you need extra space is because you need to uh i mean basically you don't need the person first row and the first column you just have to collect every uh sum from these cells to these cells and then this will actually determine the previous sum so for this all right you add a uh up left and off left and then this will actually become your first cells on previous sum so for being i go to one i less than n less than equal to n i plus so in j equal to one j less than equal to and j plus the previous sound is actually a i and j is equal to matrix of this metric so if you want to calculate one right we need to get this value three right three so i minus one j minus 1 and then plus the top and the left was previous sum i minus 1 j plus 3 i mean baby minus one but we also need to subtract the prism at i minus one and j minus one this is because when you take everything imagine like when you take everything from here and then you need to calculate for this position right you still need everything from here right so you need to subtract this value and when you subtract this value you actually get this i mean the rest of the cells some and then this will become more accurate so present minus present at i let me just move a little bit at i minus one and j minus one and here we go so when you want to return for some range right you will be able to know that you take everything from all d right on or to d everything right so um when you're using a present you have extra space and then just making sure if you take everything from od and then you have to have plus one on the row and then column so um pretty soon you are two plus one column two it's a trap you'll subtract ob you don't need the plus one on the row because we are not including b right so pressure rule one and then column two oc the oc is three sum and if you know it's row two plus one and then you don't need to include it in your column and you just need to add oa right so please sum row one column and this will become your solution so let's just run it hope i don't have any typo all right here we go so let's just run it and this is the solution so let's talk about timing space complexity so this will give you all of m times n right m times n so time is over and we should all and then follow some range is all of one and this is the best solution and if you want to have all of um unscrew a solution you can just traverse using the full loop but i'm not suggesting you do this and if you have any question leave a comment below subscribe if you like it and give anything feedback if you want all right bye
|
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,413 |
hey everybody this is larry this is day 11 of the leeco daily challenge hit the like button the subscribe button join me on discord let me know what you think about today's problem is minimum value to get positive step by step sum so what does that mean uh it means you should hit the like button to subscribe and join me in discord did i always say that i swear sometimes i'm just a little bit uh i don't know i have very bad memory these days i'm old okay so given numbs you still have a positive start value you can calculate the step by step sums plus elements and numbers return the minimum positive values start message that just step by step sum is never less than one okay so we start at four then okay so five is less than one okay um i mean i think we can just probably just simulate and then get the minimum number um of the path and then we turn one plus that or something like that i think that should be okay so yeah so let's go yeah min is equal to minimum positive value okay i mean so min is at least one um so yeah i mean i guess yeah minimum should be positive okay well that's one of the examples but that would be something honestly i can race easily see myself uh messing that up but yeah so for four x and nums we just sum x and min is equal to min of min uh how do i want to say so if current is negative 1 for example then we want the answer to be two right so that means that we want um so okay so if current is less than zero then what is it negative current plus one reset so for example if it's negative three then we want four so this is negative this plus one okay difference is probably not necessary but um so we're looking at this plus um so now we're looking at all these possible values so this is actually the max of this because we're forced to right otherwise um and this actually works for positive numbers as well in the sense that there'll be a negative number but i think this should be good uh yeah that looks good let's give it a submit the way that i would think about this poem is just like draw it out um i think it might not be really i don't know if this is obvious but um because sometimes it's one of those things where i have enough practice that it looks um quite obvious to me but that's just years of experience right and so if you haven't seen similar things before it might not be um as easy but for this one you have i think i just kind of visualize it as an xy graph of like okay so going from left to right you see it going like up and down and then trying to get the minimum number because now you're just shifting the entire graph upwards right um so that's basically my visualization that enables this solution and of course you can definitely do this in smaller code or shorter code but here i'm just trying to you know get it correctly and just like if i have a typo it is very easy to debug versus if i had a one-liner it might not be as easy to one-liner it might not be as easy to one-liner it might not be as easy to debug um but yeah um i feel like this is probably too easy for an individual question but maybe it could be like a warm up or something like that i think this section um i haven't done recently but for whatever reason i just forgot to be honest but people or someone has asked in the comments so yeah so um so it's an interview i probably would ask this is a little bit too easy and a little bit too straightforward maybe as a warm-up and with the maybe as a warm-up and with the maybe as a warm-up and with the expectation that like hey this is just to you know get your fingers loose you have a couple of minutes um let's say less than 10 to kind of you know write this formula and think about this um but this wouldn't be like you're like this would be part of an interview like could be a one-part interview wouldn't be the one-part interview wouldn't be the one-part interview wouldn't be the entire uh thing um it is i still think it's price is still on the easy side um even with my math bias so yeah anyway um yeah i mean i don't know this is a i think this is okay for me so let me know what you think um and this is clearly linear time constant space if you have questions about that let me know i'll see y'all later stay good stay healthy to good mental health and take care
|
Minimum Value to Get Positive Step by Step Sum
|
maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
|
Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.
**Example 1:**
**Input:** nums = \[-3,2,-3,4,2\]
**Output:** 5
**Explanation:** If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
**step by step sum**
**startValue = 4 | startValue = 5 | nums**
(4 **\-3** ) = 1 | (5 **\-3** ) = 2 | -3
(1 **+2** ) = 3 | (2 **+2** ) = 4 | 2
(3 **\-3** ) = 0 | (4 **\-3** ) = 1 | -3
(0 **+4** ) = 4 | (1 **+4** ) = 5 | 4
(4 **+2** ) = 6 | (5 **+2** ) = 7 | 2
**Example 2:**
**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** Minimum start value should be positive.
**Example 3:**
**Input:** nums = \[1,-2,-3\]
**Output:** 5
**Constraints:**
* `1 <= nums.length <= 100`
* `-100 <= nums[i] <= 100`
|
Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.
|
Array,Binary Search,Matrix,Prefix Sum
|
Medium
| null |
1,342 |
Hello Hi Guys Welcome To Our Dhundhi See The Question Number Of Video then subscribe to the obscene take into account only to condition with numbers even lord will take anti through bill account Speech will initially be 200 and will look like number is grated ginger roll number 201 number with 12 number is award and so when he Twitter - wow but all far away - 21 2012 the center and while doing this you also need to increment account because you Have Taken Want To Reduce Number Finally On 110 Taste Garlic Ginger To Drows And Skimming Perfect Result Submit Number Of Institution Mathematical Operations In Number And Give Only On Thus Devotion For That One Will Put Not Equal To One Number Divided Into Your Subscribe To So 101 Divided By Two Good With Just One Se Emphasis Removing Shifted To Give Number Is Dam Clutch Sewerage Department Settings Symbol And Like Share And Subscribe To This Video Not Using Arduino Id On 200 Personality 10 P0 Is I Hope You Like It And Chew Food On
|
Number of Steps to Reduce a Number to Zero
|
queens-that-can-attack-the-king
|
Given an integer `num`, return _the number of steps to reduce it to zero_.
In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it.
**Example 1:**
**Input:** num = 14
**Output:** 6
**Explanation:**
Step 1) 14 is even; divide by 2 and obtain 7.
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.
Step 4) 3 is odd; subtract 1 and obtain 2.
Step 5) 2 is even; divide by 2 and obtain 1.
Step 6) 1 is odd; subtract 1 and obtain 0.
**Example 2:**
**Input:** num = 8
**Output:** 4
**Explanation:**
Step 1) 8 is even; divide by 2 and obtain 4.
Step 2) 4 is even; divide by 2 and obtain 2.
Step 3) 2 is even; divide by 2 and obtain 1.
Step 4) 1 is odd; subtract 1 and obtain 0.
**Example 3:**
**Input:** num = 123
**Output:** 12
**Constraints:**
* `0 <= num <= 106`
|
Check 8 directions around the King. Find the nearest queen in each direction.
|
Array,Matrix,Simulation
|
Medium
| null |
309 |
Everyone welcome to my channel, so go ahead, we are going to do question number 10 of the playlist and the name of the question is Best time to buy and sell stock with cool down period, a little notification has been done, general stock, there are many variations, okay so What did Google do by adding another different variation to all those variations and asked a new question in it? Liquid number 3009 is a medium level question. Madam, is it pretty noisy or will it be easy? When you understand it, if you write a story then everything will become easy, okay? First of all give Google Microsoft Meta Salesforce Amazon OK Now coming to the question, what is the question saying that if the price of every single day is ok then what is telling you is how much can you reduce the maximum profit by applying and selling. Now you cannot buy again after doing this, right, you have selected first, only after that you can buy now. Tell me, if you already have any stock, then you will have to buy it first, it is not late, first you will have to sell it, only after that, buy again. If you can, then you ca n't buy again after A. Okay, the second thing is that if I take you have sold. Okay, if you have sold, brother, you can't buy. You have to wait for a day. If you don't tell him, then you will buy from him. You can't just give next buy. Okay, you have to start again from I Plus. You have to decide how much you can reduce the maximum profit. Okay, now let's see how this input is given to us and how is the output of this input. If there are 3, then look at it like this, in the beginning, you have back, if you do not have any hobby, then starting, on the first day, you have to buy, right, sorry, on the very first day, you have to buy, so what did you do, if you bought on your first day? Brother, you have done it here, okay, what did you do after that you sold it, if you sold it on the next day, how much was the profit? Brother, if you bought it for ₹ 1, you sent it for ₹ 2, then I am Brother, if you bought it for ₹ 1, you sent it for ₹ 2, then I am Brother, if you bought it for ₹ 1, you sent it for ₹ 2, then I am writing the total profit here in the profit. Ok, the profit is Van. Now you have made the sale, so you just give the next one, brother, if you can't do it then it will cool down, right? CD, say cool down, after that buy it here, right, my man will buy it here. Buy Aircel is the option for both. Okay, Buy Aircel is the option for both, but when will you sell? When you have something, only then will you sell. Okay, so you are buying here at zero and you are selling here at zero. Okay, so at zero. If you bought it for Rs 2, then what is the profit? If it is two then the total profit becomes three. Now how much can you reduce the maximum total profit. Now he is asking you. Okay, so you have many more options like I take my brother. If you have done it here then it is not possible that if you had not done your sale here then you have the option. You have the option. Either way, sorry. If you have bought the stock then you have two options. You will either sell it or not. Sell it and you will get it already. Every time you ask yourself that why brother, why do you have to make it through DP only, you have the option, you are seeing that you have the option to sell on this day or not, you have another option after that. Brother, what is the maximum profit to be made or is the maximum profit asked? Well, by now you must have understood that brother, this will be a question of DP only and if you make that question also, then you will make a tree like the tree of DP. So you will get into the repetitive problem, I will make a small one in it, let's see the repetitive let's C, I will take such an example, now by the way, on the first day, you will have to buy, brother, okay, so on the first day, you came here, you were here on the first day. So you will have to buy it because in the beginning you have stock, no, okay, so you bought it for ₹ 1, now what is left with you, it ₹ 1, now what is left with you, it ₹ 1, now what is left with you, it is here for 42 rupees, okay, you bought yours on the first day, now brother, I am gone. It is okay on four that you have bought your stock, that is, if you have the stock now, then you have two options, you can say otherwise and not sell. Okay, if you sell, then what will happen to you? You bought it for Rs. 1 and sold it for Rs. 4. Given, if you are looking at profit, then where will the index go? If you look at A, then no problem, there will be no profit. Index A will go at 2. Okay, we have both till now, so if we look at the profit here, then there is profit till now. Not only zero because we have not sold till now, okay now we have sold here, what did I say after selling, you have to wait, there should be a pull down of one day, so if it is golden then we cannot do anything on this day. If you have then we will move ahead. Okay, now here you have two options, so you can buy, sorry, you can sell. Is this the path of note sale being talked about? So if you sell it, what will be the profit? Brother, if you bought it for ₹ 1, then sold it for 2 rupees, then it Brother, if you bought it for ₹ 1, then sold it for 2 rupees, then it Brother, if you bought it for ₹ 1, then sold it for 2 rupees, then it becomes zero plus van. The profit is fine, and if I will move ahead, then CR Auto is fine. Our story here is over. If you did not sell then still there is no option brother, everything has gone ahead, everything is over, okay, so look, we have multiple parts, no multiple passes, one thing, this is ours, it is fine, we have max profit from it, we had extracted it got profit, okay So it is the maximum in each pass, that is why our output will be three, right? You must not be seeing repetitive here, you must have seen one here that here something is being solved for you and here also it is being solved for you. Now if both There are different states of but I am telling you that if you take a big example then you will also see repetitive sub problems, okay then from these two you must have come to know that this DP is a question, okay then remember first of all DPA. How to create a question: First of all, before writing the code, we will develop the story of the aunties which exactly matches our question. Okay, so let's first develop the story, then see how our recognition function is, how we will write it. Okay, so first of all you should know that brother, you will have to buy it on the first day because you do n't have the stock, if the one who starts in the beginning gives it, then it will always be my bike. If brother says, I am buying, it will be only the bike. That brother, I am keeping our brother's variable true that brother, I will have to buy it on the first day, this thing is clear, what does it mean that I look, I will write a function, simple max, I will write a simple function, let's give the name of the function, we will solve it. Starting and remember the first day, what do I have to do, on the first day I have to buy because they are zero, otherwise they reduce, okay, we solved it like this, I called okay, then understand the story, it is okay, just gems, it is nothing at all. Understand the story as it is okay, we had created the search tree above, no, I am going to do the same, nothing else, no, what all did I send, brother, I sent prices, I sent zero, I did not send index first, so let's take these IDEX men, it is okay. Let's take de man, it will make you understand better, okay, give zero, after that N was sent and brother, I had sent, okay now understand the function carefully, first of all, like every time, brother, if de is what. I have become greater than equal to you and by the way, your eye has been exhausted. If you have seen your entire country then now there can be no profit. Simple step story, I have understood it, okay after that look carefully, look at me two. Option: If I have to buy today, it's okay. If I have to buy today, then I can do two things, I will consider it, that is, I will tag it, I will do it right, I will actually buy it, I will not buy it, okay, so look, if I take it, I have bought it's okay. If I take it, I have bought it, then look, I will get profit from this solution, the price is ok and I have bought it today, pay attention, if I have bought it today, I have bought it, then it is the next thing, then buy 's value falls, brother, give 's value falls, brother, give 's value falls, brother, give me the next one. I can't buy it, that's why I am sending the bike related product, okay, I will get profit by solving it, okay, that means, sorry if I took it, okay, that means if I bought it today, okay, then today's Joe and his I will sell it later, this is a solution, I am calling the seller function because look, I am sending the bike man, let's buy it, sent it for ₹ 100, okay [ sent it for ₹ 100, okay [ sent it for ₹ 100, okay so so so this is sold, give the price, sorry sold. Hua will give the price that I sold this much and what is today's price, what is the buyer's price, understand the thing carefully, I have planned today that I will take today, that means I will buy today, okay, that means go ahead brother, you don't want Faridabad. You may have bought it now, otherwise why would you buy it? Okay, and when the selling price goes up, okay, then I will mine the price of the bike and take out the profit. This is the profit I got from the take. It is clear now, what do I do if not? Taken means you have not bought your stock today. It is ok. If you have not bought your stock today then it means you cannot sell it in the future. If you have not bought then what will you buy then the prices are ok, the plus van is also ok and it is ok. So brother, you have to send this as true, if you haven't bought it today then what will you do in the future, that's why I have sent the variable of the bike as true. Okay, so where will the profit come from, if you have n't bought it yet, then in the future. I will go and buy it is okay here, I have not given the mine price, brother, why should I mine it, that is, why would I write this one as mine because I have not bought it yet, the buying function is being called, it is still buying, isn't it? The function called profit is being called here, whatever profit will come from the starting take or whatever will come from not taking, the sale is either you made your sale today or you did not sell today in not sir, this can be the condition right. Okay, think of one thing, if you had sold today, how much money would you have earned, given the price of the stock today, you would have earned so much money. Okay, so much money came, after that you sold today, right? So now after this, the function call should be of buy. After sale, you ca n't buy again after the sale. Either you can't buy again after the bike. Right, if you sell, then you will call the function for buy. Okay, so look for the bike. I am recension. I am not doing it plus I am repeating, one more price for the bike is ok, if I have sold today then I can give it in the next day brother, what can't I do? During the cool down period, they have said van, it is ok so no next day. Next will have to be given, that is, by not giving the plus van, you will have to give plus tu, cool down period was ok, I will send it at the end, what do I have to do today, I have sold neither, I can do the maximum bike, meaning I can give plus tu. What do I have to do? If I want to buy a bike, I am sending the truth for the bike. It is clear till now, you are looking at every single thing, you should understand the meaning of every single line. Okay, today I made the sale, so today is the day. If you sell, how much money will you get? How much money will you have received? What will happen for the future? If you call the buy function, then this is the buy function. Okay, and if I have sold today, then I can't sell in the Plus van. That's it. It is clear, ok and by the way, we will call brother's function. If you cannot sell again after the sale, then you can do the bike, but if you have done the sale today then it is next, I cannot do anything, I will have to cool down, so give plus, you pass. I have done it and have to buy it, that's why I have sent it here, it is clear for brother, now coming to note sale is very simple, we did not buy anything today, otherwise we did not get anything, it is okay today, so it means we will be in the future also. You can sell it later. I haven't sold it yet, so how will I buy the bike again? Brother, you can't do it without selling it. If you don't sell it today, you will have to sell it later. You can buy it only after that, so this is the function of selling it. Function will be ok so de plus van will be here ok de plus van will be n and look the function of sale is calling I have to sell yet I have not made the sale ok I am repeating again see today If I have to buy then I have two options, either I buy a bike or I don't buy a bike. If I buy a bike today, then that's it. If I buy a bike today, then I just have to call the cell function. So called the selling function. For the selling function, send me the value of the bike. Okay, and sent me the van plus it. Because if I bought it today, I can buy it tomorrow. Okay, I will get it from here and I want to make a profit. Today I have bought it. Okay, so what is the price of sell mines today, then I will get profit of tech, if I buy today, how much profit will I get, okay, now it is not tech, I am not buying today, okay, if I did not buy, then it is okay. If yes, then you can buy later, so it will be a call of buying, right? There will be a call of buy only, if you buy a little without buying, then again we are not calling of sale, we are calling of bike, hence also look at the variable of bike, we have sent true here. And the plus van is fine, we will extract max profit from it. Okay, now here we come to the sale. If there was no brother then there will be the option of sister-in-law, so there are two options on the sale, option of sister-in-law, so there are two options on the sale, option of sister-in-law, so there are two options on the sale, either sell or don't sell. If you can then sell today. So today I must have got some money or the money given by the price giver must have come plus if it has been sent today then now I will have to go ahead and buy but I will buy after taking rest for a day, the golden period is yours and I have to buy that is why I have sent you True. And if I have sold the note, then today I have not sold it, so I will have to sell it. Brother, I can do a little without selling, so going ahead, I have to call the sale function. Look, I am calling sell, and if I am calling sell, then The variable force of the bike has been sent and the plus van is fine, we will extract maximum profit from it. The maximum profit is whatever money is taken from the sale or whatever is taken from the note sale. Okay, and what will we do in the end, return profit which is maximum. It will come, okay, it is clear till now and you can simply memorize it, okay, then think for yourself that the maximum value has been given, maybe 5000 has been given in the constant and bullion can have only two values, so we What will we do to memorize? We will take 501 and here we will take two. Okay, here True or False will be used for bids and for what is given here, the meaning is to memorize. We have taken memorization of as many dimensions as the variables that people are changing. We will store the value in it. It is clear till now, so what do we do? First of all, the story of recognition and memorization that we have understood till now, we convert it into code and write the code. And let's see if you pass all date in these cases, after that we will come to our concepts. Is it bottom up or bottom upruch? Okay, so let's do this first. Okay, this is a good question. Let's come to the direct code, but before that, remember. Do the state diagram that I had made, you can include the wife in it, either you can bike today or you can't do it today brother, it's okay, that state can be even bigger, so you can try it yourself, but this. Rickson is the only one who has such an intuitive approach in himself that today I either sold the bike or I didn't do it, both are the options, if I sold today I didn't do it, both are the options and if I sold today then I can't buy in the next one, cool down period. And if I sell today then in the future I can only do the same because I have sold means I do n't have the stock so you can buy then just like a conversation, a normal story, whatever we will convert into code, okay so First of all, let's call a simple function, we will keep the number as solved, we are starting from zero, okay, today I have to say bye for the variable named bye, so let's write like this, forget a = 2, now it so let's write like this, forget a = 2, now it so let's write like this, forget a = 2, now it is the first day, isn't it? On the first day you can only buy or sell a little, it is okay so buy here, you should always give a team, I have no profit, today you have to either buy and if you don't buy then you have to sell, this is the right option. Now let's take the profit value of the option as zero, okay till now it is clear, after that now let's come ahead and see in take it equal you look take means I bought today okay and if I bought today then I have to call the sell function. For the future, if I have bought today, then I have to sell in the future, it is okay. If I have to sell, then I will have to send the variable price of the bike in a de plus van because I have to sell it in the future. It is okay, and how much profit will be made if I sell today. So the selling price will be sold from here minus the price of today's purchase and it is clear till now, you are seeing very basic aunties approach, you must be understanding it line by line, what I am telling you, right, I bought it today. Today I did not buy, these are the two options: If I buy today two options: If I buy today two options: If I buy today then it will be selling and selling minus the purchase price is equal to your profit then take will be taken out and if I did not buy today then it is okay then I will have to buy in the future too. Neither will I ever have to buy, so I can't sell here. If I haven't bought today, then going forward, I mean, if I haven't bought today, what will I sell next? I don't have anything, so I wo n't call the function of selling. Now whose function will we cover? Will cover only the function of buy because today I have not bought. Okay, so here is the bike. Okay, so buy the plus van. Okay, the variable of the bike is okay. If you are buying, then if you are buying, then there is profit here. A little profit will be made here, why would you look at the mine price, now you are buying only, then sell mine, it equals your profit, here we have still called the function of the bike only, so this is just buying only, isn't it here? Till is clear and if A's variable is false, meaning we will talk about sale, then what option do I have, I am fine by selling or else I am fine by not selling, and if here the profit is then updated, profit is equal to max of what? What will be the value of profit? What will be the value of take? This is clear. After this, let's come here, did you sell? Look, if you sold, you would have got some money today. Prices of will get money today. Now buy me. Right, now that I have made the sale, I have to buy it, so I will call the function of the bike. After the sale, I can make some sales, I am calling, but today I have made the sale, so I will take rest in the next day, there is a cool down period. So give plus van, don't give plus you, I can buy. Okay, if I do it to buy, if you have n't sold now, you will have to sell later. Okay, so if you sell later, then today you have some money. It will not come, if you make a sale then it will be zero. Today's money is not written as zero plus, it is removed. If I do not make a sale today, I will have to make a sale later also. Pay attention, I will have to make a sale only in A Plus van. Right and if the sale is made then it will be zero. If you want to do this then you will have to send the value of the bike. It is clear here, see, we have not done anything actually, we have just written the story here, did not buy, did not sell, okay and just calculate the profit here, profit is equal to maximum profit. If I get it, I will send the returns profit maximum. Okay, now what do we do? Let's submit it in advance and see. No, let's run the example discus first and see whether we are passing or not. Okay, now let's submit and see. Most likely, time limiting seat will come. Ok give how much can it be 5000 can be given in constunt Ok so 5000 let's take one call it five thousand one and one is a variable it can have only two values True or it can have only two values True or it can have only two values True or False is fine and as usual we The memorization that we are waiting for is here, let's initialize it by setting it as t - let's initialize it by setting it as t - let's initialize it by setting it as t - 1, size of t is okay, mines van dal is given, okay and now let's initialize here for memorization that if of the is given and Okay, for this speaking variable, bye will be zero, we will store it here, okay, let's run it, copy paste it once, run it and see let's see now I should pass, after that we will see by submitting. Great passed, let's submit our notification, sorry, now we come to our next approach, date is bottom up approach, okay, look, now we will do the bottom approach, so before that, answer some things, first of all, okay, I am here, I have to I am here, okay, I am here, I have to sell on the day of my arrival, so what do I know, today is the day for sure, I must have bought it some day, that is why I am selling today, okay so one Let's reduce J = 0 to I, so I am selling, okay till this point I will neither find the best price nor will I find the best price so that I can get maximum profit by selling today. So the time is right, that means I will stay at any I, okay then what will I do, I will check J=buying price so that I can check J=buying price so that I can check J=buying price so that I can get maximum profit by selling today, this thing must have been cleared, it means there is a lot of gravity, now that's it. If you have to sell today, then don't think that this is the best buying price ever in the past, according to this, I should get maximum profit by selling today, this is a very genuine thing, okay, this thing is clear man. Let's take, okay, tell me one thing, like I take T is not one, I have taken a vector whose state has something to define, if I want, then let's see what I will define, okay, this is equal, you are maximum profit, maximum total. I have given the profit till it is ok, I have got the profit, ok, if I can get out the question in profit, that will be my answer, is n't it ok, how many total mines van do we have, ok, now any person asks me, brother, if you can tell me the maximum profit till secondary. Please show me the maximum profit till one second, then zero off, you tell me and I will send it, that will be my answer, okay, so I have defined the state, brother, what will happen to me, Tuffy, what is the maximum profit, total profit till the end of the eye, this is okay. It must be clear right now, till now we are not doing anything, till now we are understanding some of the points ok, and everyone knows the profit formula. Hey brother, what is the profit? I have to sell on the day of I, so the price of selling was mine, that would be it, isn't it? Everyone knows this formula, right, this is how I will earn money on that day, I have saved it like this. I bought it during the day, I am selling it, and I bought it during the winning day, okay, but I want total profit in my tee, I do n't want that, okay, so think like this, what will happen to me, first, I have taken the profit, best byte, this one, this profit, this one. So if the profit is made, then the previous profit is the total maximum profit. I don't want the total. No brother, I don't want to worry a little. Come on, I sold and bought today. It was a great surprise in the first day, so the profit has not come out. So, it was taken out, that's fine. So, you have withdrawn one day each of this and that, the rest of the previous ones, what about the less profit that came, what do you take? If you chose this one, then you have withdrawn the profit. Okay, this day's price of J was this much and on this day the selling was If the price was this much, then it is okay, then the prices are off. I have taken out my own profit, but this previous one is perfect. What about it? We need the total profit. Okay, so this profit has been taken out. It is okay, but the previous profit taken out will also have to be added. That is, the profit of the first one is ok, we will add the profit to the total maximum profit, maximum total profit and ok, the maximum profit of I is not the total profit untilildehyde, we are talking about total profit, ok, so it is clear that brother, something like this. We will have to reduce it, okay, so now listen to one thing, pay attention, this is a very important thing, very good Jai, I chose that day, I rode a bike, pay attention, okay, so tell me one thing, can I ride a bike in the mines van or not? I could correct one thing, I came to know about it, I must not have done it right, is n't it? It was the golden period, so I can't even sell my van, so what is the last option we have, okay? And on that day, I bought the bike. I have done it from the office, I cannot sell because I have a gap of one day, so I cannot sell for sure, it must be the golden period, I will add the mines, the previous total profit is fine for the previous one. If the total profit and the profit of what I sold today came, then the total of the rectangle has been found. Look, I am writing again about today's day, the amount of profit I want is ok, how much profit would have been made, ok, so see, I am writing about today's in Hindi. The profit of selling will be the profit of today's sending. I have sold the prices of today. This is mine. Sale Mines B. Okay, this is today's profit of selling. But we want the full profit. T means what is the total profit? So I have calculated today's date and I have calculated the price, but I must have also required the previous ones as well, so here the total profit till the first T and how the total profit is calculated from the T to the T, we are making noise in the total. I had made the profit till the tee off, I have mine, you will do it and why I told you that there will be only ups and downs on that day, neither can I sell it nor can I buy it because I have made a brother in the K. Don't see here, I must have done this buy of prices off, so I have taken out the maximum profit till the first one, this one hit the mines again i.e. no profit, hit the mines again i.e. no profit, hit the mines again i.e. no profit, I have taken out the profit from the next one till the first one, this is the maximum profit. No, this is my profit from today's sale, what was the price of I - Price of is fine, I what was the price of I - Price of is fine, I what was the price of I - Price of is fine, I think this diagram is very good, I just paid attention to this diagram, this one is quite good, this one which I have written, see it, zero. How did I calculate the total profit from DJ-2? So come on, hit it, How did I calculate the total profit from DJ-2? So come on, hit it, How did I calculate the total profit from DJ-2? So come on, hit it, there is no profit and I calculated the profit that was to be made from K to I. The price is right and how would I have chosen this one, I will find it by looping it. It will be the best jeans which can give me the best answer. Okay, this is clear, so keeping all these stories in mind, if you look at the code, then see what the code will be. Okay, tell me one thing brother, it will be zero because you You have to buy it one day, you don't have stock, you have to send it, from there the first day's obese profit will be zero, the total profit will be zero, okay tell me one thing, think how much profit will be there in the second day i.e. t1, tell me one thing, think how much profit will be there in the second day i.e. t1, take two elements. That's four and one, okay, so what can be the meaning of t1, so let's take it that you rode the bike on this day, one and sold it on one day, then the profit is three, that is, the prices of one minus the price of zero, okay, and where If there are four and one, then it is okay, so I will buy it on the first day. I bought it on the second day. If there are four and one, okay, then what will happen, then what is the maximum that is free, then it will either be zero or zero because I have stock. No Okay, so it was understood that brother, it was easy for Zero and Van to get out, it was given to me at t0 t1, I was getting out from you for I = 2 I = 2 I = 2 Okay - 1 What I said that we will find a very good variable. Which is from zero to end mines one and I will choose the best one which will give me maximum profit. Okay, so first let's find out the previous profit, how will it be written - Prices profit is the previous profit. Do you remember what I said? Again we forgive, total profit is required for T, so the previous profit is here, I have taken it out in TFJ, it is fine but there is a problem here, man J-2 is not there, if the value of key is man J-2 is not there, if the value of key is man J-2 is not there, if the value of key is zero or van then index. It will be out of bounds, so give a simple check here or remove it, take this check of bounds, if it is equal then give it greater, if you are equal, then it is ok, otherwise then we will give zero, there is no profit. Okay, this is clear till now, this is also clear, our four loop is over, what will we return in the last, T and N are - 1, right, this is the question asked, T and N are - 1, right, this is the question asked, T and N are - 1, right, this is the question asked, how much less total profit will you get till the end, maximum is this. Lastly, we will send our ton-fun. Okay, we will send our ton-fun. Okay, we will send our ton-fun. Okay, now see what we have to extract, right here in this loop, I will extract, so right now the value of T is not there, it is starting from T-1, it will be updated later. Ok, T-1, it will be updated later. Ok, T-1, it will be updated later. Ok, later updates will be made here, ok and here at last we will return ok, look brother, the story is the same, isn't it, what is the story, brother, I am choosing the best for each eye, I am selling it in this day. I am okay, so I am choosing the best one, I am searching from here, what is the best thing to do, let's code this example, it is okay, so let's do our bottom approach also, okay, first of all you can write this That if N is my zero or if N is my one, then now I cannot make any profit, nor can I earn any profit, I have given only one day, so I have not given that day, okay and let's make it. Let's take our vector of end ton 0 ok total max total profit end oil is clear means brother there can be no profit and t1 what is my maximum of prices of van means from the selling price on the first day and from zero on the pay day I had bought it Isn't it prices of zero or brother, keep it zero, don't go negative. The maximum of both is right for me. I am planning to sell today. Let's take it. I am planning to sell today nearby. I would have bought as many as I would have chosen. Okay, for now let's keep the value of T of I at 5 - 1. Okay, for 5 - 1. Okay, for 5 - 1. Okay, for now because we don't know what the maximum will be, let's choose the best for and give this equal to zero gel less. Equal tu what will happen i-1 just before i and k plus happen i-1 just before i and k plus happen i-1 just before i and k plus is ok till now it is clear, after this what did i say how will tf5 come out, what will happen tf5 come out, how will tf5 come out, what will happen after that today's profit is ok, let's not define like this. If I do it today, I am riding a bike, there is a cool down period, or else I can't do it because I am riding a bike, so my van must have been cool down for sure, right, it is clear till now. It's done, that's why when can I write it, when it's greater, give equal, you are the same, then no, then we will make it zero, pro profit is ok Great, I have this question, I have passed all the details cases, it is ok, off n², it is ok. The time complexity of n² is ok and remember what will be the time compression of the recognition person. At every point you have two options, either you are selling, you are not selling, or you are buying, or you are not. If you are doing it, then come every for every, I have given you have two options, neither will you have power and time complexity, nor will you have forum time complexity, and if I have done it, then okay but sorry, ours is fine. This is because we will not solve one state multiple times. Okay, so I hope you have understood. We just converted the story into code. Nothing else. Okay, if there is any doubt, comment section and tree will help you. Gas and next. video thank you
|
Best Time to Buy and Sell Stock with Cooldown
|
best-time-to-buy-and-sell-stock-with-cooldown
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
121,122
|
830 |
Hello, today we will solve a simple problem of position 8, position 10, and there is no sub yet. What we are given in this problem is a string consisting of only lowercase letters, except for the word Es. In this string, consecutive characters like this are the same character. It's a problem of finding something that appears. There's a way to distinguish the position of these consecutive characters from before the start to the end. If you look at this string, it has very similar characteristics to an array. Strings and arrays have a similar look. For example, i. The second problem is that in the draft of the string, the station called i is an index and can be accessed in the same way. So, for example, the string e xxx has an interval starting from 0, so in a society where it is 0 or more, there are 4 and 6 types from 3 to 6. It is a problem that consists of 4 problems. So, this group is called ji when the number of letters contained in these intervals is 3 or more. Pillow or more, 2 10 Starting from the index, it gets bigger. In order, these 3 or more are all interns. Now, let's do the meter. If you look at it here, if there are more than 3, there are only xxxx, so it came out as two 36. Is the third example lowered a little by 5? In the case of the third room, it is more than this world, but there is dtd. There is e, and then there is BB. When starting from 0 in the 3rd place, it is zero, so then 3 4 5. And for that reason, it becomes 1 2 3 4 6 7 8 9 e. This mt and 10 11 have the value of a outside. Since there is no father in the past, there are now 13 14, so there are 3, so the 3rd EP group will come out like this. In this case, simply go straight from the front, and if the same letter appears, fill in the interval like this, There is a possibility that our child will become Large. And when another text appears, ok, where did this text start in the beginning? When I leave in the evening, I try to use the starting point principle. When I paid, I said Ka. After that, uh, there was 3 lb of sting here, but the social welfare was low and I was out. I'm trying to raise it. I'm taking 3 shots, and then the 6th sixth one is sitting right in front of me without any use. Then, I go in front of them and write a few letters g. Then, when I go to the current 6, the pointer goes like this. If I subtract the start p key from the 3 I was digging, it becomes 3. Well, then you can see that he's probably still right. I'm going to solve it that way. Just think about it. Well, then you can think about it as if you could ride the government's number 1 hole from start to finish. 5 First, the tattoo is 0. He's also cocked. Oil from a 0 The child will go from work 5 and now the ii series so far will be like this, and if xi bar si - and it are different, si - and it are different, si - and it are different, then the dessert that was watched will occur. That is, it started from 0 earlier, but since it was operated by the first musician, it started from the wall and when it went to the first job, the way to know the length like this is that the i-th starting point has to be that the i-th starting point has to be that the i-th starting point has to be greater than 3. You do it all. If it's more like me than others, ah, tco to i miei, because it's made up of the same things up to that point. And since it's not the same now, you start anew from the beginning. 4 to live a to z, and if it's the same, do nothing and keep going. So you can move on to the next step. But here, think about it one last time. If you think about the last case, then you are now looking at the area. When you look at this place, you are looking at the area in front and it continues to be the same. If you think about it, let's ask and it ends at the back here. When you look at the last letter here, the e does not fit inside, so we don't do this interval. So, in order to order the last one, the children were the same. If the child goes last, then we have to check this again for the same thing. It works like this. 4 At this time, the child above was the first one in front of the feet, but the last one is swearing. When it is said that it ends with the entrance exam, it is like a carp peo, so the way to count them starts and this is where 20 24 is fasting. It's 10 people. So, plus work. Now, if Blas is bigger or the same, this time, include this letter. Ah, so you've done it up to this point. You can do it like this. Then, I'll think about it as a third case to see if this fits well. The third case is Jo Saeng Bright. First of all, I brought pin 10 here, which is used for solvents. So, erase it and when the child is 1, it is si. When the child is 1, it is si and si - isn't a and b. Right, so I and si - isn't a and b. Right, so I and si - isn't a and b. Right, so I put it on here, so this is not the same. If I don't have it is gy at this time. Let's get the rail. The start is research. Then, wouldn't 0 - 1 - 0 be research. Then, wouldn't 0 - 1 - 0 be research. Then, wouldn't 0 - 1 - 0 be greater than or better than true? Without going to m, the start on this line will be number 1. It became work, and we go back all the way again, and then the child became e. Ah, it became an image. When I found out about this, I looked at the PC like this and it is not the same again. I don't have it and here e100 work is not greater than 3, so at this time too, the starting point age would be different. It changed to 2. At 4 o'clock and it became 3. Zero or more became 3. But at this time, it's not the same because it's the place where b and c are dia. It's not the same, but just like that, the blood pressure restart has become ii. So, since it's not bigger or the same as this 3 - life, let's ii. So, since it's not bigger or the same as this 3 - life, let's ii. So, since it's not bigger or the same as this 3 - life, let's just move on here and start again with 3. It's easy and the child was 4. Since it's around the Nigasa area, it's like Diago to, so it's the same, so I'm going to skip it, and the kid is going to go to 5, and when I go to 5, I'll hit the nipple, so I'll just skip it. It's currently star 1003. Then, after that. When the child gets an organic college education again, it becomes this. Ah, it has finally changed. Then, the 2nd child of childcare high school is subtracted from the 6th day, and then on the 5th day, it is deprived because it was behind. It is different, but at this time, the child is 629. At this time, the start is 3. So, it goes here for the first time. The start is 3, and then the second is hit. My child is like this. 600 Name 5. This is how one message is added. It was added. Then, did you tell me to add it and change the start? Start It was abandoned and then we move on. Darts are talked about and it becomes 7. When the enemy gets hemorrhoids, it goes again to 2u and 7 is the same as No. 1. Go ahead and sleep. The child goes to Paris and becomes 9. It was the same as the road of the section. It became 12. 11 sc minutes became A. Then, when it becomes 12, it understands the 11 vs. You can say it depends. 6 7 8 9 So Dragon or 6 became Google, which is i - 1. became Google, which is i - 1. became Google, which is i - 1. And at this time, the start again becomes a thread. To start, when the child is 10 days old and the child is 11 days old. It's the same, so we go back to the last one and when the child becomes ce, it's raining, so this time, it's different from B. The start changes again to 12. It changes to rain, and up and out. After that, 10 cheap butlers are all the same, so they called it 15. When it becomes Chibo, this is where it became Mr. I became it. Do you have the same blood as Jasi? When I compared it, no, it was different. Then 15 - Shibi. Because it is bigger than or equal to the island, Then 15 - Shibi. Because it is bigger than or equal to the island, this is managed from the house here to the 14 that becomes the i - here. this is managed from the house here to the 14 that becomes the i - here. this is managed from the house here to the 14 that becomes the i - here. Add it and then go over again, and my child started at 10, and so on, and 15 was here. Next, we move on to the next 16:00, and next 16:00, and next 16:00, and even if we go past 16, the kids are still different, i - is the start, and it's not greater than or equal to 3, so we go over to the - is the start, and it's not greater than or equal to 3, so we go over to the - is the start, and it's not greater than or equal to 3, so we go over to the head, and I'm out of there, and the dessert is 10g of tea that will return to this world. You 'll try it like this again. It was a simple problem left to try and in this case, 8 complex hitting Chan Complex Jing. Have we ever been to a pro since 5? It will be the cause. Oh, Como will be the story. And the space complex touch is the result of using more here l I Resort Except for you, I made a starting point, and since then, I wrote Buddha Dry 1, so there are 5 volumes of EP. In the female character, today I solved simple problem 8, 130 Positions Up, while I am still in the group.
|
Positions of Large Groups
|
largest-triangle-area
|
In a string `s` of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like `s = "abbxxxxzyy "` has the groups `"a "`, `"bb "`, `"xxxx "`, `"z "`, and `"yy "`.
A group is identified by an interval `[start, end]`, where `start` and `end` denote the start and end indices (inclusive) of the group. In the above example, `"xxxx "` has the interval `[3,6]`.
A group is considered **large** if it has 3 or more characters.
Return _the intervals of every **large** group sorted in **increasing order by start index**_.
**Example 1:**
**Input:** s = "abbxxxxzzy "
**Output:** \[\[3,6\]\]
**Explanation:** `"xxxx " is the only` large group with start index 3 and end index 6.
**Example 2:**
**Input:** s = "abc "
**Output:** \[\]
**Explanation:** We have groups "a ", "b ", and "c ", none of which are large groups.
**Example 3:**
**Input:** s = "abcdddeeeeaabbbcd "
**Output:** \[\[3,5\],\[6,9\],\[12,14\]\]
**Explanation:** The large groups are "ddd ", "eeee ", and "bbb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` contains lowercase English letters only.
| null |
Array,Math,Geometry
|
Easy
|
1018
|
1,512 |
hello guys and welcome back to the video so today we look at the problem name number of good pairs so given the array here you have to find a good pair which is when your number is equal and the index is i less than j for example this one when you look through the array one two three four this one is equal right and the index is zero and this one index is three so you get the first one here and the next one is zero and four and you get this one and then zero one two three and four which is this pair and then the last one is this one you know this one and this one so we have to write a function that return the total number of pairs okay we have to write a function to return number of pair i use python here python 3. i think one thing that we have to do for sure is look through the array so to remember the number that we pass by should be a hash map and we call dictionary here i think um let me call it mighty okay and number one start by zero and then we start look through the number four if the number is already in our dictionary if none is in my then we can add the number i think we can count if we pass if you can't pass this we out we add this one with the number one as we pass this is for the first time so it will be like this when we pass one we have one and when we pass two we have two one and then we have we pass three one and so on for the second time we pass one we have this one is two like this so if number in my dictionary i will and okay this one passed by uh the dictionary okay with the num and then i also add the number to the dictionary then my dictionary at the number num equal to this one just by one okay if it's not in the dictionary so but i have to add it plus one and then okay so with this i think we can try to run the code ah this one set it to one okay try one call it accepted and try something yeah there you go it's done thank you so much for watching please like and subscribe see you next time
|
Number of Good Pairs
|
design-underground-system
|
Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nums = \[1,1,1,1\]
**Output:** 6
**Explanation:** Each pair in the array are _good_.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
|
Hash Table,String,Design
|
Medium
|
2285
|
1,685 |
So Hello Friends Welcome Back In This Video Here In This Channel Equal In Solid Appeared In The Weekly Contact Problem To Anil Zinc Voice Mail Third 400 The Problem Is States Of Water Harvesting And Are Presented In This Feeling Order Which Means That Deposited In Increasing Oil Import Skin Every Possibility of Increasing Element and Witch Can Also People What They Need to States Sexual Subject Patient and Subscribe Differences Between Tits set2 Result 10th How to Find the First Element's Army Space Elements Who Travel Tips Capsule Difference of Element Right Here From All The Elements Which Means Every Delhite WhatsApp Twitter - Two Mod Means Delhite WhatsApp Twitter - Two Mod Means Delhite WhatsApp Twitter - Two Mod Means Aptitude Difference Plus Thee - Two Plus 5 - Aptitude Difference Plus Thee - Two Plus 5 - Aptitude Difference Plus Thee - Two Plus 5 - 2 180 Is The Its Water Level Chakhyou Lucent Element A Volume C The Element At Index 1872 Apps Unmute Differences With Every If Element Of This Year And By This Is Need To Optimize Your Answer Is No Evidence Which Is Clearly Visible To That Log In Why Not Today Clearly See Diary To Do Nothing But Every Step Of Issues Notice I'm On To Three 500 * Know The Cat I Need To On To Three 500 * Know The Cat I Need To On To Three 500 * Know The Cat I Need To States From Fear From Hair Soft First Step Chakri It's Okay What Is The Means A What Is The Whole Subscribe Now To Do Subscribe - Number Three Love You To You The Subscribe - Number Three Love You To You The Subscribe - Number Three Love You To You The Four Sweater First Year Committees' Four Sweater First Year Committees' Four Sweater First Year Committees' It's Right Approach That's When Going Gets Tough But Iron For UP Boond Si In This Means This - Number 323 e-1 More Notice for Means This - Number 323 e-1 More Notice for Means This - Number 323 e-1 More Notice for Not Giving and subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to the Listen Time To Which Thing Which S2 - Stree Luhaach Time To Which Thing Which S2 - Stree Luhaach Time To Which Thing Which S2 - Stree Luhaach Relative One But In Yaar Answer You're Doing These Simple Settings - Mark and Side Effects That When You're Going Wrong Simple Settings - Mark and Side Effects That When You're Going Wrong 10 Simple Sea Portal Festival Witch Mince Of Wave World Nude Art For Any Random Elements Element Three Private Limited No Smoke Hair Wedding Six Pack White Limited Validity I Don't Know What All Is The Sum Of The Lift Voice System After White Part Cut Arrived Also Know How Much Element Side Production Right So It Is It According To Number Plates The Only Festival Admin Se Zor 12345 10 Second Experts Clear The Number Elements Which Sport Her Too Number Elements Of The Record Nothing But An - Elements Of The Record Nothing But An - Elements Of The Record Nothing But An - I Minus Point In The World 12345 - If Else But Two Minus Point Which Is Nothing But 12345 - If Else But Two Minus Point Which Is Nothing But 12345 - If Else But Two Minus Point Which Is Nothing But 59722 Sohan Mohan Bhagwat Element That You Need To Major Events Before And Definition Of Do n't Thing Which Need To Know What Is The Sum Of Life What Is Group The White Part 9 And System Tis S Manya Benefits You Dare I Will Clear Dad Ok My Jaan All Nothing But Aa To * Ego My Jaan All Nothing But Aa To * Ego My Jaan All Nothing But Aa To * Ego 5 - Direct Tweet Mode For Ss And 5 - Direct Tweet Mode For Ss And 5 - Direct Tweet Mode For Ss And Vikas Avatar My Elements Mode 100 The Video Then Subscribe To My Is Number 9483 To In To-Do List Subscribe To In To-Do List Subscribe To In To-Do List Subscribe Refine OK How Many Values With A Single Refine OK How Many Values With A Single Refine OK How Many Values With A Single Act Shall Result Into Every Element Will Find Some For Every Time Simply A Whole Subscribe Now Kin Saun Hadf 1969 Ab Suhaag Sita Mummy Ne Is To Find This Samrat Which Means Of 125 Was Committed To One If were but white part white this after suffix and prefix all but simple banaras honi sufficient quantity proverb gesture inverter hi play list this affair system them arrest loot this three layer then know it is from 6 weeks unwanted walking from tongue tweet ego near 250's entry 370 Life is nothing but free Which is the distance and subscribe Park is simply Double monthly traction Under shift My heart Every now and then Day That's right something but SIM - The element which this SIM - The element which this SIM - The element which this sacrifice has been clearly seen The British hum for this website Induction motor estimates were Is This Suhave Simply Do It Is My Sum - May Suhave Simply Do It Is My Sum - May Suhave Simply Do It Is My Sum - May Deficit Its Add To Which Is The White Part In Forward Nothing But This That By 501 We Proper Intuition And Logic Obligations How His Old And Have Been Reduced Quantity Preserve And Pretty Simple Siddhartha first flight person of the whole for knowledge are tied up with answers for final answer is what is the number my this chakra is nothing but amazing subscribe to all the subscribe this Video then the pics of independent ko vidro no adi simply run Lutaaye The Situation Will Simply Want Every Element For The Subscribe My Bhavya Meaning - Sexual Dimri Ne Subscribe 556 Now Check This Remedy The Thing But - Set 556 Now Check This Remedy The Thing But - Set 556 Now Check This Remedy The Thing But - Set Number Of Lucian Freud Ne Hai To Admin Nothing But A Sum Of Elements In The Sum Of The Answer From Right Side Hard Notification Works Marial See The Series Presents Nothing Which Element * - BF Subscribe Answers Element * - BF Subscribe Answers Element * - BF Subscribe Answers From Laptop To A Bright And Thus After Every Actor Will Simply Do One More Thing But I Will Add Deficit At Every Step And Increasing Maze Pe 1067 According To Pushpa Answer Tractor 60 Its Answer For This Element Id Result Subscribe International Logic And 86 Strong And How Can Improve Modified And Subscribe Tweet How Can You Speak Concept Of Subscribe To Special Is Dam Toot Like Button Tears Drowned Person Padi Main Hai
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
1,312 |
hey so welcome back and there's another daily code problem so today it was a dynamic programming one and it's called minimum insertion steps to make a string pound drone and it's a harder level problem and so what you're given here is a string s it just has some number of characters and so once again you just want to determine what is the minimum so it's a minimization problem of insertions and assertion is just inserting any character at any index of the string in order to make it a palindrome and a pound drum well this is an example right here because it takes zero insertions to do it and that's when you read it forwards or if you read it backwards it kind of reads it the same way so it's like zzaz or if you read backwards zza ZZ right and so this one here if you read it forwards and backwards it reads differently as well although the first two letters here are kind of mirrored the m but then B and D don't match each other and then a so you would have to insert at least two letters to make it either of these cases here okay and so let's go ahead and do this so what I'm going to give you is a top-down recursive solution top-down recursive solution top-down recursive solution and it will be o of n like squared time um like uh that and then also the same thing for space because it's going to be top down and so the recursive stack is going to take the same number of space you can do it like a bottom-up approach you can do it like a bottom-up approach you can do it like a bottom-up approach with a space optimization so it's only ovent time but for me this one was a lot more intuitive um and I'm just kind of Simply practicing top down minimization for now um and then when I get better I'll move on to the bottom up approaches so yeah so what we're going to do is Define a function called DP and we're going to have a left and right pointer and that's going to just imitate us having a two-pointer technique when us having a two-pointer technique when us having a two-pointer technique when starting on the far left one starting on the far right okay and so we're going to want to return the result of this recursive function inserting at index 0 and then the end of this string here great and so we want to catch this result and that's the minimization part so that we can get the result of this Dynamic program problem if we already solved it before and of one time and so we have our base case here base case and then we have two other cases that we want to consider case one and case two and so the base case is okay we know that refinished processing this and we're going to have these two pointers kind of move inwards when the left pointer hops over the right pointer and the left pointer is now like larger than the right pointer so to do that all you have to say is okay if the left pointer is greater than or equal to the right pointer then let's just return zero in this case because naturally this doesn't count as an insertion step as you've finished and so then from here what we're going to do is say okay if our let's see here if we want to bring it inwards so there's two cases where the left and right Corners have the same value or if they don't so case one is if s at L like the letter at index at the left index is equal to the letter at the right index so if left and right pointers share the same letter I think have the same letters better word for it so SNL is equal to S at r and so in this case we just want to return the result of a another recursive call but we're just going to bring these inwards and that's because if they're the same then we don't have to make any insertion step because the letters match and we can just say okay why don't we just continue going inwards because we don't need to consider any insertions at this step right and so let's just go ahead and increment the left pointer by one and then decrement the right pointer because the right pointer is going inwards all right and so that just says okay let's continue on we don't need to add anything because they're the same letter otherwise we know that they're not the same letter and so I guess this is like an else if Case to this if um but typically I like the base case as an f and then these two cases if and else if so case two is if left and right pointers don't point to the same letter don't have the same letter okay and so in that case this is otherwise we want to return one plus and we're adding one in this case because we want to consider that we're actually inserting at this step so one of these letters like we need to add an extra letter in order to make it symmetrical in order to mirror it right and so that's this case where you can see here because we have this extra D we need to insert a letter D on the left side here right before this b or we could put the letter d um after the B if you wanted but yeah so in that case let's just add one here and then we want to return the minimum because it's a minimization problem of two recursive calls the first one is a call with incrementing the left pointer inwards one step and keeping the right pointer the same and then we can do the opposite where we keep the left pointer the same and we decrement our right pointer let's go ahead and run that and accept it so just to reiterate what this all does is we are starting with the left pointer at the beginning of the string the right pointer at the end of the string if they kind of cross each other that means that we finish processing the whole string and we can just return zero because we didn't have to insert anything at that step if they're the same then let's just bring those pointers in we don't need to add anything because we haven't needed to insert they're symmetrical otherwise if they're not symmetrical we need to add some extra letter we just add one we don't have to insert or anything we just need to increment the number of insertions that we had to do and then because there's two possible paths that we can go down we can we want to take the minimum of those two paths which is incrementing the left pointer by one or decrementing the right pointer by one and that's the solution so yeah I hope that explanation helped and good off with the rest your algorithms thanks for watching
|
Minimum Insertion Steps to Make a String Palindrome
|
count-artifacts-that-can-be-extracted
|
Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zzazz " is already palindrome we do not need any insertions.
**Example 2:**
**Input:** s = "mbadm "
**Output:** 2
**Explanation:** String can be "mbdadbm " or "mdbabdm ".
**Example 3:**
**Input:** s = "leetcode "
**Output:** 5
**Explanation:** Inserting 5 characters the string becomes "leetcodocteel ".
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
|
Array,Hash Table,Simulation
|
Medium
|
221
|
86 |
hello everyone welcome to coders camp and today we are the 14th day of april lead code challenge and the problem we are going to cover is partition list so the input given here is a head of a linked list and an integer variable x where x point at the partition of the linked list we have to arrange the elements in such a way that the notes less than x come before the notes greater than or equal to x and we have to preserve the original relative order of the nodes in the each of the two partition so let's understand this problem with an example so here is our given input list and the partition element is 3 so now we have to arrange the list in such a way that the elements less than 3 in the second half of the list should be moved to the first half of the list so if you observe in the second half of the list that is after 3 the elements less than 3 are going to be 2 and 2. so now if we are shifting 2 to the first half of the list then they come before 4 so now if you see the list is gonna become this that is all two twos came before four and then three and then finally five which is greater than three so here we have to maintain the relative order so what is the relative order if suppose the elements are going to be two and one here in the list and if we are moving them to before the list then it should come to n1 because we should maintain the relative order we should not swap the notes or reorder the note so now how are we going to approach this problem so we are going to have two pointers or two dummy heads small and large where small is gonna point at the elements which has to come before that is first half of the list and large pointer is gonna point at the elements or notes which are going to come in the second half of the list and finally merge those two headers and return the result so now let's have green color for small pointer so i am going to point at the elements which are less than three with green so now starting from the first element which is one which is going to be less than three so that comes under the small part so we are going to point our small pointer at one and now our pointer small is going to be at the node 1. moving to our next node which has the value 4 which is greater than 3 so we are going to have a point of purple that is large pointing at 4. so now it's time to move to the next element which is 3 we are going to again have that element in large because we are going to maintain large or equal in the large pointer so now from 4 dot next 0.23 so moving on to the next 0.23 so moving on to the next 0.23 so moving on to the next node which is 2 which is less than 3 so it comes under the small category so we are going to point our one dot next that is right now it is the small dot next to 2 and now small becomes 2 and same way large moves to 3 so now next element 5 which comes under the last category so now our last pointer that is large dirt next is going to connect to 5 and large moves to 5. the next element is 2 and 2 comes into the small category so we are going to point s to 2 now that is current s dot next to 2 then we are going to point s2 2. so now our iteration is completed that we have i traded through all the nodes given in the list so now our small pointer ends at the smallest element and large pointer ends at the large element so now wherever the large pointer is that is going to be the last element of the list so we found the last element of the list so we are going to connect null with that so the next to large is going to be null because that is the end of the list so now our small element is at 2 we are going to connect our small with large dot head so we're going to have a dummy pointer at large where it has started so we are going to connect small too large so that now the list is sorted in such a way that all small elements comes in the front and all large elements go to the back so hope you are understanding the solution so this is gonna happen in one pass that is it is gonna iterate through our given list only once so this is gonna run in big o of n time complexity and constant space so let's go to the code now so first i'm gonna have two dummy pointers head one and head two and i'm gonna declare my small and large to head one and head so to iterate the given list i am gonna have a pointer current which is gonna iterate through our given list so now i am gonna iterate till my current node reaches the end of the list then i'm gonna check every value or every nodes value in the list whether it is less than x or not so if it is less than x then we are going to point that to the small category so small dot next will point at the current element and now small moves to the current element if not if it is not less than x then we are going to point the large pointer there so yes so for every iteration current is going to move to the next node so that it will light right through the list completely so yes everything is done so now we are going to point large dot next to null since it is the end of the node or end of the list and small dot next is equal to head 2 dot next where we have assigned head 2 to large so this is actually going to point at the first node in the large list and finally written head one dot list that is small where the small is starting as the first node of small is going to be minus 1 from the next node it is going to be the actual output we need so let's submit now yes a solution is accepted and it runs in 0 milliseconds so thanks for watching the video if you like the video hit like and subscribe thank you
|
Partition List
|
partition-list
|
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`.
You should **preserve** the original relative order of the nodes in each of the two partitions.
**Example 1:**
**Input:** head = \[1,4,3,2,5,2\], x = 3
**Output:** \[1,2,2,4,3,5\]
**Example 2:**
**Input:** head = \[2,1\], x = 2
**Output:** \[1,2\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 200]`.
* `-100 <= Node.val <= 100`
* `-200 <= x <= 200`
| null |
Linked List,Two Pointers
|
Medium
|
2265
|
5 |
so i'm going to show you an easy way to solve this little problem that says the longest palindromic substring so given a string s return the longest palindromic substring in a so the easy way to solve it of course there are different ways uh the easier most the easiest most efficient way to solve it is use is to use the two point terminals so the two pointer method actually uh you can also use this to point our method in two ways so let's take the simplest method for example so the first method says have a function a helper function that is called is palindrome so this helper function here is going to return true if a string is palindrome and return false if it's not a palindrome okay now what we are going to do with the original string is that they are going to start from index one here and then check the first two items so you're gonna check ba and check is palindrome no it's not palindrome i am going to move to the next one b a b and check his palindrome yes so i got to now stall the length so far so let's call the length so far to be three and the string so far to be b a b okay so the at the next iteration we're going to move to the next one which is b a is it a palindrome no and then we don't and then we complete it and then we move to the next one which is a we are going to check a b a this is the palindrome yes but we are going to check if that palindrome is greater than the longest so far is not so we don't worry about this and then we are continuing all the way to the end so this iteration going here is going to take order of ends quite time because we are going to check for each of the items we are going to check all the other items and this is going to be our worst case scenario we are going to start from here and check everything for each of them so and this function here is going to take order of n times so if you put them together it's going to be order of uh n cube time so it's going to be the complexity is going to be n cube and if you are in an interview you recognize that this is not very good to have a performance of n cube so how do we do better than this so the method we can use to do beta is to use um is to check for is palindrome for each of them for each of the letters so it means that for b we are going to check if he's palindrome and for a we are going to check if his palindrome on based on the item surrounding it so which means that for b we are going to check if he's palindrome for a we are going to check the item before it that is we are going to check a we're going to check b a b that is in case of a okay so in case of b here we're going to check b a b in case of uh b here we are going to check b a d so you have this middle so what are we saying what we are saying in effect is that for each item for instance b here this very item here we are going to check the items on both sides of uh of these items so for two in we have an index like an index right so for instance if we have this if we put indexes on them we have zero one two three four and b is an index two for instance so assuming i is two in this case and we're going to start a left index of two which is going to be i minus 1 this is going to be the left index and it's going to give us 1 and we are going to have a right index which is going to be i plus 1 and that's going to give us three right so it means that we are going to start from here and go outwards from that very item checking whether the both items match so if they match then we know it's a palindrome so in that way we are going to reduce the time to order of n squared time because for each item we are going to use two iterators or two pointers to move uh in the same time in two different directions in order of end time so combining it with the uh the iteration going from beginning to end so that's going to give us only order of n squared time and i think that is way better than order of n cube time so let's see how this plays out in code so let's go to the font part let's go right the code now and let's see how it plays out in code so first let me kind of increase the font here so the first thing we want to do here is to uh check the base cases so the best case is when the string is empty so i'm going to say if s is 70 so if the length of s zero we are going to simply return so the longest string here is going to be an empty string okay uh if we look at the question let's see what they tell us about our empty string um so they didn't give us empty string so we can so we have s has to always be one okay greater than one so we don't have any business checking list so let's check for one only one item and if it's only one item then the longest palindrom is going to be that item i'll simply return it now let's also make life easy by checking when length of s is two so when the length of s is 2 what do we are going to return those the item if both of them are equal so in this case we are going to return s if the first and the second item are equal so if s0 is equal to x1 okay return x is equal to if a0 is equal to x1 ah then i'm going to now say else if they are not equal so just return the first item perfect now what we are going to do here uh we are now going to begin uh some initializations first okay so let's go back to our drawing board here so permit me to kind of uh take this and clean up here so if you look at what we just set up we've checked for here we've also checked for when there are two items so now we are checking now for when there are three or more items so that's what our loop is going to be doing and from what i told you before we are going to start from here right this is the only place we can start from that is going to take into consideration both sides okay so it means that we are going to first we are going to set the longest so far so let's call it longest so far to be s zero okay so these are longest so far okay uh until we check and find out that there is something longer than the longest so far so this is just as an initialization and we need two pointers uh at this point so let's see so we have um the first point is going to be i so for now let's just loop from i is equal to 1 all the way to the end so i'm going to say for i in range going from one to line going from one to length of the string uh yeah i think we can add plus one here because the last index is not inclusive uh yeah okay great okay so we are now at index i which is here we are now going to initialize two point as l uh let's call it left is equal to i minus 1 and right is equal to i plus 1 okay so we now have two pointers initialized uh so now we are going to begin a loop okay uh another loop that actually now uses these two pointers and goes in two different directions so i'm going to call that a while loop now if we are at point let's say here at points uh let me take my pain at this point our loop is going to continue looping uh while the left pointer is zero or more the loop is going to continue looping or the right pointer let's say we are here the right pointer is at the length minus one all right are the lengths uh minus one so in this case we have zero the right point that gets to three we are going to also stop the loop so we are going to now begin the iteration while left is greater than or equal to zero y left is greater than or equal to zero and because in this case while left is greater than equal to zero and right is less than or equal to is actually strictly less than line s okay so what we are going to now do at this point is to check the items at left and right so we are going to check the two items so we are going to say if the item at left is not equal to the item on track because we want to terminate this uh check if the item on the left and right is not recalled so if the item in the left is not imported the item in the right we are going to simply break and start another a while loop now after increasing the left and the right so i'm going to say if s left is not equal to s right what do we break out of this loop there's no need of checking because even if you find two items the same it can be a palindrome because it's been broken somewhere so else now in the else parts we have a palindrome okay we have a palindrome because the items are the same so else we are going to now uh we're now going to adjust the left so far here we're going to adjust our less left so far if the items the palindrome found in this case the palindrome will be running from left to right so if the item going from index of left to right if this item is greater in length if the length of this string this palindrome because a palindrome was found then we are going to update our left so far so i'm going to check that if okay why am i having this arrow here and let's just take all this okay so i'm going to say if the length of the string calls s of uh s going from left to right plus one because remember the right index is not inclusive if the length of this string uh is greater than the length of the l so far of the length of the line existing line so far we are going to replace the length of the lsf which is our existing um our longest uh the longest so longest string so far we're gonna just replace it with s uh left and right plus one so if we check this against this let's take for instance we are left so fine in this case let me just do a little bit of cleanup so our left so far we initialize to our left so far e l uh left so far we initialize it to b you remember when we say l s of zero now in this case b a b right b a b we are going to now uh we are not we have because in this case our left is zero our right is two so i'm going to now set the left so far to be s of 0 to 3 okay so x of 0 to 3 is going to give us b a b so we're going to update our left so far um yeah so i think i'm getting this syntax a bit wrong sometimes i mix it up so it's going to be a column uh actually and this same here as well okay so we are going to replace our left so far and let's check what else do we do nothing and regardless we are going to advance our pointers so i'm going to just advance the legs to the left minus uh equals one and because i'm now advancing the left uh one step minus i'm going to do the right plus equals one okay so i'm advancing the right pointer as well okay so this is basically it at the end of the day uh at the end of the day let me just check if i'm not missing anything um we are simply going to return uh what do we return at this point we are going to return um a second we are going to return lsf line so far okay so this is what we are going to return here and here so now there is a catch because if you look at it we are checking that there is an item in the middle what if there is a situation where there is no item in the middle for instance if you look at the string s is equal to b for instance okay and we can if we set the height if we set here it means that we cannot do a check this way you see so there must be a way to also test for palindromes where the palindrome is even number of items like this in this case we are not going to be doing uh meat we are not going to be taking i and i plus 1 and i minus 1. here we are going to be simply taking i the left here is going to be i because if we set it to here okay the left now is going to be i minus 1 and the right here is going to be i okay so in this case we now have zero and one and at that point we can simply do exactly the same thing with these unfortunately i don't know exactly how to reduce the code base so what we are going to do here is to just replicate the code base so it means that when we do this for loop here we are going to do it a second time detecting even number palindromes because what we have here is odd number palindromes for this very loop right here okay so i'm going to copy this time is going to be for even number palindrome so i'm going to kind of adjust this and kind of reduce the font to make the code a bit readable and then i'm going to put a comment here i'm going to say for even number palindrome okay and this for loop here is going to be for odd number palindrome okay so this is what we have here now how do we adjust the even number palindrome of the feet again we have that we are setting our eye to one to length of x minus 1 that is remains the same and we are setting our left to i minus 1 our right is now going to be i like this so if we now look at this while loop if the both of them are multiplied contaminate but if both of them are equal we are now going to check now we have to take a look at this condition here just make sure it works so if the uh the length from zero to two in this case is zero to one because this is once it comes here we found another padding drum we are going to adjust this and of course we do an increment here uh so i think we should be good to go now except that i need to just check yeah okay so let's run this code and let's see what we have so i'm going to click on the run button and yeah and it works so let's see if we can submit i hope it works let me make some room here so i'm going to submit this code now and let's see and it works so you see a runtime 18.36 and it works so you see a runtime 18.36 and it works so you see a runtime 18.36 uh 18 36 millisecond faster than 35.9 uh 18 36 millisecond faster than 35.9 uh 18 36 millisecond faster than 35.9 percent of 5.3 that is not so bad i percent of 5.3 that is not so bad i percent of 5.3 that is not so bad i think we did a good job and i think it's quite intuitive so i'd like to thank you for viewing please remember to subscribe to my channel and if you have a particular challenge you want me to handle uh please leave it for me in the comment box below this video i remain times on the tech pro and i'm always there for you
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
1,690 |
hey what's up guys this is chung here so this time let's take a look at this one 1690 stone game number seven i believe so another stone game so alice and bob take turns playing a game with alice starting first so this is another like game problem and for this problem there are end stones arranged in a row and each players on each player's turn they can remove either the left most stone or the rightmost stone and by doing that they get the points by the sum of the remaining stones values and the winner is the one with the higher score when there are no store stones left to remove okay so and it asks us to find the maximum difference basically the but how many stones right but the maximum winning point alice can get since alice will start uh start the move first so for example this one all right so that's some examples here you know for this one alice can either take five or two that's the only two options she has right and then by taking five she gets the point of this part if she gets if she takes two she gets the together points on the left part so and there's like constraints here right so the constraints end to the power of sorry it's a one thousand so i mean the brutal fourth way is the average time we just uh do a basically just do a dfs search and every time uh at each of the numbers we have two options we either take the left one or take the right one but obviously that's not gonna it's not a good solution because the that's the time complexity will be 2 to the power of 1000 right so because that was definitely tle so we have to uh do what so we have it's obviously it's not obvious i mean we can certainly use the dynamic programming to solve this problem you know and for this problem you know actually it's pretty the definition for the programming is pretty straightforward basically the dp it's just the i and j right so or where i call it left to right left and right this may be better to understand basically from left to right and for the left and right what's the maximum difference the per the person who's going to take this left and right stones can get right and the difference for this one is this then state transition function is also kind of straightforward right so once she takes once this person takes the left most one right so we have dp left plus one right and then right that's going to be the remaining parts and then we'll plus the difference sorry so let's see for this part there's like a point let's see there's a p1 from here to here right that's p1 and then from here to here this is p p2 so by taking the uh by taking the leftmost one so and this person will get p1 right and then since we're defining like this is going to be the most winning points the current person can get so by taking the first one so we are basically we need to multiply we need to subtract the numbers taking from the next step because the next person will start from this state which is dp l plus one and then r okay right so and this is the this is basically the difference by taking the left most one because again so this is the point we can get but the next person will get the whatever we have here which is the uh by taking either the left one or the right one so that's the basically the first uh option here right and the second option is of course by where so the current person will take the right one so the right most one that's going to be the p2 and then we're going to have like similar thing dp l to r minus one right i mean this is like a typical way of solving this uh gaming problem you know since just two persons will play uh in turn right so this time this person plays and then the next time the next person will play and the next person will also get since both person will play optimally right and the next person will also so then basically the next person will get the difference from this dp l plot plus one r and we don't have to we don't need to worry about actually we don't need we don't care who is playing the current dp state yeah because you know someone made me wondering that okay since we're getting the alice maybe we need another state here to vary to st to tell us who's playing this one but it doesn't really actually doesn't really matter because if you treat those two persons uh separately actually they are they're playing independently it's the only difference that one alice will start first and then bubble with what follows we'll follow alice that's it so basically at each of the state so it doesn't really matter who is playing the current one we're only calculating the biggest difference at the current player is playing so that in the end all we need to do is we just need to do a dp 0 and n minus 1 because at the beginning at the very start you know this is the start for the whole stones and now alice is going to play that's why we just need to return this dp 0 my n minus 1 that it will give us the maximum difference alice can get right so yeah and of course so to uh to calculate these things right it's obvious it's uh we all we should use a pre-sum so that can we should use a pre-sum so that can we should use a pre-sum so that can help us improve that so and that's the other basic you know the state transition functions and for this problem actually and you know for dp you really have two ways to do it right top down or bottom up and for this problem top down is the most straightforward solutions so i'm gonna to start with that and after that i'm gonna also try to do at the bottom up by the bottom but sorry but the bottom up is a little bit different than the traditional bottom up for loop it will requires a little bit change so but let's try to do the uh the top down first since it's the most straightforward one and here we go so in the end we just need to return dp 0 and then because the stones right so in the end we need to return the n minus one that's going to be the uh the final answers and then we need to have like a pre-sum and then we need to have like a pre-sum and then we need to have like a pre-sum so for the pre-sum you know uh we can so for the pre-sum you know uh we can so for the pre-sum you know uh we can either use like the uh minus one zero right because i personally prefer a dictionary because that can help me handle this minus one case so that i don't have to shift this index by one to the right side i mean but i think for the dictionary is a little bit slower than the array you can of course use the list you know but to use the list you have to consider um handling this index and shift it to right by one but for the uh for the dictionary we don't have to worry about that because the dictionary can give us the minus one case and yeah or even use the array you can handle the zero case separately so and then for if it's like zero you just return zero if it's a minus one we return zero right but since i'm using a dictionary i'll just uh continue with my solution here so enumerate so now i'm just building the pre-sum just building the pre-sum just building the pre-sum list all right so pre-sum i equals to the pre-sum pre-sum i equals to the pre-sum pre-sum i equals to the pre-sum i minus one plus s right so that's that and then the top down right so the def dp left and right and how are you of the cache right it's not so and oh so for the base case right so the base case for this problem you know so by the time there's only one numbers left if you go through the examples you can see that whoever i mean if there's only one numbers here whoever is playing this number is whoever the turn it whoever takes the turn that person will only will get zero because by removing this one there's nothing left that's why we will have zero so that's why the base case is if the left equals to right so which means there's only one stone left we simply return zero other than that we just do a system.max other than that we just do a system.max other than that we just do a system.max since we're getting the maximum right and uh we just uh do uh the maximum of two case right so you either take the leftmost one which is the uh the prism actually we don't even need this one since it's uh it's just one of the two scenario we can just do this so gonna be the pre-sum right so the pre-summed l pre-sum right so the pre-summed l pre-sum right so the pre-summed l sorry right minus three sum left and then we plus minus right so that's the uh the sum we can get by removing the leftmost one and the red the rest will be dpl plus one then r right so that's that and the second one is the uh it's different pre sum l minus one minus three sum left minus one and then subtract dp uh l r minus one and then please return the answer yeah i think that's it if i run the code okay so this one passed um time limit accident really what if i do this sorry i'm just yes when i did this way it did it in this way in that during the contest it didn't tle okay so that's what happens basically you know so for this problem you know the top down is a little bit there's some i don't know there's some bug issues in the online judge basically you know if you don't uh if you don't limit the cash uh you use you would you get the tle and so that's why you know if you do a nine here right so usually it's fine because this is the time complexity just like what the n square right so it's the n square because that's the 11 right there both in here i don't know why this i think that's the online charge issue so it's just n squared shouldn't be a problem but if you don't limit this not this line here it will it'll tre for some reason it's really weird and one way of doing this to fix this you either like do this you just limit like what i did you limit this one to some numbers right for example since we know that to us like smaller numbers right or we just or another way of doing this it's like in the end here before returning it you can there's like dp dot uh cache i think cache clear i think yeah so it where it will clear the cache so i think this should also work if i'm not mistaken all right for some reason this one didn't work and oh i see sorry uh so yeah so for this one uh we have to do this yeah we have to call the dp first and then we do the dp cache clear and then we do uh we return the answer yeah so i this is like a weird thing but i don't think you guys need to worry about that it's just like the online downline the website or the language specific issue but the concept is this here's just so ignore this one ignore this uh this issue but the top down is pretty straightforward right just like we either take the leftmost one or we take the rightmost one and then we pick the maximum amount among those and then that's the base case three street four right so and the bottom up one so for the bottom up you know since we are defining like a left to right so it's for bottom up it's als always it's also going to be the same dp left and right but if we follow the other traditional way of doing the bottom up way which is the uh which is this and i'll need this thing which is the l and the right and the way we're doing the for loop for the bottom up is something like this right for i in range of to n and then for j in range of up to i something like this right and then basically for each of the stones and for the stone here we're trying to look at we're moving the eyes forward we can do it either from the in the front from start or from the end and every time when the eye is here we're trying to calculate all the other substrings within the eyes here okay but you know for this one it won't work because the way the game is being played this is because you know the current one the i and the iron j it could be removed from either the left or the right one so what does it mean it means that you know if we remove from the left one so by the time we remove the left one the remaining parts so the dp of l plus one has not been calculated yet right because we are we're calculating from left to right so let's say we have r here and we have a this is our this is the left so by the time we calculate this one the r the dp rl plus one has not been uh calculated yet and that's why we cannot simply do this is like for a nested for loop for the traditional bottom up so how to how can we do it i mean another way of doing this um of doing this kind of bottom up way is we instead of looping through the index indices we can always look through the length of the uh the subs the substring or the sublist so basically what i'm doing what the way i'm doing it is that like for each of the length right so the length could be from starting from uh zero doesn't make sense so from one to n minus one that's the length so for each of the length i'm going to loop through i'm trying to find all the substrings i'm sorry the all the sub array that has the length of the current one and then i'm going to calculate that because why is that because let's say we have five three one four two right so the bottom up so the idea of bottom up is that we're starting we started from the small we start from the base case and then we build it we build the solutions from bottom up we from we start from the very the smallest case and then we build it up so what's so what is the smart the base case we have already analyzed it so the base case for this solution for this problem is so one number which is the five three one four two so right and we know that you know uh so if we calculate all the cases for the base case and then we can start building the uh what the five and three so we have five three and we have three one right and then we have one four and then we have four two right so that's the second layer so it means that uh we have we already have the base case that's why we can use the base case a smart the previous previously calculated a small sub case sub problem to call to get the current one which is the lens two right like i said since this one can be since we cannot from can do it from one side that's why we have to use the length basically we and then from this one we can just uh do another one we can do a three right five three one and then we have this is gonna be the one three one four right and then one four two right so as you can see here for the for this current one right so since we are going to remove either the left one or the right one and by removing the left one what we're ending up is like it's another sub problem it's a length two same thing for same for removing the right one we end up with another sub array which is length two that's why since this problem can either do it from left or right that's why we have to do the loop the first loop is going to be the length and then we build it start starting from there cool so and all right so the length is okay so for that let's create like dp right so the dp is zero so at the beginning we have zero and four this thing in range zero in range n and oh and the reason i use zero not the minimum the maximum of the negative values is because uh i saw that i don't have to initialize the uh those numbers who has the length one you know right because like i said you know for those like the one number case you know there they should have all they all should have zero that's why i initialize everything to zero so that when i start looping the length here i can start looping from two instead of one because for all one case they already been set to zero that's why we have two to n plus one yeah since this is the length that's why we need a length n and then we have a left right so the left uh that's going to be the n minus length plus one right so that's the uh the left one and with the left and the length we can easily get to the right will be the left plus the length minus one right so and then we can just follow what we have before right so the left and right is equal to the max of i can basically copy these things here the only difference is that i have to change this one to a list right so that's that the other one is this i'll copy this one l to r minus 1. and in the end same thing just dp 0 2 and minus 1. yeah i think that's it so if i run the code all right and if i submit okay so it's also accept it yeah so as you guys can see here right so that's why we have we need to loop through from the smallest case in this case it's a length one it's not the uh it's not a particular string on the left most side or on the right most side it's the length one for all the strings and then we build on to a lens two and the lens four until we have uh consume exhaust all the length is all right cool guys i think that's it for this problem and oh so time complexity o and square right i think i have already talked about that i don't quite remember all right i'll stop here thank you for watching this video guys then stay tuned see you guys soon bye
|
Stone Game VII
|
maximum-length-of-subarray-with-positive-product
|
Alice and Bob take turns playing a game, with **Alice starting first**.
There are `n` stones arranged in a row. On each player's turn, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.
Bob found that he will always lose this game (poor Bob, he always loses), so he decided to **minimize the score's difference**. Alice's goal is to **maximize the difference** in the score.
Given an array of integers `stones` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **difference** in Alice and Bob's score if they both play **optimally**._
**Example 1:**
**Input:** stones = \[5,3,1,4,2\]
**Output:** 6
**Explanation:**
- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = \[5,3,1,4\].
- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = \[3,1,4\].
- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = \[1,4\].
- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = \[4\].
- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = \[\].
The score difference is 18 - 12 = 6.
**Example 2:**
**Input:** stones = \[7,90,5,1,100,10,10,2\]
**Output:** 122
**Constraints:**
* `n == stones.length`
* `2 <= n <= 1000`
* `1 <= stones[i] <= 1000`
|
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.
|
Array,Dynamic Programming,Greedy
|
Medium
| null |
122 |
is persistent programmer here and welcome to my channel so in this channel we solve a lot of algos and go through a lot of legal questions so if you haven't subscribed already go ahead and hit that subscribe button under this video and let's go ahead and get started today with our question best time to buy and sell stocks too so in this question we're given a input array that looks like this and um if you haven't done the first version of this question i will link it in this video somewhere so you can have a look at that too and so the difference between that question and this question is that we are able to perform multiple transactions um at the same time uh so we can do multiple stock buy and sells but we can't sell a stock um if we sorry we can't buy a stock if we haven't sold the previous stock already so let's look through this example to understand the question um so we're given an array like this and it says that buy on day two so if we buy when it's the lowest tier price one and sell on day three which is where price is five we made a profit of four right and similarly after we have done that transaction then only we can proceed to our next transaction which is to buy and sell again so we buy the stock on day four again which is where price is three and we sell the stock on day five which is where price is six and so we get the total of these two profits that we've made which is four plus three seven so if we look at the graph here um i have plotted out this array exactly and what we can see here is that we make profits when we are going from a lower day to a higher day so here is the case that is written over here where we have the profit of five minus one so we went from a lower day in the previous day to a higher day right and uh similarly here this case six minus three um which is where we had a higher day here and a lower day here okay awesome so let's look at some strategies on how to solve this problem okay awesome so we have visualized the problem here and we can see that um the maximum profits that we can make is when we have a low day and then we sell it at a higher day and then keep selling it if we have a low day yesterday or the previous day and then a higher day the next day so the sum of all these positive deltas is actually what's going to give us um the answer which is seven here right so let's go through this example um to make sense of it more so let's say i take the deltas of everything in this array so remember that we can't um sell something we haven't bought so it's going to be this value the next value minus the previous value so it's one minus seven that's why it's negative six um and then same thing here five minus 1 4 so we can see that this is a positive value right and then we have negative 2 and then we have 3 here so this is again a positive value and we have negative 2 here so basically the idea is that we don't want to accumulate negative values towards our maximum profit because that's not a good strategy to make money when you're selling and buying stocks so what we need to do is add these positive deltas to get us to our final answer now what we can bring from this is we can derive some conditions in our code that we need to check we need to have a way to check if our prices in the next day is higher than the previous day so this is what we're checking right and to convert that to our system code what we need to check is if the current position i'm at is greater than the previous position so i minus 1 is just getting us the previous position so let's say i'm over here at 5. so is 5 greater than 1 yes it is and this is one we need to accumulate and add to our profit so that's the basic idea behind this problem so uh what you need to do is just check this condition and then if this condition meets then we add that to the profit the other case to keep in mind is that if you continuously have a negative delta so there's no way for you to make a profit because you bought the stock on the highest day you need to just return a zero and with our check where we are checking if the price next day is higher um than the previous day it won't even hit this case so we are good with um just uh initializing that profit to zero and then just returning the profit for this case awesome so let's go ahead and dive into the code so what i've done here is i've initialized the profit to zero and then we need to return the profit at the end and what i'm going to do now is create a for loop so for um let i equal zero and then actually we need to start at one because we are going to get the previous element right so we're going to check if that current position so um the loop is going to start here and we're going to check if this value is greater than the previous value and when that is the case that's when we need to accumulate to the profit so that's why we're starting at 1 here is equal to i is less than prices dot length and i plus okay great um what we need to do now is put our condition in so if prices i is greater than prices i minus one this is when we need to accumulate the profit so profit is going to be um the delta of the price so this is the values we have calculated here so that's what we need to accumulate the profit to so prices i minus one okay awesome and we need to return the profit okay good so i will run this okay awesome accepted and submit yeah success
|
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
|
88 |
hi guys in the video merge two SED lead one of the least important problem let's get AR a so n plus m equal to X so X log of x in the intu is not going to work for us next okay crein so next we found out we are going to use three pointers poin was thir question9 in same 4 problem so it's not a problem going to same three pointer algorithm i j okay for let me explain simp okay up four zero compare I mean four so in the reverse order let me rewrite that array wait 1 3 5 0 the 2 4 simple maximum element okay a of K A output a of simple for while J is greater than or equal to Z simple next so yeah let's solve this problem it doesn't mean you have to solve it inage can do it in any language minus C so you can do it in any language as you like so first thing = length of a minus 1 J = to length of B = length of a minus 1 J = to length of B = length of a minus 1 J = to length of B minus 1 is the length of B number El a b l a b we can easily solve this problem let's do this something i j n minus 1 k m we not going to do anything extra so J less than or equal to n so great for easy understanding a so B a of IUS equal 1 IAL IUS 1 it's not a problem right going to again = Jus one again = Jus one again = Jus one meaning okay in the whole process = Kus we'll get our output test case is accepted let's submit it runtime error list out of range okay so only is greater than or equal to zero and we move it will face an issue so we have solved it internet eror speed Maybe see it is fast so in the can definitely Sol by guys
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
530 |
hey everybody this is Larry this is me doing the uh leeco daily child day 14 uh yeah hit the like button hit the Subscribe button join me on Discord let me know what you think about today's pop and also hope you enjoyed the drum video as I've been trying to do them as I am traveling I am currently at a city of Albany um learning a little bit wash and finally I don't know why it took me that long to even think about it so definitely um yeah very little just started Duolingo so uh yeah uh so it's never too late to try to learn whatever I actually learn we'll see but yeah anyway all right today's problem is 5 30 minimum absolute differences in pst3 and I haven't done this before so yay for Newport we've done the minimum absolute difference between the values of two different notes in the Trees of the two closest one right the thing to notice is that this is a binary search tree so that means that um if you do it in Orange reverse so then it's going to give you the numbers in order and of course the minimum absolute difference in the list of in order will be just around you know two adjacent elements right so using that knowledge we can uh better is also the same as another above but using that Notch we can just you know do the do they know the traversal right and then just keep track of the previous number so maybe we could just do the previously go to none uh is it is there at least two notes or at least two notes so maybe you could even sell know it by doing like negative Infinity where Infinity is just some obscenely big number I've seen you enough maybe Mali I've seen um but yeah and then you just do in order so if you could spell that correctly uh yeah so the code is going to know that value right uh I mean I'm just setting it up so we do in order to know that left in order to know that right if notice none we return we already terminate this is the processing step and then basically uh yeah so yeah Delta is equal to current minus previous and then best is or closest maybe you want to say that is equal to Min best of Delta and then now we update previous is you go to the current of course we have to not local some stuff and that should be good maybe not the prettiest but you know linear time and of course oh whoops whoopsie daisies yeah linear time uh linear space or it's linear space in the worst case of course you can also if you want to be a little bit sensitive to the input um H is the height of the tree right so definitely a couple of things I'm a little bit lazy today just because I think this is pretty basic and apparently it is the same as the other problem but uh but you know Cafe uh you know just Prime test recursion tree which is already recursive data structure and just I don't know I guess that's maybe heard me I don't know if I had the three things maybe we just work three's but what I mean is still uh you absolutely need to know to do how to do this and probably at this point to be honest relatively quickly um for interviews and stuff like this I'm definitely for sure of a competitive um because it cannot it doesn't really get much easier than just in with respect to this type of problems so yeah uh that's all I have today let me know what you think stay good stay healthy to good mental health I'm dancing I'll see y'all later and take care bye
|
Minimum Absolute Difference in BST
|
minimum-absolute-difference-in-bst
|
Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 104]`.
* `0 <= Node.val <= 105`
**Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
532
|
1,921 |
hey everybody this is larry this is me going over q2 of the weekly contest 248 on lead code obviously you eliminate maximum number of monsters hit the like button hit the subscribe button join me on discord give me a little support because i had tears over this one really should have been i feel like should have been easier but i had two mistakes and took a long time so this one is greedy it's the short answer i'm gonna give you the algorithm but i'll also go over why i struggled with this one so this one is greedy in that you always basically want to shoot the two ways to think about greedy right one is at every time shoot the one that's closer to you but you're gonna have to up do an update on that alive right so the key thing is basically um the second type of greedy is thinking about you have to shoot the monster that is um going to get to you can basically shoot any monster that is going to get to you or the not the monster that is closest to you but the monster that is going to get to you next so that's basically the idea that i did um and of course um so this is my code really small actually basically we look at the distance and the speed we put it together and then we sort it by distance over speed which gives you the time that it arrives and you know that's a basic you know uh line intersection type thing so yeah so we sorted by that and then for each time we go okay because we could shoot one at a time we just enumerate through all of these and then we basically if you rewrite this is basically this which means that if the current time is greater than the time that it arrives then we get eaten by the monster i actually been watching a lot of zombies moving on relatedly so i actually relate very hard to this problem i felt really uh scared when i was doing it maybe that's what freaked me out but in any case and the reason why i skipped the first monster and the time one is because no matter what in the beginning i shoot the first closest monster or the monster that would get to mucosis so you always start you always have one monster that you shot so the reason why i have this i struggle with this one even though what i said is greedy and it's straightforward in that sense and it makes sense because it doesn't um in terms of proof you don't want to shoot a monster that's farther away from you because that's always going to be suboptimal i know that i'm using english and it's not a rigorous proof but you could probably imagine that my issue was that i always worried about um phoning point division that's always my i think and in this case i worry that i'm gonna mess up on a floating point to be honest so i was doing a lot of weird things to over optimize and try to think about try to do keep having an integer and i think if i use python 2 you could do it because you can do computer based sorting instead of key based sorting which basically if you have comparison based you can actually compare them in a way that is in um that is 14.3 is in um that is 14.3 is in um that is 14.3 and then this is also 14.3 but instead i and then this is also 14.3 but instead i and then this is also 14.3 but instead i did a couple of things and i had some like i think i had this but i missed a less than equal sign or something like that so that was just very sloppy um yeah but overall this is basically gonna be n log n time uh of n space because of the sorting and different various things but yeah basically short ends are greedy and just keep on shooting the monsters uh yeah that's all i have for this one you can watch me suffer live and you can watch me like try to do it with integer only stuff and then messing up really poorly um you could do that or that during the contest next okay that was hard to read um hmm you hmm just gonna give me issues oh actually not okay um um hmm really slow today um that's not even right whoops so that's not right then is this right yolo okay maybe i knew it wasn't gonna be right this is such a mess okay so the answer is two did i get this one five so i don't even need to do all this funky stuff okay another wrong answer my weakness okay fine did i miss did i misread this no i can't read this right so guys so now 10 so you shoot this one and then second turn the answer should be for the second time you shoot this kit and so that's time two zero one and then two wouldn't that be two did i misunderstand this exactly the start of a minute right oh wait what oh i know i see but this is uh i need a comparison-based but this is uh i need a comparison-based but this is uh i need a comparison-based sword i think that's why because i was worried about this okay let's give it another go okay that was just me being dumb uh yeah thanks for watching everybody hit the like button to subscribe and join me on discord let me know what you think about this problem uh it was a tough contest so hope you did well uh yeah stay good stay healthy to good mental health and i will see you later bye
|
Eliminate Maximum Number of Monsters
|
eliminate-maximum-number-of-monsters
|
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city.
The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start.
You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon.
Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._
**Example 1:**
**Input:** dist = \[1,3,4\], speed = \[1,1,1\]
**Output:** 3
**Explanation:**
In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster.
After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster.
All 3 monsters can be eliminated.
**Example 2:**
**Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,1,2\], so you lose.
You can only eliminate 1 monster.
**Example 3:**
**Input:** dist = \[3,2,4\], speed = \[5,3,2\]
**Output:** 1
**Explanation:**
In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster.
After a minute, the distances of the monsters are \[X,0,2\], so you lose.
You can only eliminate 1 monster.
**Constraints:**
* `n == dist.length == speed.length`
* `1 <= n <= 105`
* `1 <= dist[i], speed[i] <= 105`
| null | null |
Medium
| null |
495 |
hello everyone in today's video we will see lead quot problem 495 Teo attacking and it is a easy problem so in this problem uh there's a hero called Teemo and he's attacking an enemy ASE with a poison attack and it is said that uh the Ash gets poisoned for exactly duration second duration is a second so he's getting affected by the poison for dur point of time and uh if uh we can say it like an attack at second T will remain Ash is poison during the inclusive time interval of T to t+ duration minus one interval of T to t+ duration minus one interval of T to t+ duration minus one so once an attack is done to the Asche it will remain till T2 t+ duration minus it will remain till T2 t+ duration minus it will remain till T2 t+ duration minus one time interval okay so if Teo attacks again before the poison effect ends the timer for it is reset and the poison effect will end duration second after the new attack okay so it is an ascending integer array and we are given with array time series where time series I denotes the temo attacks at that second and Inger duration so we need to return the total number of second that Asha is poisoned Okay so let us understand the example so the time series is 1A 4 which means that the attack has been done at first unit at first time it means uh we can consider a number line uh where attack is done at 1 and uh it will remain till uh next two unit for example an attack is done at 1 then it will remain till 1 to 2 to 3 it will remain till 3 so next attack is done at four so it will remain from four to next two unit for example 4 5 6 it will remain from 4 to 6 and this attack will remain from 1 to 3 so 1 2 3 and 4 to 6 so there it is covering four units so we will return four and the second example is uh 1 comma 2 so first attack is done at 1 and the duration is two so it will remain from 1 to 2 to 3 it will remain from 1 to 3 and the second attack is done at two so it will remain from 2 to 3 to 4 so in total it will remain from 1 to 3 so we need to it will remain from 1 to 3 so 1 to 2 to 3 no it will remain from 1 to 2 3 to 4 because 2 will remain from 2 to 3 to 4 so it will remain from 1 to 4 so 1 to 2 3 and 3 to 4 so we need to return three so there are total 3 seconds so what we can do in this problem that we can initialize a sum and put it as zero and we need to create a for Loop and I is equal to 1 I should be less than equal to time let us consider it size to be N in N is equal to do size okay size should be less than n and I ++ so what we need to do is n and I ++ so what we need to do is n and I ++ so what we need to do is that uh we need to take our sum and we need to put the minimum of Time series of I minus time series of i - 1 we need to substract four we need to subtract two from one we need to substract sorry we need to substract one from two so 2 - we need to substract one from two so 2 - we need to substract one from two so 2 - 1 and then we need to take the minimum of it with duration okay so we need to put this minimum into our sum and at last we need to return our sum plus duration because we are not adding for the last number we are not adding the duration for the last number because here the first one it will take 2 seconds so here the duration is 2 and then we are taking the difference here so 2 - 1 which is 1 so we are here so 2 - 1 which is 1 so we are here so 2 - 1 which is 1 so we are taking 1 comma of 2 so the minimum is 1 okay so the minimum is 1 so we will put one into our sum and we are not calculating the duration for the second because we are adding it here so in our sum we have one and we are adding one with duration two okay so our uh we will turn three here so this is a special case here so we are mostly dealing with this okay so let us try to run this Oho I missed a semicolon here everything looks fine so let us run this okay it is accepting all the test cases so let us try to Summit okay so it is accepted so thank you guys if you find this video informative for you and you get to learn something from this video then please do subscribe and like and do support me thank you
|
Teemo Attacking
|
teemo-attacking
|
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack.
You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`.
Return _the **total** number of seconds that Ashe is poisoned_.
**Example 1:**
**Input:** timeSeries = \[1,4\], duration = 2
**Output:** 4
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
**Example 2:**
**Input:** timeSeries = \[1,2\], duration = 2
**Output:** 3
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
**Constraints:**
* `1 <= timeSeries.length <= 104`
* `0 <= timeSeries[i], duration <= 107`
* `timeSeries` is sorted in **non-decreasing** order.
| null |
Array,Simulation
|
Easy
|
56,605,649
|
415 |
hey everyone welcome back and today we'll be doing another lead code 415 add to string given to non-negative integers to string given to non-negative integers to string given to non-negative integers num1 and num2 represent it as strange rate and the sum of num1 and num2 as a string you must solve the problem without using any built-in library for without using any built-in library for without using any built-in library for handling large integers such as big integer you must also not convert the inputs into integers directly so we have to solve them as they are in string so you can see like example two four five six seven will be returning as 533 we have to add them like integers but without converting them this is uh what they are saying what we have to do is just take their ASCII value subtracting by 0 and whenever we have a carry now carry is the thing like if you add six to seven it is um 13 you will be taking 3 and carrying 1 to the next position so that's it this is it so we'll be making a output list also our carry which will be initially 0 also a pointer at one uh for the num1 so the num1 will be like this the pointer at the very end the pointer of the num2 will be the length of the num2 minus one so while these two pointers pointer one is still there like greater than or equal to 0 or one of them is still there pointer at 2 is greater than or equal to 0 we are going in and if the pointer one is greater than equal to 0 what we will be doing is calculating its value by which will be value 1 how we'll be taking the ASCII number as key value of the num1 by giving it a pointer uh one so this looks good and now to ask you is subtracting it by the ASCII value of 0 and in the else case if there is no pointer one like in this case you can say like 12 and 2 there is no pointer 2 in this situation so what we'll be doing is just taking its value as 0. so value 1 will be 0 and doing the same process with pointer 2 and value 2 num to pointer 2 and now value 2 so this looks good yes this looks good what you'll be doing is just value and make this will be the value that we are going to append so we'll be adding the value of 1 plus the value of 2 plus our carry divided by not divide if we just take like this modulo by 2 and a model by 10 and carry will be the value at 1 plus the value at 2 plus carry itself if there is a carry so dividing it by 10 and that's it like this looks good after doing this we can just output dot append the value after that we can also update our pointer so pointer will be decreasing down to the very first index so pointer 2 will be also going down to the very first index after doing this we will be making out of the loop and if there is a carry so this carry is going to be appended in our output load up and in our output so carry is now like this so this is for the case like 999 and we have again 999 then there will be a carry in the fourth position so after doing all of this we can just return a string joining our list but we have to Typecast it into string so for every character so for every I in output we will just reverse it so this looks good less let's see if this works or not this works let's go and that's it if you have any kind of question you can ask them in the comments and that's it
|
Add Strings
|
add-strings
|
Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_.
You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly.
**Example 1:**
**Input:** num1 = "11 ", num2 = "123 "
**Output:** "134 "
**Example 2:**
**Input:** num1 = "456 ", num2 = "77 "
**Output:** "533 "
**Example 3:**
**Input:** num1 = "0 ", num2 = "0 "
**Output:** "0 "
**Constraints:**
* `1 <= num1.length, num2.length <= 104`
* `num1` and `num2` consist of only digits.
* `num1` and `num2` don't have any leading zeros except for the zero itself.
| null |
Math,String,Simulation
|
Easy
|
2,43,1031
|
54 |
hello everybody this is Edie today we're going to go through a LICO challenge your favorite spiral matrix problem so the instructions are as follows given a matrix of n by n elements return all elements of the matrix in spiral order let's illustrate this problem on our interactive whiteboard / paintbrush interactive whiteboard / paintbrush interactive whiteboard / paintbrush application one thing I miss about Windows computers is that their paint application is like 10 times better hopefully they make something similar for the Mac anyway this is the matrix in example 1 through 9 with 3 rows and 3 columns alright so what does it mean spiral well simply means starting from row 0 and column 0 apologies this should be column this is row so rows start from the very top at 0 column start from the very left at 0 so I'm starting from 0 right here we're going to go in a clockwise direction until we reach the very center of the matrix or close to the center so this is what our path would look like there we go and as you can see on LY code this path and the order in which we cross the numbers and matches the output one two three six nine eight seven four five okay yep and that's how you do just kidding I'm actually going to show you how to set up your four loops in order to traverse them correctly because it took me a little while to get all my boundaries straight so I think a good analogy for solving this would be an origami box within a box which I have provided here so why provide this visualization because I want you to imagine this matrix as a series of boxes within each other the box on the outside is the layer of numbers on the outside right so in this case the outer layer would be these eight numbers and the inner layer would be this number right you could imagine we could make the boxes rectangular so that there are more rows and columns or more columns and rows the same concept applies okay so now that you've got that picture in your head let's actually show you the bounds right here so let's get rid of these oh man so another thing about paintbrush is that it like can't remember like anything longer than ten steps ago so I gotta erase these manually okay so now that we have our original matrix here almost okay so how do we traverse a layer so remember we've defined a layer as a box right so let's say all the numbers immediately inside right next to the layer are included all right so this layer would include 1 2 3 actually let's make this a little more intuitive okay so anything the yellow line crosses is part of this layer so anything and each layer is gonna be rectangular in shape right and we know a rectangle is gonna have four sides right so there's going to be a top bottom actually let's go and clockwise order right because that's how we want to add the numbers to our me array top right um top right bottom left okay so you might imagine what do we need to traverse each of these layers what are we gonna use well that's called a for loop one of the most the first things you learn in programming is like they teach it in intro courses it's the for loop and basically yeah that's all you really need to know to solve this problem just for loops nothing fancy you just had to be careful with how you setup the problem so right now I am circling the numbers that are going to be included in our for loop now there can be different ways in which you set up your for loop and you'll still be able to solve the problem what I mean is like this blue you can do it up to here right and then you can have your right to column include these three on the right I'm just doing it the way I did it a new can experiment the way you want so our right side will include the number is just below the top layer or I should say the top side until the very bottom and the bottom will include the numbers just to the left of the right layer and the left layer includes the numbers that have not been included by all the other layers so you see you can see after we go through our four for loops so mm-hmm go through our four for loops so mm-hmm go through our four for loops so mm-hmm gonna remind you that we are using a for loop for each side to traverse each of the numbers in each side we complete a layer what do we do after we complete a layer well we want to move on to the next layer the inner layer right so we want to adjust our boundaries one by one in the inner direction okay so we have four sides which means we're gonna have four boundaries we're going to have so this is going to be our row so this is row and this is column right so the row on the top so this is our top layer that's going to be our upper boundary and we're going to initialize this to 0 because we're gonna always start at 0 row 0 okay apologies let me make this a little clearer okay we're gonna start at row zero how about the bottom boundary the bottom row well that's gonna be the row of our bottom side and that is going to be initialized to the length of the matrix minus one so the length of this matrix is a 3 by 3 matrix so 3 minus 1 is 2 alright and our right side is going to define our right boundary and our columns are arranged from left to right so the right column is going to be initialized to the number of columns minus 1 and our left is also going to be initialize to 0 ok so we have got all our boundary set up which is a major piece of solving this problem now I'm just gonna make this a little easier to understand by rearranging these boundaries I'm gonna put this next to this and this next to this ok so now you get the top and the bottom limits for the rows and the left and the right limits for the columns so we want 4 for loops in our first for loop and that is the top for loop right we want to go from row so let's call this the top R and let's call this the bottom our means row and let's call this actually let's use low instead so low are and high R and low column and high call so on our top for loop you want to go from low let's see low column right so we are doing this one right here traversing this side right here so we keep the row the same which is the low R but we want to go from the low column to the high column so let's say from a low column to high column at low our apologies so for our bottom for a loop okay take a minute to think about what our for loop would look like okay so we want to start from so we are going from the bottom I mean the top row to the bottom row but we don't include the top row because that's already been included in our topside right so we want to go from low R plus 1/2 PI R we want to go from low R plus 1/2 PI R we want to go from low R plus 1/2 PI R and the column is going to stay the same in this case right it's not going to change for this side so we're going to keep this constant at high C alright two more sides left so it looks like I jumped the gun they should actually be left I mean right okay so let's do bottom now we want to go from so we're doing the bottom which is this side so we are traversing the columns in this case and if you look at this picture right here we see that we do not include the right to most column because it's already been included in the right side so we can say from IR I see a minus one to low C and we're gonna do this at the higher at height the higher row right the rows not going to change okay one more side left of the left side so the left side is going to be similar to the right side except instead of traversing the rows at the higher column this side so remember higher column is right here we want to do it at the low call so this should be pretty simple to write I'm just going to copy this try it here and let's write at low column okay so this basically takes care of one layer of our matrix so this takes care of one layer oops so we want to continue doing this so we need to adjust our boundaries after we finish a layer so we want to adjust these boundaries inside right so that means we need to adjust the boundaries that we've defined earlier by one so we want to adjust our top boundary by one our bottom boundary is going to be decreased by 1 because decreasing the row will bring it inside in this direction okay our love column should be increased by one to bring it to the right and our right column should be decreased by one to the left so as a result we get 1 as our top row now 1 is our bottom row 1 is our right boundary and one as our left boundary so we do not want to stop unwrapping these layers when the row the top boundary equals the bottom boundary and the left boundary equals the right boundary in this case we want to include this number right so our condition for whether or not to continue traversing the inner layers should be as follows we should check while okay T remember that's our top boundary - bottom is greater than or boundary - bottom is greater than or boundary - bottom is greater than or equal to 0 and right - left is greater equal to 0 and right - left is greater equal to 0 and right - left is greater than or equal to 0 we're going to keep exploring the layers and adjusting our bounds by 1 to explore the inner layers right ok yeah so that is basically how this problem works if you want to see this is the code that I wrote up for this column wrote up for this problem I mean you can see the four for loops that I've included now there's a wrinkle in here that I haven't explained it's this if statement right here that kind of is a condition for entering the bottom and the left side now this basically says that checks if we enter a situation in which our high column equals our low column or our high row equals our left row in that case there's just going to be a single row or a column of numbers which we want to explore if we didn't have this if statement it would allow it would actually traverse the same numbers twice so let's say it would treat the up side and bottom side the same so we would think there are two different sides but it's actually the same side so we don't want to do that so we want to check whether there is actually more than one row in more than one column before we traverse the numbers in the square or rectangle right actually let me just go through that example real quick so okay I can just copy this here okay so you could imagine we do this we're gonna traverse one layer of this we end up here so our next layer is gonna be this stuff right here right now you notice this is not a square rectangle so it doesn't have four sides it only has two sides that means we only want to traverse two sides right so in this case we're only going to traverse the top and the right side the top side is going to include all of these the right side doesn't have a right side right and this if statement prevents us from including the same numbers in the bottom side so that's basically what it's there for okay anyway I hope you learn something I have fun doing this problem and thanks Merry Christmas bye
|
Spiral Matrix
|
spiral-matrix
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100`
|
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
|
Array,Matrix,Simulation
|
Medium
|
59,921
|
36 |
hey guys Greg here let's solve valid sidoku so our job is to determine if a 9x9 sodoku board is valid and only the filled cells need to be validated according to the following rules so basically each row column and the nine 3x3 subboxes of the grid they must contain the digits 1 to 9 without any repetition and these notes are extremely important a sidoku board which is partially filled it might be valid our job is to validate it but it's not necessarily solvable so that doesn't matter and only the filled cells need to be validated okay so what this means here is a board will look like this it's partially filled and we're not worried about the fact that this is missing items okay we just need to say so far is it currently valid and yes this one actually is we return true here in each of these nine boxes here there's no duplicates in each row there's no duplicates and in each column there's no duplicates and you really just care about if there's duplicates because you'll actually see that we're guaranteed each boarded i j is a digit 1 to 9 or it's period saying that it's nothing you're guaranteed that the stuff in the board is actually what you want it's just you need to make sure there's no duplicates so we're going to break this into three different parts we're going to validate the rows the columns and we're going to validate the boxes as you might guess validating the boxes is easily the hardest part although it's really not too bad now firstly how would we detect duplicates what data structure is good for that well since we're actually guaranteed that the board is very small it doesn't really matter what data structure you use but in general you would want to use a set because you have o of one look up for finding if there is a duplicate or not so we're going to use a set so we know that the board is 9 by 99 so we'll just do for I in the range of 9 and then this is going to send us through the rows so this is going to basically say okay this is the first row second row third row and so on now we actually need to check each row and so we need a set at least a default set s for every single row okay because when you hit a new row you want to use a new set to make sure there's no duplicates there so we'll make an empty set and then we'll say for J in the range of n i is going to go over the rows J will go over the columns so we'll see every single board position here one row at a time we'll say that the item we're looking at is the board at i j and then hey if the item is in the set s already well then we can immediately return false because that means you had a duplicate now otherwise if the item is not a period because you don't want the period in the set we don't want to put that into the set we want to just ignore it you want to s. add the item and that's really the trick for all of these in fact I'm actually just going to copy and paste this for the columns because it's extremely similar okay you would say for I in the range of N9 and for J in the range of 9 you access the item as board i j but we can actually just access board ji effectively you look at one colum at a time now the boxes there's different ways to do this but I feel like the most intuitive way is to have a nested for Loop for each of the starting positions so here a box is basically this stuff and so there's always this starting position of the box which is the top left here this is 0 if we go over three it's going to be 03 if we go over here 06 and then if you go down three rows it's going to be 3 0 3 and 3 6 0 63 and 66 okay so we're actually just going to get those we'll say starts is equal to the list of all those positions okay so now we have the starting positions but we need to keep running this Loop that uses the start position and it's going to go over just the position of the Box we'll say for I and J in the starts now we need to do this Loop to go over the box which is why we need our set here so we get S is equal to our set we'll do for Row in the range of well we want to start at I and we want to go until just I + 3 okay we want to go until just I + 3 okay we want to go until just I + 3 okay remember this is always exclusive it's going to do whatever I is and then the next two indices after that and for call in the range of J to J + 3 now we can in the range of J to J + 3 now we can in the range of J to J + 3 now we can do exact the same code except we get item is equal to the board of each row and column if the item is in the set already we know we can immediately return false otherwise as long as that item is not equal to a period then we can just add that item into the set at the end of this we are going to return true because we have passed all the checks therefore it is valid and if we run this it is going to work okay so the time complexity of this algorithm is technically constant because you are guaranteed that the board is 9x9 and the space complexity is also guaranteed to be constant as well however if you were to kind of LAX this a little bit there's no reason that this couldn't work for bigger values now it's probably still going to be a square grid so really you'd argue this is more like o of n^ you'd argue this is more like o of n^ you'd argue this is more like o of n^ squ that just means all of the positions we're going to see all those positions many times when we check each of the rows our set will store at most end things when we check the columns our set will store at most end things and even when we check the boxes those are still going to store N Things this is nine things as well okay so we would say that this space complexity is more like o of N I hope this was helpful guys drop a like if it was and have a great day
|
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
|
1,630 |
hi everyone today we are going to solve the Ral equation arithmetic subarrays okay so first of all description said we need to keep this formula so what does this formula mean so this means um all two adjacent numbers are same difference so let's say we have three and five so in this case what is the next number if we get through easy right it's seven and in it's impossible to put smaller than five because so index one minus index Z is 5us three so that is two so that's why we need to add two to five that's why uh next number is seven so what is our next number of seven it's nine and then next I think uh 11 so I think uh we have a solution pattern right so point is sort subarray then check difference between all two adjacent numbers so we don't have to sort it with descending order because if ascending order is true so descending order is also true so um let's say U we have like a three five 7 n so this is true um because uh difference between all two adjacent numbers are two right so how about this 9753 this is also true because the difference between all two adjacent numbers are minus two so um both cases meet this formula okay so let's see one by one with this example so the first subarray is from index Z to two so in this case 465 right 46 five and first of all sort this subarray in this case four five six and then U check all two adjacent numbers so difference between index zero and one is one and between five and six is one so that's why we meet this condition so in this case we should return two easy and then next subarray is from Z to three so uh 4 6 5 9 and sort this sub array and it's 4 five 6 9 and then um check all two adjacent numbers so this is one but look at between six and nine so this is a three difference right in this case we should return PSE and then last sub array is from 2 to five so I think 5 9 3 7 and S this sub array so 3 five 7 9 and I check all two adjacent numbers and the difference is two right so that's why in this case we should return true and in end so we should return like a two false true uh array yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all create a result variable with list and for query in range and the length of L and then um rest do append so we openend the result so we Creator is arithmetic Artic and sub should be nums and uh left Q column right q and we need to include the last number right number so that's why plus one and then create a is arithmetic as a in function So Def and taking like a subarray and then um first of all we need to sort as I explained earlier and then um okay so calculate diff equals uh number at index one minus number at index zero and then iterates through all numbers one by one so for I in range and uh we can start from index two and then length of sub then if sub current number minus sub minus um one current number minus one is not equal if in that case we should return false and then if pass all cases we should return two yeah that's it h no and then in the end we should return less right yeah so let me submit it yeah looks good and the time complexity of this solution should be order of Q multiply n log n so Q is a number of query here and N log n is for sorting each subarray every time here so that's why Q multiply n log n and the space complexity is order of Q so in the end we should return like a true or false length of query times so that's why this is a step-by step algorithm with my is a step-by step algorithm with my is a step-by step algorithm with my solution code I hope it will help you understand my solution code deeply yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Arithmetic Subarrays
|
count-odd-numbers-in-an-interval-range
|
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`.
For example, these are **arithmetic** sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not **arithmetic**:
1, 1, 2, 5, 7
You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.
Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._
**Example 1:**
**Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]`
**Output:** `[true,false,true]`
**Explanation:**
In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence.
In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence.
In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence.
**Example 2:**
**Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\]
**Output:** \[false,true,false,false,true,true\]
**Constraints:**
* `n == nums.length`
* `m == l.length`
* `m == r.length`
* `2 <= n <= 500`
* `1 <= m <= 500`
* `0 <= l[i] < r[i] < n`
* `-105 <= nums[i] <= 105`
|
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
|
Math
|
Easy
| null |
399 |
hello and welcome back to decoding here we discuss problems which are frequently asked in programming interviews and try to build a step-by-step solution to build a step-by-step solution to build a step-by-step solution to those problems of course discussing this space at the time complexity today we're here with a problem which is from the craft playlist that we are currently working on there are several playlists that we are maintaining a stack playlist a craft playlist and several others beside the weekly contest so these playlists are to learn and the weekly contest are to see and check your skills this video might be a bit longer so please watch the complete video and after this there will be an announcement as well so I would need your suggestions and your help so as to enhance the quality of the content theme that we are creating for you let us jump to the problem statement the problem is we are given equation of the form a divided by B which is equal to K and we need to evaluate some queries which will be of the form a divided by C so let us make this clear with the help of an example let us say that if we are given a divided by B equal to 2 and then B divided by C this is given as 3 now when we are asked to find a divided by C can we represent this as a divided by B multiplied by B divided by C we can do this there's simple mathematics and this will turn out to be because we are given the value of a by B and B by C it is 2 multiplied by 3 which is equal to 6 so this is how we need to calculate that but how can we think of it so if you think this in terms of nodes let us say that each alphabet I am denoting this with the help of a node of graph we are given a by B that is a relation from A to B so if there's a function f X comma Y which is given as X divided by Y there is a relation from X to Y so this relation from A to B which is in evaluation as X divided by B and the value of this is given as 2 so this 2 is being associated with this relation and this relation is an edge from A to B similarly if we go home B to see this an edge and the weight of the edge would be 3 first of all let us try to create the graph would be of type a string so it will be a map of type string and a vector of pair of string comma or double this is the map this is equation these are values and these are queries now we are creating the graph we are creating the edges and I equal to 0 I is smaller than e dot size M of e of Pi the solution from zero to one that is from the from A to B so in a of zero e of I of zero it is a and E or Phi of one it is B dot push back e I 1 and the value so the value is given in this another vector of double it is V or Phi this way we are done creating the graph now we need to find a way to evaluate the queries which are given to us so if we come here if the query it is given us we need to evaluate a divided by C so it is a multiplication of a by B and B by C so if we find a path from A to C and in that path the edges are of the weight two and three we can simply multiply them and get our answer so had it been a path from A to D so and this edge was given as 6 so it would be the multiplication of 2 3 & 6 let me try to multiplication of 2 3 & 6 let me try to multiplication of 2 3 & 6 let me try to prove this as well so if you were given a divided by B we were given B divided by C and then you are given C divided by D in order to evaluate a divided by T that is from A to D a path we could have multiplied them all and the answer would have been a divided by D so this is what we have to do we need to find a path from a given source to the destination so these source and destination are given in the queries array for each I is equal to 0 we are traversing the queries array now history source is Q of 0 and the destination is Q of 1 now we simply need to find the path what all girls can be used we can either use a BFS already if as I am going with the DFS one it will be of type avoid DFS it is going to take a source a destination then this map and a visited array let us create this as a set of string let us keep this as V this is visited and then to Williams double the answer that the final answer from A to C and then this will help us evaluating the final answer if the source is already visited this source I am keeping as the iterator I mean this is the node that on which we are currently on so if we dot find s is not equal to V dot end that means we are already this node is already destroyed we need to return in this case else we are visiting this so we need to insert this V dot insert the current node if the source is equal to the destination answer is equal to temp and return else we need to us each of the child of the current node also a belong to M of s this is a simple DFS that I am writing here DFS a dot first mm string D em V and answer and them so we need to change this temp as 10 multiplied by 8 or second what we are doing over here is we are backtracking here so what instead we could have done is we could have stored the value of temp in another temporary variable and then changed tempis temp multiplied by 8 or second and passed Dampier then again we can change them for the next recursive call so for the next iteration I am going to make the temp as temp 1 again so this is the backtracking part now instead of writing this entire thing we could simply write temp x you're second okay so we're done with the deepest part we just need to apply it and get the required answer we need to return a vector of double so let us create that first vector of double answer I think at the end of each video lecture I should provide certain problems which are on the similar lines and then you can go and solve them by yourself so as to practice so from the next time I am going to find some similar problems and then provide them in the description box so we need to apply the DFS now DFS from the start to the destination and pass the map or pass the visited array and then pass the answer and then a temporary variable which is fun initially let me tell you why is it one before that a set of visited a set of type of string or visited that we are passing here and answer is going to be minus one answer should be passed as a reference now what is this temporary variable for this temporary variable is initially one if you are finding a path from A to D we will be traversing from A to B and we will be multiplying 2 to the temp will now it become 2 then from B to C when we go we will multiply 3 to the temp and now the temp will be 2 multiplied by 3 which is equal to 6 there's a value of The Tempest 6 when we are traversing from the C to D the edge is of the width six so six will dream the six will be multiplied to this temp and it will be 6 multiplied by 6 which is 36 now when we reach the destination then we are going to set or answer as this temp so that is what we are doing here when we reach the destination in the DFS call if source is equal to destination we simply need to make our answer as the temporary value variable and then return as simple as that now we are pushing back the answer after the DFS traversal answer dot let us make this result because we are using answer inside or for each loop our for loop for the queries so as a result or pushback result or push back answer and then finally return oh I return the result let us try to end this is TMP it should be te MP temp no variable conversion from line number 35 string s Q of 0 it should be Q of I of 0 and Q of I of 1 so we are getting wrong answer for few of the cases let us try to handle them one by one so for the last case the answer is one it should be minus one why is it one for the last case that is because the edges that we are given here is let us try to make the graph first increasing the font size okay now we can create the graph a B and C from A to B the relation is to the weight of the relation is to from B to C it is three we are asked to find from A to C which is 2 multiplied by 3 is 6 we are getting this as correct then from B to a because from B to a there is no path the answer in our solution is minus 1 but it should be something else we are going to handle this a bit later then we have from A to E because E is not present it should return minus 1 and it is returning minus 1 from a to a it should return 1 from X to X it should return minus 1 in this case because X is not present so first let us handle the cases which are not present if I am dot find this start is not equal to m dot enter then only we need to call the BFS function if the start node is present then only call the DFS function that way we handled the last case now we are left with the case number 2 in the case 2 the answer should have been Oh point five but the answer is minus one in our case because there's no path from B to a but if a relation is of division type so if a divided by B is given B divided by a could be obtained actually a by B is same as 1 divided by B by a and vice versa so if we have B by a we can obtain a by B if we have a by B we can obtain B by a by simply doing 1 divided by a by B so these both should be handled in our map there should be a relation from A to B and from B to E as well but when we are creating a relation from B to a we should create this as one divided by the edge of it so this is handling the relation from A to B as well as from B to a so this is actually forming the complete graph ok it should be 1 and it should be 0 this is now computing the graph and it is going to answer each of our queries let us try to submit this it got accepted now let us talk about the space and the time complexity after that we will be discussing something about the channel so this e which is the number of equations let us say the size of this is M and there are queries there are let's say n queries if E is given as M we will have 2 into M edges we know that the time complexity of a DFS is e plus V big o of e plus V where V is the number of edges in worst case we could be as large as n Square where as n is the size of the number of nodes so if the number of V if the number of the node is represented by V e could be as large as v square so if the size is given as M the complexity will become big o of M in worst case and this DFS function is being called n time so it will be big-oh of n into M this is the will be big-oh of n into M this is the will be big-oh of n into M this is the time complexity talking about the space complexity first of all whatever we are using here if whether it is a map or it is a set of string we should declare this s unordered so that we have a constant time complexity now talking about the space complexity we are using map here Big O of n where n is the number of nodes or I should rather say Big O of V where V is the number of nodes so this is the space complexity now talking about the channel V we are creating separate playlist so first I thought of going in a company wise manner so creating the company playlist such as Microsoft Amazon Google over Facebook first I created these playlists but now I am thinking of making the playlist according to the topic so now we have a stack playlist a carafe playlist and I am thinking to create another linked list playlists so please suggest me that which method is better for you to utilize these videos whether they should be in a company wise manner or they should be in a topic wise manner for me it matters because when I'm creating certain videos I have a mindset that I'm creating this video for graph or I am creating this for specific company so that's how I proceed when I'm creating this playlist each week I will be focusing on a particular place and try to provide two or three videos to that playlist and then we will move on to the next one this is what we are doing parallel to this we will be uploading the solution to the VT contest and bi-weekly contest as well but this and bi-weekly contest as well but this and bi-weekly contest as well but this is the main focus as of now so that you can learn from this and then you can perform well in the contest as well as in the company interviews so please provide your suggestions in the description box thank you
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
1,833 |
hey everybody this is larry this is me going with q2 of the weekly contest 237 maximum ice cream bars so this one's a little bit weird to be honest my first instinct when i saw this uh was dynamic programming uh so hit the like button the subscriber and join me on discord let me know what you think but it turns out that because you can only buy everything once it becomes actually just greedy and sorting because basically you just want to maximize the number of ice cream bars and there's no other you know it's not a knapsack even though you know i guess in a lot of ways i'm conditioned to think about knapsack but uh but yeah you can just because they're all fungible they're all the same um you can just keep on buying the cheapest ice cream as possible and that's basically what i did um you know it i sold the car so that is we look at the cheaper ones and then i just go down the list um yeah as you know as long as we can buy the ice cream we buy it and then we spend the money and actually you can break the first time it doesn't but i just was lazy about it but yeah uh so what is the complexity well it's going to be dominated by the sorting and this for loop is just a linear loop and we don't use extra space unless you want to count sorting stuff but yeah so yeah n log n time constant space and there you have it you can watch me solve it live during the contest next hey yeah uh hope you enjoyed that explanation or video uh hit the like button to subscribe and join me on discord join me on twitch whatever you like drama and instagram i guess uh yeah uh i'll see you next time but stay good stay healthy and to good mental health bye
|
Maximum Ice Cream Bars
|
find-the-highest-altitude
|
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108`
|
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
|
Array,Prefix Sum
|
Easy
| null |
713 |
hey guys welcome back to another video and today we're going to be solving the lead cloud question sub area product less than k all right so in this question we're given an array of positive integers called nums and when we count and print the number of contiguous sub areas where the product of all the elements in the sub area is less than k so what does contiguous over here mean it's basically that we can't have a sub area which is 10 and then 6. the numbers have to be right next to each other so we can have 10 5 and 2 and so on and so forth as a valid sub area okay so in this case what the question is it's we have this as our array and we have a k value of 100 so the cumulative product should not be more than 100 or equal to 100. so in that case we have 10 5 2 and 6 by themselves since they're all less than 100 then we have 10 and 5 which when you multiply them gives us a value of 50 and 50 is less than 100 and similarly you also have 10 5 and 2 but so when you do 10 into 5 it's 50 into 2 100 is equal to our k value so it's not going to be a valid answer so in that case that is not going to be a valid sub area and we're not going to count it again we have 5 and 2 and then we have 2 and 6. then we also have 5 2 and 6 which gives us a value of 60 and yeah so those are going to be the eight sub-arrays that we have and that's eight sub-arrays that we have and that's eight sub-arrays that we have and that's what we output the total number of sub-arrays number of sub-arrays number of sub-arrays which have a product less than a hundred all right so i remember doing this question uh a very similar question to this and we're going to be using the same or similar method uh which is the two pointer method okay so real quickly let's just see how that looks like so over here we're gonna have two variables so we're gonna have a left pointer and we're gonna have a right pointer now both of these pointers are gonna start at the zero with index or in other words it's going to start at the first element now why are both the pointers starting at the first element and the reason for that is because the individual number itself also counts as a valid suburb so for example over here 10 by itself counts it's a valid summary and so on and so forth so 5 2 and 6 they're all valid sub areas so which is why we're going to start the left and right pointer at the same position all right so before we actually go through this step by step let's just go through the entire idea once so what's going to happen our right pointer here is going to be moved to the right we're going to keep moving this pointer of hours until the product whatever product we have so far is less than our k value once that product becomes more than our k value we're going to move our left pointer until the cave until our product becomes less than the k value and each time we move our right pointer over here we're going to add that movement to our count which is what we're going to end up outputting okay so now let's just go through the step by step so over here we're going to have one more variable called product and this variable over here is going to start off at a value of one and this is going to be used to count or keep hold or track of our cumulative product and finally we're going to have our result and this is what we're going to end up outputting and obviously our result is going to start off at zero since in the beginning we have zero sub arrays all right so at our first iteration what's going to happen is that our right value starts at zero and obviously our left value also starts at zero and the zero refers to the index okay so now what's going to happen is we're first going to account for this 10 in our product so to do that we're going to do 1 multiply by 10 and one is going to be the product that we start off with so 1 into 10 now gives us a product which has a value of 10. so over here we're going to check if this value is less than k it is less than k so in that case what's going to happen is we're going to go to our result and we need to account for the sub area so what we can do is we can just add one but that's actually not going to make any uh too much sense so what we're going to do over here is we're going to take the left value or sorry um we're going to be taking the right value subtract that with the left value and add that by 1. now the reason that we're doing this is so that we can account for each of the uh elements by themselves and all of its possible combinations so the purpose of this should make a lot more sense as we go through our iterations so currently our left and right are both at zero so zero minus zero plus one gives us a value of one so we're going to do zero plus one which over here just ends up giving us a new result value of one and that makes sense because we currently accounted for the sub area ten so now what's going to happen is we're gonna move our right pointer to the right so now this is the new location of our right pointer and we're going to do the same steps so we need to account for the 5 so 10 multiplied by 5 gives us a value of 50. now it's 50 is still less than 100 so now in this case we're going to do the same thing so right minus left so currently the right is at one and left is at zero so one minus zero gives us one plus one gives us two so now over here we're gonna add the value of two so that's gonna end up giving us a value of three two plus one equals three now how does two make sense so we already accounted for the ten so the two basically means that we're doing ten five so ten comma five is one sub area and the element five itself is going to be the other sub area so in this case we're accounting for both of those conditions all right so now we're going to move our right again so it moves over here let's account for that so 50 into 2 gives us a value of 100 all right perfect so 100 over here is actually going to be equal to our k value and this value has to be less than our k value right so now what we're going to do is we're going to move our left pointer so that our product over here becomes less than the k value so now we're going to move it by one so now our left pointer we move it by one and as we move it what's going to happen is that we're not going to be accounting for the 10 over here right since we moved it the 10 is not part of our cumulative product that we're counting over here so we're going to divide this 100 by 10 and that's going to give us a new value of 10 100 divided by 10 is 10. okay and over here we're going to check if this value is less than k it is less than k so that is going to be our new left value and we're going to stop and now we want to account for this in our results so to do that our right value is currently at two and left is at one so two minus one plus one is going to give us a value of 2. so now we're going to add 2 to our results so 3 plus 2 now gives us a value of 5. and that also makes sense because we have 5 comma 2 and then we have 2 by itself and finally now we're going to move our right over here so now this is currently at the very ending so what's going to happen over here is we're going to add this to our product so 10 into 6 now gives us a value of 60 and 60 is less than our k value but if it was not less than our k value what we do is we would move our left pointer so that it does become less than our k value so over here we have 60 and now we want to add that to our results so in this case it's going to be wherever the right is so it's currently at 0 1 2 3 and our left is at 1 so 3 minus 1 2 plus 1 3. so 5 3 gives us a value of 8 and 8 is going to be what we end up resulting outputting not resulting okay so that's going to be our final answer so yeah so now let's see how the code part of this looks like let's start off by defining our variables so over here we're gonna have our left pointer which is gonna start off at zero sorry okay then we're gonna have our results this is also gonna start off at zero and then we're gonna have our product which is going to start off at a value of 1. okay so now that we have this we're going to go inside of a for loop and this for loop is going to give us our right value and i'll call that r so for r in range length of num so we're going to be going from 0 all the way up to the ending of our nums list over here our first step is going to be to account for this new value inside of our product so to do that our product is going to be multiplied with whatever value we're currently on and to get that we can do nums and then r okay so now we have our product and over here we're going to check if our product is less than our k value so if product is less than or equal to our k value then in that case that means that we need to move our left pointer in order to decrease the value of the product so to do that we're going to be using a while loop and over here we're going to be having two conditions so the first one is while our product is greater than or equal to our k value and the second condition we have is while our left value or sorry l is less than or equal to our current right value so those are going to be our two conditions and the reason we're doing this is because our left value cannot be greater than our right value okay so over here each time what we're going to be doing is we're going to go to our product and we're going to divide that by the current number that we're on so to do that we're going to do uh divided by nums and then we're going to go to left value sorry l and one more thing that we're going to be doing is we're going to be moving our left pointer to the right by one so l plus equals one so that moves it to the right by one and in this case if right now our product is less than the k value in that case we're not going to go inside of this while loop again and we'll be done by it and by the ending of this we will get a new value for our left pointer and now what we're going to do is we need to account for that inside of our results so result plus equals and we're going to be doing the same steps so right minus left and the reason we're doing right first is because the right value is always going to be greater than or equal to our left value and we're going to do plus one so that is going to be the end of this and at the very ending we're just going to end up returning our result so let's submit this and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you
|
Subarray Product Less Than K
|
subarray-product-less-than-k
|
Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
\[10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6\]
Note that \[10, 5, 2\] is not included as the product of 100 is not strictly less than k.
**Example 2:**
**Input:** nums = \[1,2,3\], k = 0
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `1 <= nums[i] <= 1000`
* `0 <= k <= 106`
|
For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.
|
Array,Sliding Window
|
Medium
|
152,325,560,1083,2233
|
342 |
hello everyone Aaron here and welcome back to leaked code today we are doing the power of four problem given an integer n return true if it is a power of four otherwise return false and enter N is a power of four if there exists an integer X such that n is equal to x 4 to the power of x so here we say 16 is 4 squared 5 is not a power of four one is four to the power of 0. so that's those um the reason I'm doing this one in C today rather than python is because I don't want to do it the obvious way I don't want to try and take log four and then check that's an integer very close to it um I don't want to continually divide by four and see if I ever get down to one or anything like that what I want to do is I want to think about how 4 is represented or powers of four are presented on the computer so obviously every number is a binary number on a computer in one way or another so four is uh one zero all right like this now these are 32-bit all right like this now these are 32-bit all right like this now these are 32-bit integers so in fact there's one two three four five six seven eight nine ten 11 12 13 14 15 17 89 25 6 7 3 8 9 30 31 32 this is what a 30 32-bit integer of 4 looks like 32-bit integer of 4 looks like 32-bit integer of 4 looks like what about 16 well it turns out 16. in fact we'll do the first power of four which is of course one looks like this four looks like this 16. what's that look like well a 16 looks like sorry no that's not a four that's a two good grief um one two four that one is the four so this one here one two four eight sixteen the next power of four is this is zero one two four to the power of three that's four times four which is sixteen times four is eight times eight which is 64. so the next one is 64. and if I just quickly steal this what it actually is one two four eight sixteen thirty two so what we can see here is that it's the powers of four have exactly one in them and it's in the first third fifth seventh etc et cetera slots up this binary representation The Quirk is that they sell us a number could be negative but the good news is that powers are four always positive because no matter what you set X to four to the power of X is going to be a positive number so if n is less than or equal to zero return false there is absolutely nothing we can do else what we want to do is we need to do this check um there's what's the way to do this check well first off how can we check look there's exactly one bit set somewhere we don't care where it is at the moment just that there's one bit set and the way we do that is if we think about what uh well let's see what this looks like if we um take away one for example this looks like a zero so it's all zeros if we take away one from this these two turned into a one and so we see that this is all zeros down to here and this is all ones and the idea is that if we say let me do this with a much smaller number I have a much smaller number of bits let's do four again but this time only with um three four five six seven eight bits uh so four is this one three therefore looks like zero B one two that's three four and three yeah four and three is going to look like I need to space these out even further zero but what happens if we had say two a two looks like zero B zero one zero if we have three and two zero B zero one zero three and two is not zero four and three is going to be zero three and two is not going to be zero and actually this trick here um is true for all powers of two so I know we're doing powers of four but all powers of four are also all powers of two because four is a power of two um so the idea is that is power of two this is if we take n and come and end it with n minus one and check that is equal to zero if that's true then we know it's a power of two and so that means if it's Power of Two the powers of two are all of these but they're also all the ones with this skipped bit filled in as well so all we want to do is return is Power of Two and uh no let us know correct it is set so this is where we need to check that it's the correct bit set so we want to do in and we want it to be we know n only has one hang on I'm saying this badly let me try this again so if this then we know n has exactly one bit else return false so now what you want to do is we want to check whether that one bit is in the right place so the right places is zero uh the binary representation of well hang on what's the largest one here uh I'm just trying to work out whether this is going to be a well hang on let's do one zero oh God it's a very long way of doing it hang on um let me do the octal version one and oh um zero o is one four is oh four sixteen is oh one oh good grief this is difficult um hang on let me just stick a zero on the front of this that's one two three four five six seven eight sixteen twenty four thirty two um if in and right places if we look in all the right places and we see something that is non-zero return true else return false this thing's gross and I'm not 100 sure that's valid C syntax let's find out apparent it is validity syntax excellent and this seems to work so let's use all the example test cases excellent works for all of them so one works because we showed this up here one minus well as it's positive so we pass that check one and zero is zero so it has exactly one bit set and then the one lines up with this one here so it's got the one in the right place um before we go any further this can absolutely be tidied up because there's only one happy path and that happy path is when n is greater than zero and N minus one is equal to zero and uh when in and right places is greater than zero all of that logic there is here it's a power of four if it's positive and it's a power of two and it's one of these specific powers of two that we have all together let's just double check that still works to really compact this down you would probably work out what this is as an integer and then just put it in line here but it's fine as it is let's hit submit see what happens um pretty fast so this is obviously a well too low for it to actually make any meaningful measure of its speed basically this runs instantly its memory use is absolutely powerful the course but that's expected almost every solution is going to be running in approximately the same amount of time so sorry for the slightly dodgy explanation but hopefully that made sense it's quite a cool little program this one all it does is some bit shifting and it can immediately tell you without any Loops at all whether a number is a power of four that's it from me for today thank you very much for watching Remember to like comment subscribe all that good stuff let's make the YouTube algorithm happy and I will see you next time bye
|
Power of Four
|
power-of-four
|
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_.
An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`.
**Example 1:**
**Input:** n = 16
**Output:** true
**Example 2:**
**Input:** n = 5
**Output:** false
**Example 3:**
**Input:** n = 1
**Output:** true
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Bit Manipulation,Recursion
|
Easy
|
231,326
|
1,481 |
Welcome to my channel code Sorry with Mike So today we are going to do video number 27 of Greedy's playlist. Okay lead is marked number 1481 medium but will make it quite easy. Three different approachable number of unique int's after removals means you will get a You have to find the least number of unique integers after removing the elements, meaning the least number of how many unique numbers can you get by removing exactly the elements. Okay, let's understand by looking at the example. Look at the first example, this one is yours, it is given that k = 1, first of all, is yours, it is given that k = 1, first of all, is yours, it is given that k = 1, first of all, tell me how many number of unique elements are there in this array, one is seeing five and the other is four, that means total number of. How many unique elements are there? Total number of unique elements is two. Okay, so it is saying that there should be at least unique elements, so you can kill k dilly, maximum is okay, so if you look now, notice that this means 1. Now you can delete one element, if let's say you deleted five, then there are still two types of unique elements, five and four. The count of unique elements is still two, but if you had deleted four, then So see four has disappeared right now see how many unique elements are there in this Hey, there is only one, the frequency is two, isn't it, but there is only one element, this is five, okay, how many number of unique elements are there, only one, that is five, which is already It is better, I want the least number of unique elements, then the answer came that we can bring one unique element, we can bring up to one unique element, the meaning of unique element is that here we are not talking about frequency one, here we are talking about How many different types of numbers can you bring, this is the minimum, so first remember, there were two types of numbers, one was five, one was four. What did we do this time, we made it five by deleting the four, so a little bit from here. You must have got hint one about which I will also discuss with you in the approach. This is where you must have understood what you have to do actually. Okay, so let's come to approach two. Sorry, let's come to example two. Look here, pay attention. k = 3. Meaning, you just first Look here, pay attention. k = 3. Meaning, you just first Look here, pay attention. k = 3. Meaning, you just first tell me how many unique number of elements are there in it. One, I see four, one, I see three, one and two, total how many unique elements are there, total unique elements are counted. The count of types of elements is four, total four different types of elements. Okay, so I have to reduce it because four is a very big number, can we bring even less unique elements? Have you given three dishes, can you kill three dishes, okay? Look, if we assume that you have deleted two, then I have deleted two, k = 2, who else deleted two, k = 2, who else deleted two, k = 2, who else can be deleted, let us assume that you have deleted four, okay, k = 1, okay, k = 1, okay, k = 1, you have also deleted 4. You have done it, not th, but delete two. Okay, you have one more left, you can delete one more and kill, so you assume that one has been deleted. Okay, so now look at us, what has happened? Three is one. There are so many different types of elements, here one is visible three and one is visible, see how many unique elements there are only two unique elements, earlier there were four different types of elements, now there are two different types of elements. There are only elements, so our answer is two, okay, it is clear till now, let's build our mind, how will we solve this problem, understand the thought process, then look at us, pay attention, let's assume k = 2 and this is your input, okay if. k = 2 and this is your input, okay if. k = 2 and this is your input, okay if. You just see what is the current situation of this, I have four different types of elements, one is four, one is three, one is one and one is two, so how many unique elements are there, different types of elements are four, okay so now. Look, if we assume that you thought that you will delete the three, okay, you deleted the three, your K value becomes one, now you can hit one more dish, let's say then you decided that you will delete the one, then your It has become zero, but now let's see what is confined in it, still I can see four types of elements, four are left, this one is left, this is three left and one is two left. So there is still no benefit, the k = two that was no benefit, the k = two that was no benefit, the k = two that was given to you was of no use, you deleted the wrong element, so now see why I got it wrong because look, first of all you deleted three, neither three Even after deleting, you are seeing that three more elements are left, so why do n't we first delete those who have come less number of times, that is, those whose frequency is less because if you delete them, then the whole of them will be destroyed very quickly. They will become because their frequency is less. Okay, so whose frequency do I see the lowest? First, let's write down the frequency. The frequency of four is one. Look at the frequency of three. Three is very high frequency. Its frequency of one is two and frequency of two is one. Right, this has become my number and this has become my frequency, so whose frequency is the lowest, I am seeing the lowest frequency, four is okay, so first I will delete four, so if I deleted four, how many elements are there in 4? The frequency of 4 was one, so I deleted one element, so I made it -1 in k. Okay, after that, I made it -1 in k. Okay, after that, I made it -1 in k. Okay, after that, who has the lowest frequency? After that, what is the sub-section frequency of two? How much sub-section frequency of two? How much sub-section frequency of two? How much frequency is one, meaning if I do one element, then I will do this. I will choose 2 because its frequency is less, so let's see the value of k is one, that means it can be deleted now, so yes, I will choose 2 to delete, then k has become zero, now I can't delete anymore, now I see, my hey now. How is it visible to me, how many types of O elements are visible, one is visible, three are visible, one is visible, only two types of O elements are visible, so this time look at the four types first. Now there are two types of elements, so there are two types of unique elements, this is your answer. If you want the least number of unique elements, then what is your intuition built here that pick the one having lowest frequency, the one with lowest frequency will be selected first, as if we assume. If the value of my K had been more and I could have deleted it, then whom would I have caught? I would have caught the one because look at its frequency, it is two, but yes, it has a higher frequency, that is why I have not caught it first, hence, I would have caught the one first whose frequency was Lowest, understand what it means that you should sort. Sort the frequency in ascending order. The smallest frequency will be done first, followed by the bigger frequency. This is ascending order. Neither do you care about the frequency nor do you care about the number. What do you care about the number? It means how much element is to be deleted, so you just store the frequency. How is it? Otherwise, first of all, in the map, I will see what is the frequency of each element. Here, the frequency of four is one and the frequency of three is one. The frequency of two is two, the frequency of two is one, so what did I do, these are the frequencies, I store them in one, I am fine, the frequency, the first frequency was one, after that it was three, after that it was two, after that it was one, these are the three frequencies, this is There were four frequencies. Now what did I do? I sorted them. Why in ascending order? Because I have to pick the lowest one first. Okay, now I don't care whose frequency it was or whose frequency it was, it makes little difference to me. It doesn't matter to me what is the frequency, so I am not storing which element has this frequency, right? We mean frequency, so when you sort it, first comes one, then comes two. Then three has come, ok till now it is clear ok 0 1 2 3 Remember our k was two so it is obvious, first of all which one will I delete, I will delete this one, then k is one, then I will delete this one, here one is k. It's done, okay, so now look, pay attention, I have been able to delete only this much of the elements, so how many total unique elements are left, this is the frequency of one type of elements, this was the frequency of the second type of elements, this is the third. This was the frequency of type of element. This was the frequency of fourth type of element. I deleted two type of elements using k. How many types were left. Two types were left. Which was one type whose frequency was two and which was one type whose frequency was three. I mean by type, how many unique types are there? If you look at the total size, then 1 doti of this frequency is 4 four. How many types have we deleted, two types have been deleted, 4 - two, our answer is two deleted, 4 - two, our answer is two deleted, 4 - two, our answer is two types are left, right? Who were those two types? The frequency of one was two. The frequency of one was three. Let's see who they were. Two were of frequency one and three were the frequency. These two were left. I have deleted the ones with smaller frequencies, so it is not even clear. Okay, so this was our first approach, this was our approach number one, in which what we did was store the frequency in the map, okay and then sorted the frequency C in ascending order, after that simply start deleting, is it clear till now? How much is its time and space complexity complex? So, it is clear cut that if you are sorting here, then it will take your time. n l n. This is in the worst case, and if the space is for storing space complexity, then the worst case. Our space will be equal to the number of elements. Let's assume that I had a total of unique elements. Okay, there were unique elements, everyone's frequency was one. If we go by the value, then also see the size of the frequency ones. It will be the same and in the map also all the elements of N will be gone, then in the worst case our space will be of A space. Have we done what we told above to tell? Okay, first of all I had to store the frequency in the map. The frequency of F. Two is four, frequency is one, then I put the frequencies in sorted order in frequency one. Okay, the smallest frequency is one. After that, frequency two is put in sorted order. Okay, now look, pay attention, I said that every one I will go to the frequency and start deleting, so the first frequency is one, that means there must have been any element whose frequency must have been one. Okay, so I hit delete, how many elements did I delete? If I deleted one element, then k is equal to minus two, sorry. How many elements are there minus the number of elements in this index? Was there a frequency of elements in this index? There was this much frequency, so I have minus the number of K. Okay, so let's see what is the value of the element. What is the value of the element of the next element and the minus frequency of and that is. It has become zero, it has become one, it has become zero, okay, so what if it has become zero, will you return it now? No, you will not return it now, because if you return it now, then look, pay attention, what is the frequency dot size? There are two and now you have deleted it currently, haven't you currently deleted it, so now I said that frequency dot size minus you are up to the current index, now mine aa, if you do then see what will happen. The value of my aa is zero, so it will be returned to ga, whereas when it was deleted, this one frequency was 4, so the answer should have been one, it is right that only one element should be left, only this one with two frequency is ok. We will put such a check here, let's say if k is, if the lesson has become zero, then we can send frequency dot size minus aa, see what will be the benefit of it, let's assume let's look at this case, right? Here k was the minus frequency of e so k was only 1, my minus frequency was one -1 became 0 so the frequency was one -1 became 0 so the frequency was one -1 became 0 so the value of k became row so now k but lesson is not 0 right so that is why what will happen i will move ahead Again I did the same k = k my frequency aa remember the did the same k = k my frequency aa remember the did the same k = k my frequency aa remember the value of k had become zero so 0 - 2 became value of k had become zero so 0 - 2 became value of k had become zero so 0 - 2 became -2 this is ok so pay attention to one thing what -2 this is ok so pay attention to one thing what -2 this is ok so pay attention to one thing what happened this time that k lesson has become 0. Na k lane is 0 then what will I return k frequency d size - aa so return k frequency d size - aa so return k frequency d size - aa so what is the size of frequency see minus aa two minus aa's value is one then one is left and that one is left only this is ok till now clear When it is done, that's why I said that we will put this check. By putting this check, we will be saved from this corner case. Okay, otherwise you can handle it in other ways, but this is the cleanest way, isn't it? You handle it like this, so let's go. Let's code quickly and finish this approach. Let's code quickly. First of all I told you that you must store their frequency. Un ordered map of int comma int is ok. In this I will show the frequency for int and. x in array m of Remember MP, what was the first element? It was an element and the second element in the map is its frequency. So, what I mean by frequency is just the frequency under the back and second. Okay, the frequency which I stored in the map. Now what I had to do was to sort the frequencies in ascending order. Okay, we sorted it. Now there is nothing, it is very simple. Int i = 0 i is the lesson very simple. Int i = 0 i is the lesson very simple. Int i = 0 i is the lesson frequency d size one by one. I will go to the frequency of all the elements i + frequency of all the elements i + frequency of all the elements i + p. I will go to each frequency one by one, so first of all I will delete the first element k mine i is the frequency of i, I have deleted all the elements that were there, but what we had to do is check that if k is my less then 0 now if you can't delete it then return it frequency dot size - aa what will happen with this frequency dot size - aa what will happen with this frequency dot size - aa what will happen with this how many more unique elements are left it will be returned ok but if k has never become 0 then do you know what it means What happened that you deleted all the elements and you came out of the for loop then return zero no elements were left all deleted so no unique element left all got deleted let's see after submitting we should be able to pass All the dis cases, after that we will come to our second approach. Look, it has been passed. Now let's come to its second approach. Now let's come to approach two. Look, approach two is no improvement. Same time completion on approach one, every time. We wanted the frequencies that were smallest, then we wanted the one after that, and then we wanted the one after that. Remember what we did, we sorted the frequencies in ascending order right so that we processed the smallest frequency first. Delete them. Okay, so you want a small element every time, then the one after that, then you can achieve the same thing with Priority Queue, something like this is a very good approach. It is the same, we just changed the data structure, there we stored it in frequency and sorted it, this time we stored it in priority queue and what does priority queue do, it keeps it already sorted. If min priority is taken then what will it do? We will keep the smallest element at the top, followed by the one that is bigger than that, then the one that is bigger than that, so already it keeps it sorted, it is fine for us, so what will we do, we will create frequency, which means that of all the elements in the map. We will store the frequency, let's assume that frequency is one, frequency is two, frequency is three, why will we put them in priority, okay and since priority one, which one are we taking? The smallest frequency will be at the top, after that the bigger frequency will be there and so on. Okay, we will process all the frequencies one by one. Okay, so what was in approach one was that we had taken a frequency array and sorted it. What we are doing in approach two is just taking a simple priority q and processing the elements from it. It is also ok if you look at the time complex t, then remember first we had taken a map, all the frequency elements in the map and Frequency was inserted, after that we picked up all the frequencies and put them in Priority A. If you insert the time completion in Priority A, it takes log of n time, where n is what is the current size of priority. If q is the worst. In this case, the size of priority q can be n and due to the value, we have inserted n elements. Let us assume that the frequency was n. What was the frequency n? So if you insert all the frequencies, then n will be n, our time complexity will be In this too, because if seen indirectly, you are sorting, then what is happening if you insert it in priority why and that at the end, it is sorted internally, okay, so whether you solve it from approach one or approach two. Solve it is exactly the same approach, just in this we have chosen a different data structure, why is the priority okay, then the code is exactly the same, just we will not take the frequency array and sort it, we will simply put it directly in priority K and what will happen to me in priority K will be min heap. If not, then let's solve it with this approach also, after that we will come to the third approach which is time completion. After that, remember that we had taken a frequency array, added frequencies to it and then sorted it. We will not do this time. What will we do this time? What did you say that we will take priority, okay int comma vector of int p, we know what it is, actually this is your max heap, to make it min heap, you either write lda separately or put a greater int here. Give it will be converted into min hip, so I write this min hip has become mine, okay, now what will we do, we will pick all the frequencies in auto end it in map and put all the frequencies in the graph and push it dot. Remember, second was my frequency and eighth was my first element, right in the map, now you will put this for loop frequency, now you will put this while loop, why is it in priority, right, until priority k is empty d MT. Okay, it is clear till now, so we will do the same thing by p minus it's frequency of a and we will top it with p. What will happen by topping it? I will pick the smallest element, I will pick the frequency and will subtract it from k If the less day becomes 0, then I will send all the remaining elements in priority k currently p kdot size in the return because look at the rest, I am seeing p cuds popping and getting deleted which I have mentioned here. Removed, okay, the number of elements left in the last priority is the same number of unique elements left, so here I will return all the sides, okay, and why are you returning zero outside because all the elements would have been deleted. If you never hit return in the while loop here, then it's ok. Let's submit. Let's see. We should be able to pass all the test cases. This was a simple approach. It was exactly the same as approach one. Now let's look at our third approach. On your approach three, which is also saying from the time complexity of n that we will be able to do it, let us see what is your approach, if you pay attention then what do you need to know ultimately, you need to know how much brother, which ones. The frequency is mine, I have it, let's assume four, that is, it has come once, three, that is, that has come three times, one, that is, that has come twice, two, that is, that has come once, so I told you, right, we only have frequency. So all we need is to mean the frequency, okay and okay, we mean the frequency, right? And now pay attention to one thing, how many elements are there whose frequency is one is visible, its frequency is one is visible whose frequency is It means one, what I am saying is that how many elements have frequency one, number of elements is written here, there are two elements whose frequency is one, so you can also deduce from this information that how many elements will there be in total. Off frequency is one and there are two such elements, so there will be 2 * 1 2 total two elements, so 2 * 1 2 total two elements, so 2 * 1 2 total two elements, so brother, from this also you can find out how many elements there will be, that is, this data is also enough that you can find out how many elements we will have and let's see. Is frequency e 3 frequency equal t 3 how many people are there let's see the frequency th I only see this means there is only one element right here what I am writing is the number of elements and here I am writing who is the frequency. C is the frequency of one. How many elements are there whose frequency is one? There is only one element. Sorry, there are two elements whose frequency is one. The frequency is three. How many elements are there whose frequency is three. There is only one element whose frequency is three. Okay and let's see. The frequency is one, the frequency is three, the frequency is also two. How many elements does one have whose frequency is two? I think there is only one element whose frequency is two, so I write one in the count that there is only one such element whose frequency is two. If the frequency is one then this information is also enough. Now from this information you can find out. Look, tell me what can be the maximum frequency of any element. Brother, it is possible that element is complete, only that element is present in it. If the size of this array is n then the maximum frequency of any element can be n or a, some may have frequency one, some may have two frequency, some may have three frequency and so on maximum frequency. There can be n of any element. Okay, so here what I said is that frequency one is of how many elements, it is of two elements, so I wrote that frequency one is of two elements, so remember what it was, this is my frequency, how many. Frequency is and this is my number of elements, how many such elements are there whose frequency is two, which element is there, it does not matter to me who is the person whose frequency is one, it does not matter how many such people are there whose frequency is one. It does not matter, I have to find out the count only, 2 1 2 is not a frequency, okay and there are two elements which have a frequency, then 2 * 1 will be two elements in total, and am * 1 will be two elements in total, and am * 1 will be two elements in total, and am I getting the number of elements? Neither is enough, I have this much information, okay, frequency a three, which is frequency three, only one person had it, okay, so I went to frequency three and put a here, what does it mean that frequency three was of only one element and You know who that one element is but it doesn't matter to you, whoever it is, the frequency is only one element, it is three, it is okay, now let's see the frequency two is of only one element, it is one, okay, this is You have collected the information, now what is the benefit of this formation, ca n't you easily find out from this information how many elements are there, like look at this, its frequency is one, its frequency is two, its frequency is 1, so already it is sorted, isn't it? How many such elements are there in i and one frequency? If there are two elements then 2 and 2, there will be total two elements. If there is one element with two frequencies, then 2 and 2. If there is one element with three frequencies, then 3 1 3 then 3 2 p 3 there will be seven elements. Look, actually there are seven elements, one is Doti Ch 4 5 6 7, so I am trying to tell you that yes, this information is enough that how many people are there according to frequency A, whose frequency is this one, this is two A. So on, you can store it, so I have already told you that the maximum value of frequency can be n for any element, okay, so what will I do, I will take one of n + 1 size, okay? take one of n + 1 size, okay? take one of n + 1 size, okay? If you take a size of n+ 1 then obviously it is 0 1 If you take a size of n+ 1 then obviously it is 0 1 If you take a size of n+ 1 then obviously it is 0 1 2 and so on, the value of n will go up to it, okay and here I will store it or keep in mind that this is the index which is it denoting the frequency and what is the frequency. And the value, do you know what it is telling that how many such elements are there whose frequency is one, how many such elements are there whose frequency is two and so on, it is telling that it is ok, so how many elements are there whose frequency is one, how many elements are there whose frequency is two. So I put two here. Frequency two was of how many elements. A was of one element. I put one here. Frequency three was of how many elements. If it was of one element then I also write frequency three here. I was of one element so I put one here. I have put that the frequency is of the th one element, okay, it is clear till now let's see how easily we can solve it using this data. Yes, don't forget how I would have populated this. Okay, I have n+ 1. Hey, I took the size and Okay, I have n+ 1. Hey, I took the size and Okay, I have n+ 1. Hey, I took the size and must have populated it from the map. Remember, I had stored in the map that whatever is four, has come once. Whatever is three, has come thrice. Whatever is two, has come twice. So this is frequency one, so here I went to frequency number one and I added one here, now let's assume that everyone's value is zero, okay, everything is zero now, okay, I just came here, frequency three, so I am in frequency three. I went there and made it + 1, I am in frequency three. I went there and made it + 1, I am in frequency three. I went there and made it + 1, I said that there is an element whose frequency is three, frequency two came, I said that there is an element whose frequency is two, again it came with frequency one, so I said look, I made it + 1 so I said look, I made it + 1 so I said look, I made it + 1 here, that is, two. There are elements whose frequency is one. I understood how I would have populated it. Okay, now let's move ahead. Before moving ahead, let me explain one important thing here separately. Let's take one test case each and see. Let's assume. Hey, we have 11 1, okay, this was our Hey, and k il two, let's say 4, okay, so now what will you store in this here, what will you store in this Hey, that it has four frequencies, how many four frequencies? Of the four elements, there is only one element whose frequency is four. Yes, one, no, do something else. 3 33 Yes, there is only one element, three, whose frequency is four. I have written the same here, right, I am here. That's what we used to store, isn't it? There is only one element whose frequency is one, so now pay attention to one thing. Let's assume that it is not k. Let's assume that it is not four. Let's assume that if it is eight, then it is okay, then pay attention to one thing. There is one element with two or four frequencies. There is one element with four frequencies. Who is that? That is three. Okay, now look, pay attention to how many types of elements can I delete. Let's see how we will find out. The value of k is eight, right? How much frequency is four, right? So what does it mean that I can completely delete two elements whose frequency is four? Okay, two elements whose frequency is four, what am I saying? If there was 3 and one more element whose frequency was four, then we can delete both of them because the value of k is eight, right, and I have two people with frequency four, here there are two people, right k. My value was eight, so what I did was, I saw that I can delete eight people and how many frequencies do I have. If I have four frequencies, then how many people are there whom I can delete. There are two such people and who are those two people? There is a group of three, a group of four, okay, this is what I want to tell you, but look, what is our case here, brother, I have only one person whom I can delete, there are only three, right, but I have only three. But what power do I have that I can completely eliminate two such people, right? And then look at this carefully and understand, here I divided k by what, which is the value of frequency by four, so what does it mean, what does k mean? How many people can I delete? Four means people whose frequency is four, then how many people are there whose frequency is four. Do k ba 4. There will be two people whose frequency is four. I am capable of deleting those people. Because the value of my K is A but I saw that there is only one element whose frequency is four so no problem I will delete this one. Okay so what does it mean that I can delete elements of the type equal to my original value. I am that one but I have the ability to delete two people, so brother, whatever it means, delete that one, otherwise I will take the minimum, there is no problem with both of them, okay, that means I have the power to delete two such people, but my value is if one. It means there are only three, so I will delete these three. And what is ok, I will take the minimum. Now this thing is clear. Now look here, if you calculate the total number of elements, how much can I delete? Hoon by frequency is four, isn't it four? Let's see how many elements are there whose frequency is four. 88/4 That is two. Okay, so let's see how many elements are there whose frequency is four. 88/4 That is two. Okay, so let's see how many elements are there whose frequency is four. 88/4 That is two. Okay, so let's see how many elements are there whose frequency is two. Originally there are two people like this and I am trying to delete two people. If I am capable for this then it is ok, I will delete both of them one by one 4 5 6 7 8 all will be deleted ok then what will happen in the case minimum of k ba 4 comma which is the original value I have for this frequency, meaning I have stored You must have decided that how many elements will there be for frequency four. Okay, so k ba 4 is my two. For frequency four, if there were two people, then the minimum of two will be only two and that is correct. I can delete two people, two like this. I can delete people whose frequency is four. Look here, the minimum of what is one means there is such a type of person whom I can delete whose frequency was four and that is three. Okay, the most important part was this. For this, here I first find out the number of types that I can delete. Remember what I said that minimum of total number of elements that I can delete right now, can I delete by right now, which one in the current frequency? I am seeing, so I will write this frequency here because I am moving the index here and remember these were my frequencies. Okay, so what does it mean that I can delete a total of so many elements and this is the current frequency. What I am looking at means I can hit delete on so many types of elements. Remember, I had explained the same thing here, what I meant is that I am looking at the current frequency four. This is my current frequency. Okay, and K is my total. The number of elements that I can delete means that I can delete two such people whose frequency is four. So the maximum that I can delete is two such people, that is, I can delete such elements whose frequency is It may be coming but actually how many elements do I have, that is, actually how many elements do I have whose frequency has come, I will take out the frequency of from here that actually I have so many elements which I can delete, so many types of There are elements which I can delete, okay and this is the maximum I can do, I will delete the minimum of the two, okay, it is clear till now, okay, you must have understood this, now look, pay attention. So actually how many people will I be able to delete k = k minus Now look, it is delete k = k minus Now look, it is delete k = k minus Now look, it is very important to pay attention, the number of types which I removed is okay, do you remember the frequency of each type, what was the frequency of each type, it has come, right, because I Now I am looking at the frequency of these elements that I have deleted so many elements. Look at what I actually did. Look at this earlier example to see what I removed. How many types are there that I am capable of deleting? Minimum of k. / i k mine was four, ok, Minimum of k. / i k mine was four, ok, Minimum of k. / i k mine was four, ok, how much frequency am I looking at four, comma frequency of four, how many types are there, this is the maximum possible value, no, sorry, the value of k was eight, here the maximum possible, I am so many types. I can delete people whose frequency would have been four and how many types of frequency four are there currently. If there is only one type, then yes you will be able to delete only one, otherwise the type has become one, meaning there is only one person whose frequency would be four. And if I can hit delete on all four of them, then how many deletes can I hit? k minus how many types of people are there? If there is one type of people, then what is 1 in one? What is my type? I found a type whose frequency was whatever frequency. I see, this was a very important part, k minus type in aa, so here I wrote the number of types, people of so many types whose frequency has come, then I am capable of deleting so many people, till now it is clear, okay. Now you are remembering one thing, remember that in the map, we have stored all the elements, so how many unique elements are there. Look, one 2/4 is a total of elements are there. Look, one 2/4 is a total of elements are there. Look, one 2/4 is a total of four unique elements. Can you say that there were total four types of elements, you had four different ones. There were types of elements out of which how many number of types have I deleted, so I will reduce here, I will reduce by counting the unique A's, unique element type equal to minus equal to how many types have I just deleted. Removed so many types, removed number of types, removed so many types, if it is clear till now then everything must be clear. Now look at one last thing, let's take this example through an example, this will help you understand one thing. Okay, so this is my Hey, it was based on values and you had stored something based on values and you had stored something based on values and you had stored something like that brother, my frequency is four, how many elements are there with frequency four? There is only one element whose frequency is four, okay, it must have been understood that there is only one such element. Whose frequency is four, then I have something like this. Oh, frequency must be made like this, then leave it. Natu 3 four and so on. There is only one element of frequency four, rest all are zero. Okay, now look, pay attention. Let's assume that you are here right now, so I told you how many types of elements you are capable of deleting that I can delete. That's right. I told you after mean is equal to mind of. What is this but there is 4 comma which is the current value. How many types of elements? Type is I have frequency of current frequency, let's see how much will come, how much is the minimum of, three is 3 children, then look what came, minimum of 3/4 is then look what came, minimum of 3/4 is then look what came, minimum of 3/4 is zero, this is one, minimum of zero is there in both, okay Now one thing is very important to pay attention to, this part is very important to understand that brother, you know that it has become zero. Do you understand that it means that you cannot delete any type, you cannot completely finish it because there are three, see, you will delete all three. So that type is still left, it is not finished, it is extinct a little, you could not make the entire type disappear, here we are talking about deleting the type, okay, you could not delete it, you know why this happened because the frequency of the current is very high. The current which has come is four, the frequency which has come is no, the current which is coming, the frequency is four and you know that it is smaller than the one which is sold, it is either smaller or equal to two, that is why this happened, brother, tell me one thing. You could have deleted three elements. Okay, you could have deleted three elements, but the frequency of the current element is four, so the lesson is equal to two. So, it means now you cannot delete any more and you cannot delete the types. If you can, then it is as much as the unique element. It is okay to return the same amount as the unique element. Okay, now look at the value here, even if k = 4, then see what would have even if k = 4, then see what would have happened. The value of frequency k is four, how much is 4/4? It has become one, right? The frequency happened. The value of frequency k is four, how much is 4/4? It has become one, right? The frequency happened. The value of frequency k is four, how much is 4/4? It has become one, right? The frequency is one. Okay, so what will be the minimum of both? It will be one. Okay, so what does it mean that I can delete one type of element, I can completely eliminate one type of element, see. That's right, the whole type is finished. Okay, so when the whole type is finished, remember what we wrote here, the minus types of 'e' are in here, so let's see types of 'e' are in here, so let's see types of 'e' are in here, so let's see what will be the value of 'k' in that case. In my k it's minus number of types how much can we delete one type n into how much is the frequency of that type four is 4 so look pay attention what was my four was minus f became zero okay now look pay attention Dena ke hai zero is done, that lesson is equal to the current four. Okay, so see in this case also it worked. Okay, so what does it mean that when will we return here when the ke jo hai is less than equal to the current frequency. Because if the lesson becomes equal to the current frequency, it means that it cannot eradicate that type any further, that type will remain, so what I am saying here is that even if the lesson remains equal to the frequency, it is okay. So we will return only the amount of return unique element that is still left because look, this is a very basic thing, I have explained it in more detail but it was very basic, see what is this line, let us assume that it is 3, okay. = Three and let's okay. = Three and let's okay. = Three and let's assume the frequency of any element was five, let's say 5 is not F, take any example, let's say six was 6 Now see this which is 3, delete maximum three people. If it is possible then it will be deleted, then it has been deleted but this type has not been finished yet, it is still existing, the entire type has not been finished yet, so this type will still remain in the unique element. Either it would have been the case that this ch would have been only three. Okay, so when you delete these three, look, if you had deleted them, then it would have been updated here, not e unique elements minus e number of types, after that see k my row is done. It happens because if I delete these three, then 0 is equal to the current frequency. How much is the current frequency? When there are three, in this case also we will return because then we cannot hit delete now. Okay, this thing should be clear. It meant a lot, even after failing one or two test cases, I was able to understand the flow of this approach later, because I also made a mistake, only after that I went to the correct approach. Okay, and lastly, what to do outside the for loop. It's nothing, just return, if you are not able to return here, then inside the for loop, it is a very small code, but there were a lot of things to explain and according to me, the most important line of it was this, it is good to understand. And this was and this was this part of it which is if condition k le equal to frequency why we are going to return because now you cannot delete that type again, we had total number of unique types was four, right? One was four, one was three, one was two, right? We ca n't delete the other types because the current frequency itself is bigger, my k is greater than k is equal to two, isn't it okay, so let's finish it. And let's code it live and remove this approach of ours, it is fine till the map because we have to store the frequency of all the elements in the map, till this point it is fine, after this I know, remember I told you? Vector of int We will keep a count of each frequency this time that corresponding to some frequency I give that frequency of count of aa means do you know what is the number of elements i.e. you can either say types i.e. you can either say types i.e. you can either say types having frequency e equal to aa okay This was an important part. Now remember, instead of saying unique elements, you can either say types, how many unique elements are there or how many unique types are there. We have as many elements as we have in the map. Okay, I have so many unique types. Now what do we have to do? Have to populate auto and it in map ok int frequency e ad second frequency got it now what I will do is go to the index of that frequency and hit it plus one I got the element whose frequency is this frac ok till now Is clear ok now let's start for int frequency ev will start with frequency lesson e a maximum frequency can be this much right ok frequency plus let's understand everything till now the toughest part is here first of all I this I will find out that brother, maximum how many unique types can I delete, okay and how many unique types are currently available to me, for this current frequency IF, okay, that is how many types I can delete, okay, how many types can I delete? Types I can delete, how do I find out by frequency, how many elements are there whose frequency is frac and I can delete, that means so many elements, I can hit delete, okay and how many elements whose frequency is frac, so many types. I can hit delete as maximum possible but currently how many types are there, they see the frequency count of the number of types, of the frequency count of the number of types, I have so many types, I will delete the minimum of the two, okay, and after that let's hit delete. Is k e's minus equal to two. Look, remember who is being deleted, so many types are being deleted and what is the frequency of each type. Is it a break? Neither is it into a break, that is why it is important to understand every line. It is a very good approach. Actually it is fine and I also came to the correct solution after making two or three mistakes. Okay, till now I am understanding. Now look, pay attention, I had kept the count of unique elements here, how many unique types of unique types I had. Initially, now how many types have I removed, so many types have been removed, I have deleted them, it is okay and at any moment, if k lesson is equal to the current frequency, it means that in future, this delete will not be able to kill any other type, it will not be able to kill any type by deleting it, right? It is possible that an element can be deleted but it cannot delete any type. When the entire element is deleted, only the element with a particular frequency will be deleted, but now the type cannot be decreased because see k which is the particular current frequency. It has already become small, now going forward the frequency is going to get bigger, frequency plus, so how will we be able to delete the entire type, so stop at this point, return only the unique type that is left, ok, this is a very good solution. This is off n, but yes, it would have been a little difficult to think, but now if you understand this type of funda, then it will become very easy for you. Look at its time complexity, is it off n? There is no need for sorting anywhere, okay here. We have not defined n let's take int n eed size ok I hope I was able to help any doubt raise in the comment section I will try to help or see next video thank you
|
Least Number of Unique Integers after K Removals
|
students-with-invalid-departments
|
Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
**Output:** 2
**Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
**Constraints:**
* `1 <= arr.length <= 10^5`
* `1 <= arr[i] <= 10^9`
* `0 <= k <= arr.length`
| null |
Database
|
Easy
| null |
343 |
welcome to joey's tech in this video of my dynamic programming tutorial we'll look into the integer break problem which i have taken from the lead code website you can find the link in the description box below this video i found this problem really interesting and what makes it more interesting is that we can solve it using dynamic programming let's now see its problem statement the problem statement is very simple and easy to understand you are given an integer n you need to break this integer into those k positive integers the product of which comes out maximum when n is equal to 2 you can only break it into 1 and 1 the product comes out as 1 now when n is equal to 10 if you break it into 3 and 4 then you get the product as 36 which is what we need to find out you will see how to find the solution using the dynamic programming technique in mytp framework but before we move there i urge you to subscribe to my channel and hit the bell icon so that you get the new videos the moment i release them now let's switch to the framework check this arrow over here the size of this array is n plus 1 i am considering n is 10 as you saw previously so there are 11 cells in this array we will fill this array and the last cell over here is going to give us our solution let's start filling this array now what i am going to fill in this cell indexed by 0 consider n s 0 can we break it into any integers no right so i populate 0 in this cell ok we move ahead now n becomes 1 can we break 1 into any integers no again so in this cell i'll populate 0 again n becomes 2 now 2 can be broken into one and one by breaking i mean finding integers the addition of which is two the product of one and one will give me one only does i populate it here in this cell now n becomes 3 we can break it into 2 and 1. we have the value for 2 stored here in this cell but can we use it no because the value in this cell is 1 and not 2 so you have to remember that whenever the value in a particular cell is less than its index then you use the index and not the value this logic will be more clear once we solve the next few sub problems similarly we are not going to pick this value for 1 because it is less than the index so we are going to pick the index which is 1. the values which we will consider are two and one it is simple logic the product will come out as two so i populate it in this cell three can be broken into the addition of three ones also but the number of integers that it can be broken into has to be greater than 2 we saw the condition k is greater than equal to 2 in the problem statement let's move ahead n becomes 4 in this sub problem we start backwards from here the first index we encounter is 3 subtract 3 from 4 we get 1. so we need to look at this cell indexed by 1 and this cell indexed by 3 observe that the values in them are less than their indexes so the product will not be legitimate so in these special cases we have to take the product of the indexes like i told you before 3 multiplied by 1 will give 3 so let me store 3 in this cell first we move one step back from here we reach this cell the index is 2 subtract 2 from 4 we get 2 that means the value we get from here will be multiplied with itself since the value in this cell is less than its index again hence will consider 2 as the value from here 2 multiplied by 2 will give me 4 if i compare 4 with the value already available here which is 3 then i'll have to populate 4 in this cell as 4 is greater than 3 and we are looking for the maximum product let's move one step back we get to this cell which is indexed as 1 subtract 1 from 4 we get 3 but we have already done it a while ago so let's skip it and move to the next sub problem which says that n is equal to 5 so we are going to start from this cell previous to 5 and we are going to go all the way back to 1 in order to find the maximum product when n is equal to 5. so let's start from here we have the index 4 over here so 4 subtracted from 5 is going to give me 1 that means i'll have to look at the value stored in this cell indexed by 1 okay which is 0 but since the 0 is less than the index so i am going to use the value 1 from here and what is the value stored here in 4 we have 4 already and this is not less than the index so i am going to use 4 and 1 so the product of four and one will be populated in this cell which is four we move one cell back now we have three subtracted from five is going to give me two so i'm going to consider this value as well as this value but since both of them are less than their indexes so i will consider the indexes so the product of 2 and 3 will be considered 2 multiplied by 3 gives me 6 which is greater than 4 so i will store 6 over here and then if i go 1 cell back i'll reach here 2 i subtract 2 from 5 i'll get 3 again we have already done it so this iteration will be skipped let's go one cell back to 1 and one subtracted from 5 is going to give me 4 we have already done that so we are going to skip that too all right so we have the value calculated when n is equal to 5 let's calculate the value of this sub problem when n is equal to 6 so we are going to start backwards from this cell once in previous to this cell for which we are finding the solution okay subtract 5 from 6 we get 1 so what value we are going to get from here it will be 1 so i will multiply 1 with the value which is stored at this cell indexed by 5 is 6 so i will multiply 1 with i'll get the value 6 which i am going to store over here all right i go here 1 cell back so the value over here is 4 but first i'll have to subtract 4 from the 6 so i am going to get 2 i will get the value 2 from here so here the multiplication will be 4 multiplied by 2 i will get 8 is greater than 6 so i am going to capture 8 in this cell we move one cell back to this particular cell indexed by 3 subtracted from 6 is going to give me 3 again value over here is 2 which is less than the index so i am going to consider 3 here so the product will be 3 multiplied by 3 so 3 multiplied by 3 is going to give me 9 is greater than this 8 so 8 will be replaced by 9 all right we move one cell back we have 2 when i am going to subtract a 2 from this 6 i am going to get 4 but that particular multiplication has already been done so i will move one cell back i have 1 over here i subtract 1 from 6 so i'll get 5 that particular step has already been taken care of so i am going to skip this iteration as well so we have the value calculated for n equals to 6 which is 9 the maximum product when n is equal to 6 will be 9. let's consider this sub problem now n is equal to we are going to start from the cell we are going to go all the way back to 1 so 6 subtracted from 7 is going to give me 1 so i have the value 1 from this in and the value 9 from this cell so 1 multiplied by 9 is going to give me what 9 i'll do 9 over here okay i move one step back i have 5 over here 5 subtracted from 7 is going to give me 2 so i get 2 from this particular cell and i have the value 6 over here so 2 multiplied by 6 what it is going to give me 12 which is greater than 9 and remember we are finding the maximum product here so we are looking for the maximum values so i will store 12 over here 9 will be replaced by 12 okay we move one cell back we have 4 deducted from 7 is going to give me 3 so i will get the value 3 from here i have 4 over here as the value so the multiplication of 3 and 4 i will have to calculate which will be but i already have 12 over here so it doesn't matter if we replace it they both are the same we come over here 3 deducted from 7 is going to give me 4 but that thing has already been taken care of so we need to skip this particular step i move one step back i have to subtract it from seven is going to give me five i have already taken care of that step so i'm not going to go into that anymore now i will move one step back so i'm going to get 1 subtracted from 7 is going to give me 6 that particular step has already been taken care of so 12 is the maximum product that we are going to get when n is 7. all right let's quickly calculate the values of these three sub problems so n is equal to 8 i start from here 7 subtracted from 8 is going to give me 1. so 1 is the value which i am going to consider over here and 12 is the value i get from here so 12 multiplied by 1 is going to give me 12. i go one step back to this cell all right 6 subtracted from 8 is going to give me 2 so over here the value which is going to come out will be 2 multiplied by 9 is going to give me 18 is greater than 12 so 18 replaces 12. one step back we go again so here i have 5 subtracted from 8 is going to give me 3 the value which will be given by this particular cell will be 3 multiplied by 6 is going to give me 18 is already there so it doesn't make any difference cool now i go one step back again so 4 subtracted from 8 is going to give me 4 so 4 multiplied by 4 is going to give me 16 but 16 is not greater than 18 so 18 stays and 16 doesn't affect our solution now if we go one step back then we are going to get titrations which have already been taken care of so i am going to skip these three iterations all right because 3 subtracted from 8 is going to give me 5 and that particular multiplication has already been taken care of you just saw that so we are going to skip that 18 is the maximum product that we are going to get when n is equal to eight each of these cells apart from these three each of these cells represent individual sub problems and if you are observing then you know how we are making use of them let's move to the next sub problem where n is equal to 9 so we are going to start from this cell we are going to go backwards from this cell 8 deducted from 9 is going to give me 1 what value i get from here 1 what value i have here 18 multiplied by 1 is going to give me 18. great now we move to the cell 7 deducted from 9 is going to give me 2 what value i am going to get from here 2 what value i have over here 12 multiplied by 2 is going to give me 24 is greater than 18 so 18 gets replaced by 24 all right i move over here i have 6 subtracted from 9 is going to give me 3 i am going to consider 3 from this set the index 3 multiplied by 9 is going to give me 27 now 27 is greater than 24 so 24 gets replaced by 27 we are going so good now i come over here so 5 deducted from 9 is going to give me 4 i have the value 4 over here i have the value 6 over here 6 multiplied by 4 is going to give me 24 but 24 is not greater than 27 so that value will be skipped it doesn't make any difference to our solution i move to this particular cell so 4 deducted from 9 is going to give me 5 but this particular iteration this particular calculation has already been done so we need not worry about it similarly i am going to skip all these iterations because they have already been taken care of all right we move to our final sub problem which also happens to be our problem here n is equal to 10 so we are going to start from here we will go backwards from the cell previous to our final sub problem we have 9 over here 9 subtracted from 10 is going to give me 1 the value which i am going to get from here is 1 multiplied by 27 is going to give me 27 and i will put 27 in this cell all right i come over here 8 deducted from 10 is going to give me what 2. so over here i am going to get the value as 2 which is the index and what is the number i have over here it's 18 so 18 multiplied by 2 is going to give me 36 now 36 is greater than 27 so i populate 36 in this set let's go to this particular cell one step back one cell back i have 7 over here so 7 subtracted from 10 is going to give me 3 i have 12 over here which i am going to multiply with 3 so that is going to give me 36 again so it is not going to make any difference to my solution because i already have 36 over here i am going to go one cell back to 6 so 6 deducted from 10 is going to give me 4 i have the value 4 over here and i have value 9 over here 9 multiplied by 4 oh it again gives us 36 but 36 is already over here so it doesn't going to make any difference how many cells are giving us the same value that's incredible let's move one cell back to this particular cell i have 5 over here and 5 subtracted from 10 is going to give me 5 again so this value will be multiplied with itself i have 6 over here and i'll multiply it with 6 and there you go i again get 36 so i have 36 over here so it's not going to make any difference i move one cell back to this particular cell 4 subtracted from 10 is going to give me 6 but that particular calculation has already been taken care of so i am going to stop here now and i am also going to declare 36 as my solution so we have solved this problem if you want to check out the solution to this problem then i am giving my github link in the description box do check it out but i recommend that you solve this problem on your own first with this we have come to the end of this video i hope you enjoyed watching this video i hope you found this problem interesting i look forward to help you with programming and algorithms and until the next video goodbye and take very good care of yourself
|
Integer Break
|
integer-break
|
Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers.
Return _the maximum product you can get_.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** 2 = 1 + 1, 1 \* 1 = 1.
**Example 2:**
**Input:** n = 10
**Output:** 36
**Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36.
**Constraints:**
* `2 <= n <= 58`
|
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
|
Math,Dynamic Programming
|
Medium
|
1936
|
45 |
everyone welcome back and let's write some more neat code today so today let's solve jump game two so you might remember recently we solved the first jump game problem and i would recommend watching that video or solving that problem yourself before looking at this one because this one is actually very similar the main difference is we are the premise of the problem is the exact same we're given an integer array of non-negative an integer array of non-negative an integer array of non-negative integers they're always non-negative and we are they're always non-negative and we are they're always non-negative and we are placed at the first index of this array so let's say this is our input array we're going to be placed at the first index over here and our goal is going to be over here the last value in the index that's the goal and our goal is to jump to the last position from the first position in our integer right in this problem though the question we're trying to answer is what is the minimum number of jumps that it takes for us to reach the last index and luckily for us we can always assume that we're always going to be able to reach that last index so in this first problem we know that we're starting here right in this two position if we take so since we're at the position two we have two choices right we can either take a jump of length one or we can take a jump of length two our choices are these two values the three and the one if we take if we reach the one then we take one more jump get to the second one and then we take a third jump to get to the four which is the goal right the goal is the four the last position of the array or if we go to the 3 instead then we actually just take a jump of length 3 to get to the 4 which means that in this case it'll take us exactly two jumps right we go from two to three and then we get to the goal so that took two steps two jumps and our output can be two because we're looking for that minimum number of steps so you might know that this is a problem that can be solved with dynamic programming just like the first jump game solution but i'm not really going to go over the dynamic programming solution because actually just like jump game one this problem also has a greedy solution and it turns out that the greedy solution is a linear time solution so oh big o of n whereas the dynamic programming solution is actually big o of n squared so we know that with this problem we can make a some kind of decision tree right we know that this first position right two it has two choices right if we're jumping from this position right we can jump to the three or we can jump to the one right so those are our decisions right so really from two we can get to these next two values the greedy solution is going to be something similar to a breath first search type solution right so next so we looked at this value right this two that was the starting position and we saw that these are the next values that we can go to from there right we're going to continue this process that's why it's kind of like a breath first search because we're going to be continuing this exact algorithm what we're going to be doing though now is we saw that from here we could get to these next two values now the next question becomes from this entire portion of the array what are all the other values outside of this portion that we can also reach let's take a look at that from this three we know we can reach this next one right but that doesn't count because it's already a part of our green area right we can reach that one but it's redundant because we can already get to this part we can also get to this next one right so that's going to be at the next level or the next part of our breadth first search we can also reach the destination which is four right at this point we would normally be done with our algorithm because we know that we can reach this four and we've basically found the minimum number of steps that allow us to do that but we're going to continue with this just to understand the algorithm so we know that from this 3 we are able to reach these two values let's just continue it just to see okay this one we also need to check what are all the positions it can reach well in this case it can only reach this one and that's already included in our purple area okay so now we see that this purple level is what we can reach from the green level these portions and the whole reason i'm color coding this is because the levels tell us how many steps it takes to reach these cells the minimum number of steps right we know that we start at this position right therefore the number of steps it takes to reach this position is zero right it takes zero jumps for us to reach this position how now my question to you is how many steps does how many jumps does it take to reach the green uh values it takes exactly one jump right that's the whole point of color coding it because we know from two we can jump here or we can jump here it takes one jump for us to reach any of these values if we're taking the minimum route right we're taking the minimum number of jumps now next what about the purple values how many jumps what's the minimum number of jumps that it takes for us to reach these well obviously it's two because if it takes us one jump to reach these green values and we can take one jump from the green to get to the purple it's going to take one extra jump to get here so it's obviously going to be two jumps right this is pretty simple this is a pretty straightforward algorithm we would continue it if we had more values in our array but as you can see what we're doing here is basically through a simple or a one-dimensional through a simple or a one-dimensional through a simple or a one-dimensional array breadth-first search we are finding the breadth-first search we are finding the breadth-first search we are finding the minimum path or the minimum number of jumps to reach the destination right remember we only care about the destination once we reach the destination we are done so in this case we can see it takes exactly two jumps for us to reach the destination so this is the visual explanation but now hopefully you get the idea of what we're doing the colors hopefully can illustrate that and we're going to translate this into the code it's very little code the code is actually pretty straightforward let me show you how to do that part now that we know the breadth for search algorithm so remember we are counting the number of jumps it takes to reach the destination we'll call that result we'll initially set that to zero i'm also going to have two pointers left and right and they're both initially going to be set to zero because these left and right pointers are going to tell us our window we saw that initially the window starts at just 0 right the first initial value so that's what it's going to be we know that i think the second level was where left equals 1 right equals 2 right so this would represent a window from index 1 all the way to index 2 and that's basically this is basically going to determine what level of or what portion of the array is going to be used for breadth first search currently and we know we are going to continue this algorithm until right which is the rightmost value of our current portion until it reaches the last value of the input array so while our right pointer is less than the last index we're going to be continuing our algorithm and keep incrementing that result so just for visual purposes uh what i mean by the left pointer is that let's say we're currently going through the green our left pointer would be here because it's the left most value of the portion we're going through our right pointer would be at the rightmost portion so that's great last thing is how are we gonna determine the boundaries for the next portion well what we're gonna do is we're gonna look at who can jump the farthest the three the farthest jump it can make is one two three right the farthest jump it can make is to this value the one the farthest jump it can do is just a one so it can get here right so what we're going to do now to update our pointers is we're going to take our left pointer and set it to right plus one right it's gonna be adjacent to the right pointer so this is where our left pointer would go where's our right pointer gonna go it's gonna go to the place that we can jump the farthest right it's going to go to the right boundary of our purple area so we're going to cross this out and put right over here the reason we're putting it over here is that's the farthest position that we can jump to from the previous section the green section so now let's get back into the code so we are going to have a variable farthest which is going to tell us who can jump the farthest and what's the index of that jump so right now we're going to go through our portion you could say we're going through our green portion so for i in range uh from left to right plus one because we have to make the right value inclusive so going through this loop all we're trying to determine is who can jump the farthest because that's going to determine how we can update our left and right pointers so what we're going to do is just set farthest equal to the max of itself and the max of the jump that we're currently performing so i is the index that tells us the jump we're performing so we're jumping from index i so i plus the value at index i which tells us how far we can actually jump so nums of i plus i is going to tell us what's the look what's the farthest location that this could jump to and so we're going to take the max of this and then update that farthest variable by the end of it we should be good farthest should be set to what the farthest it can go is and then we can update our window right so we can say left is now going to be equal to right plus one just like i showed in the picture right is going to be equal to farthest and don't forget to increment the result each time because remember that's telling us how many jumps we're taking to get to that end point so once you're done with this that's actually the entire algorithm after that all you have to do is return the result so what we're doing here is basically uh a simplified breadth first search it's we're doing it on a one-dimensional on a one-dimensional on a one-dimensional array and we're using a left and right variables to keep track of what our current window is we're also updating that window as we keep progressing once our window or in other words our right pointer reaches the last value in the input array that's when you know that we're done counting the jumps and we can stop our in our loop and then we can return the number of jumps that we took the minimum number of jumps so i hope that this was helpful i hope you have a visual understanding of this problem as well as understanding the code and thank you for watching uh don't forget to like and subscribe if this was helpful and have a great day i'll see you pretty soon
|
Jump Game II
|
jump-game-ii
|
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i + j < n`
Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** 2
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[2,3,0,1,4\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 1000`
* It's guaranteed that you can reach `nums[n - 1]`.
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
55,1428,2001
|
52 |
hey everybody this is larry this is day five the june nico day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm okay uh that's weird right isn't it um this is literally like yesterday's form but now we have to do the count instead um in theory there are optimizations that you can do to make it slightly faster but i think given that nine factorial right um what is 9 factorial is like 36 362 000 so i'm not going to worry that much about optimization um there are i'm yeah i don't think there's much i don't know i'm going to do the lazy thing today actually to be honest um and i do go over how this code worked from yesterday so definitely check out that video if you're here um i don't think i'm gonna spend that much time on this one today uh just because i don't know i would like something more particular um that's a little bit sad though but one thing that you can do and i'm just going to copy and paste a little bit because to be honest is i don't know why they did it this way oh sorry leco um but yeah but here all we have to do is just do right and that's pretty much it i believe uh there are more optimizations that you can have fun with but i don't know oops and again we can there's only nine so we can just test all nine uh oh i forgot to run the code so it's gonna be wrong whoops click on subscribe accent uh oh i don't even need to board right yeah i don't even need to board in fact i got rid of it anyway so i will um oh i forgot the type finished typing it but then i gotta i was looking at the other thing uh yeah i mean uh oh that's weird actually oh i guess i changed it in the last yesterday's yeah i mean obviously you're seeing me just being really lazy and kind of going through it but yeah apparently also the only 252 cases i think i missed it yesterday but knowing that of course in the future you would just have a cache right or like you would have a uh an array of nine numbers and then just return it so you don't even need to do that's an optimization that comes into place from time to time so i think less rare or more rare these days with respect to um you know because p depending on how they do it but uh in terms of the number of problems i see uh but yeah i mean i don't know i don't really have much else to add for this one other than that for yesterday i suppose um i think i forgot to talk about the interview uh which is that these things do or they used to come up a lot um so definitely study around it i would say uh yeah i mean i think this is just standard recursion stuff so yeah uh that said i think in general you know you're probably not going to get something maybe i'm wrong about that one depending on the company but just the idea of kind of thinking about states how to kind of do the backtracking how to make a change and then rewording that change and making sure that you have places and a good thing then uh yeah and then the other question is well can you um can you dp this right and the answer is actually i wasn't thinking about it yesterday but the answer is technically maybe yes um i mean for nine items it's not going to matter but um and it may be too expensive anyway for any real numbers but for columns used for example well first of all the way that i would think about it if you want to think about whether things can be uh dp'd was what was going to be 0 to 9 inclusive so that's 10 numbers columns used will be i mean i used to set but you can think about it as a binary um uh binary bit thing or just like a uh an array of boolean values right true force values so that's going to be two to the nine uh diagonal is gonna have the same logic except for i guess they're more diagonals right because for a nine thing uh wiping my eyes i gotta stop doing that but i think they're about two to the two times nine diagonals so it's gonna be about two to eighteen give or take i mean i think that's like two to 17 maybe even you want to be more specific um but yeah so then now i look at these states when i go okay uh these are the number of states and number of states of course it's just this times this which you can see very quickly that this is not doable so those are the things that i would think about in terms of dynamic programming uh of course this one uh you know you do the maven is nine factorial and it should be okay but you know but that's only for this input right so i think that's one thing i would say as well i mean that let's say we don't keep track of diagonal right then now we can let's say we get rid of these parameters well now uh the reason why we had these parameters is that we can um you know that we optimize this part so that we can enter these two queries in constant time but if you want to convert them back to uh you know linear and the size of n then well in that case then now you're caching it one way forward your states are fewer but each state will do more work right so then now in that case let's say we don't have the diagonals one number of states is uh what was it 10 times 2 to the nine and each state now does uh n times maybe n work say so 10 times 10 work um i get this number because this is 10 for each column and then maybe another you know another loop to see if there any diagonal conflicts so then in that case you do the math and it's like okay maybe this is dp about but you have to think about the states that you care about um yeah i think that's what i'm going to say about this one for today um i know that there's a little bit maybe i'm going a little bit fast as well and this is a bit to absorb um so one thing that i would maybe urge you to do if you're doing at home and i'm lazy today so uh or maybe i just want to you know for those of you who wants to you know challenge yourself after you did yesterday's think about or implement this using dp i mean i already kind of gave you a little bit of hints maybe i should have paused a little bit first for the spoiler but yeah so that's pretty much all i have uh let me know what you think the contest for me the weekly contest is in about an hour and a half so good luck to yao and good luck to me please uh yeah that's all i have uh hit the like button hit the subscribe button join me on discord remember discord is free so come join and post your code and you know just uh do stuff together anyway stay good stay healthy take your mental health i'll see you later and take care bye
|
N-Queens II
|
n-queens-ii
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_.
**Example 1:**
**Input:** n = 4
**Output:** 2
**Explanation:** There are two distinct solutions to the 4-queens puzzle as shown.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 9`
| null |
Backtracking
|
Hard
|
51
|
35 |
hi guys and welcome again to my channel in today's video i'm gonna start um a new series uh in which i will be solving uh in each video like uh one lead code problem and i'm going to show you how i'm going to explain the question for you and we're going to solve it together uh also like just to mention that lead code is one of the leading uh resources that you can use to ma while you're preparing for any technical interview that you might have there are different languages supported and different topics and i highly recommend that you guys go and start practicing over there so in today's problem i'm going to be uh solving a search um search question let me share my screen with you okay um all right so today's problem is called uh it's number 35 and it's search insert position it's ranked as easy so uh this ranking guys it's very good um way of uh like categorizing the problems in when you are uh like starting to practice for uh or preparing for an interview you can like move from easy medium to hard don't only focus on hard questions because uh most probably you are gonna get like two medium and one easy question that's usually the scenario and maybe in like uh in their cases you would get a hard question and a medium question and like another hard question so uh try to be uh like dive play to span your uh questions from easy to medium to hard and not only focusing on one category all right so today's uh question is uh called search insert position so the question uh body says giving a sorted area of distinct integers and a target value so we have a target value and we have a assorted eddy what do we mean by sorted ide we mean an array that starts from uh like in a descending or ascending order usually when they say sorted array it's usually ascending order so it increases as we move to the right so return the index if the target is found if not return the index where it would be inserted to make the order like works what do we mean by index means the position that the number holds in an array so here guys if take a look at this array we have one three five six elements in it uh the value is one the index is zero here the value is three the index is one here the value is five and x is two so indexing start from zero index means the position so the location where the element is so not like arrays can hold any values so they can have numbers they can hold strings whatever and the values like the type of them is um different than the index is the location and it's usually from zero if the index starts from one the question would specify so or the domain would say oh the indexing starts from one but like in most uh and like 99 of the time it starts from zero so um the question want us to return the index of the target if it's found if not to return the location it would be and if it was to be inserted all right let's take a look at the example they gave us so our array called nums it has these values the target is five we would go over that a and when we find the 5 we would return the index that 5 was found at so 0 1 2 the index is 2. the location that five was found at is two over here the array holds one three five six the target is two we would go over the uh the array looking for the target which is two we didn't find 2 but we want to see where it would be inserted such that the array remains sorted so 0 holds the value 1 two holds the value three two falls below then three and bigger than one so it should be inserted between the one and the three and this way when we shift one position to the right the index that two would be inserted at is one okay this in this previously hold which value it hold it there it holds the three all right the third example they give us one three five and six the target is seven is not here okay so where would we i add it seven is bigger than all elements and it's bigger than the six so we would insert it after the six which in this it would be after the six so zero one two three it would be index four okay so um here they give us some constraints saying that the number should be uh a delay value uh bigger than the one and it should be a ascending order and it should be distinct values so we not have any duplicates inside this array okay so how would we solve this question guys first of all we would need two pointers one at the beginning of the array and one at the end of it we would call it as left and right the left pointer would hold which value the index where for zero so the lift pointer would be pointing to the one element but it would be at index zero the right pointer would be at the end of the day right which would be which index so guys how would i know how many elements is inside my array i would use something called len which is the ln method and i would pass my array in it and then what this would return for me what guys it would return for me for okay so the result for this method call with b4 however the index is what is 4 minus 1y because we're starting from 0. so 0 1 2 3 so the right index would be minus 1. okay now what would i go what would i do i'm trying to go over the array such that i will be looking for my target okay so while that's how we would deter it while my left is less than or equal to my right okay what would i do i would be looking for the target now how would i know where is like uh like where is my target um either i would do the brute force way i would be tricking every single element of the array or i would be using binary search which means that since the array is sorted i would be starting from the middle okay when we start from the middle guys because i know any element in the array anything on the left of it is less than it anything on the right of it is bigger than it because it's sorted so we have to specify a third pointer called the middle index and this pointer would be the middle so it would be left plus right minus left over two okay now in order to um avoid fractions we would do like this in python and this way we would get uh like a full number okay so like the middle point here would be um 0 left 0 plus three over two all right now if target now what would be checking we would be checking the middle element so if target equals to the middle element this is guys basically um binary search question if it's element it's equal to the element at the middle index we would just simply return the middle index if we meaning if we find the element at the middle point then we're done like we found our target we already found the target so we returned the index that it was found at this is the scenario here we found the five okay and the five is in the middle so it returned two and that's it now the other scenario if what if um if the target is less than the middle point so if target is less than the middle point then what would i do guys so if i know that my target is in the left section of the array okay if in the left section of the what which point i should move the right or the left pointer so here i know the tool is in this section it's not here does it make sense to keep going over the whole array like here it's a simple example we have only four elements but when we have like 100 uh elements in the array would it make sense to go all over n when we could go over n over two so we would move which pointer we would move the right pointer so instead of having the right pointer pointing at the six we would have the right pointer pointing at the three so right equals the minus one now if the element is not less than the middle point it's bigger and it's not equal so we would move which pointer we would move the left pointer so instead of having the left pointer pointing at the one we would have been pointed at the five so else left equals to middle plus one the reason why i am um adding one and subtracting one is because i'm like we already checked the middle point so we want to check the next one to it or the one before it so it doesn't make sense to stay at the point this way we're not moving anywhere okay now if it's uh after we like check all the f and l's if we didn't find our element which index we should return guys so here we didn't find the we didn't find the element 7 we want to insert it and we didn't find it we want to look for it and we didn't find it which index we should return that the 7 would hold if it was to be added over here now take a look at the y here the y left is less than right so the moment the left becomes bigger than the right because here we're adding to the left and subtracting from the right the moment the left becomes bigger than the right this is when my loop breaks and stops iterating so this is when i am exiting the loop and that's the index the moment i exit the loop the index at the left is the one that i should be returning so return left so basically i start with two pointers i go over the left this then the right and then i calculate the middle index here just simply to get uh like a full number not a fraction and then i check if the target is equal to middle if not if it's equal the if it occurs in the left section or if it occurs on the right section okay so the left section which is the less the right section which is the bigger and then after i finish with the loop i exit and just one second and if we run the code we have the final result so if we input one three five six and if we wanna uh look for the five the index would be two okay that's the index that the five is at okay um this is it for today guys um this is an easy problem in next videos i'm gonna be going over uh medium and hard air problems i would be like moving shuffling all around these types and uh in i recommend you create an account elite code and you practice yourself thank you very much for watching make sure to subscribe and like this video if you wanna keep getting like um like notified about my new videos alright thank you and have a good day
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
297 |
hello friends today wealth of serialize and deserialize binary tree okay actually the problem asked us to use a string to represent a binary tree and then we convert that string to banner tree again so that's the two functions well we call it a civilized actuaries convert tree note the two string another function is the other functions coded Tisserand vise we convert a string back to user tree note so let's see oh well as it is a binary tree problems the simplest solution is usually use that first search and usually we will use some help functions because we need to return string and string is quite complicated in Java so usually we will use we will simply use a string builder as a parameter so we will use a help function we call it a pewter string and it has two parameters one is the tree node of course another is a string builder we carried so as it is a def first search problem solution we will have base case the best case is if the root equal to now we append some character to indicate it is a nun I use this shop you can use other character even six or seven works so we append the shop and we also append a comma why because we use this coma as a separation character for the future use so if we are not now we will enter the recursive case we appended this route of value and we appended is comma and we do it recursively we build a string to the left or no to any to the right node so it is actually a pre-order traversal it is actually a pre-order traversal it is actually a pre-order traversal okay so we finish the civilized function now let's go to the DS youren nice function we pass a string we call it a data so as I mentioned before the string is not quite easy in Java so we can split this string by the separation character comma so we can get a actually string array but arrays is a fixed size so we can convert it at you list now we have a list of string why should we use a little string because every time we just needed to carry it is the first character because we put it in a pre-order manner so in this case we a pre-order manner so in this case we a pre-order manner so in this case we needed to recover the tree we just need the first character if we equal to the shop will return now otherwise we built a root node from that integer and we built we recursively built its left node in the right node in the annual return node so for this beauty tree how function we only have one parameter which we call it at least actually the string list okay now let's write the code so for the 0 nice we need a string builder we just call it SP new string builder and we pass it to the build strength pass route and the SB vana route SB to string okay now let's write a private void build string this is a tree node root string builder we called SP so the best case if the root you caught you now what should we do we should s be a panda the shop and the common the we return otherwise the SP will append the current route Wow and the SP will append a comma and we view the stream routed are left SP and we build stream route all right SP okay we finish this part so for this your own eyes we use a linked list why because owning linked list has a master removed first so we call it a string list we call it linked list as we know there are visibility to this they'll have either a common we will help us array so we will convert it to a list so we use this method erased as Lisa there will be dead house bail it up by the comma okay so now we will return buuuut tree we pass the string list okay so private she know the Butte tree it is linked list string we call it a string molester okay so we get the first string list to remove first we tell whether you quote you the shop if first equals to the shop we return now otherwise it has an integer value we build the route new tree node we get an integer value of the first and then the root at all after you go through the Builder tree string yes to enlist and the route at all right you go to build tree string list finally we just return the root SM we finish it okay thank you for watching see you next time
|
Serialize and Deserialize Binary Tree
|
serialize-and-deserialize-binary-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 a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
**Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
**Example 1:**
**Input:** root = \[1,2,3,null,null,4,5\]
**Output:** \[1,2,3,null,null,4,5\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000`
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
271,449,652,765
|
482 |
hey everyone welcome back and today I'll be doing another delete code 482 license key formatting and easy one you are given a license key represented as string s that consists of only alpha numeric characters and dashes the string is separated into n plus one groups by n dashes you are also given an integer K we want to reformat the string as such that each group contain exactly a characters except the first group which can be shorter and by K but still must contain at least one character furthermore there must be a dash inserted between two groups and you should convert our lower case to uppercase so we have a key and uh K integer so every group should contain K character so K is for the groups are in four you can see divided but there is an exception to the very first key uh with a first group which can be shorter by KS so K is equal to two other groups are 2 but the first group is two so we'll be starting off by making our whole string uppercase and then we want to remove the replace the dashes okay just remove the dashes and we'll be making our string reversed because it makes sense to start from the very end because we have a free hand on our very first because there can be less characters on the very first group but there can be less characters on the very last so we'll be reversing it and starting from the very end and making a list so for I in range of you will be starting from 0 till length of s and we'll be using KS tabs so now we will just result.append result dot append and will be appending by slicing our string to from I to I plus K and then we can just return a dash by joining it with our result and of course reversing it because we started with the reverse string and that's it there is a wrong answer why is there a wrong answer yeah that's it
|
License Key Formatting
|
license-key-formatting
|
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`.
We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first group, which could be shorter than `k` but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.
Return _the reformatted license key_.
**Example 1:**
**Input:** s = "5F3Z-2e-9-w ", k = 4
**Output:** "5F3Z-2E9W "
**Explanation:** The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
**Example 2:**
**Input:** s = "2-5g-3-J ", k = 2
**Output:** "2-5G-3J "
**Explanation:** The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of English letters, digits, and dashes `'-'`.
* `1 <= k <= 104`
| null |
String
|
Easy
| null |
269 |
hello welcome to my channel today we have leeco 269 alien dictionary and this question is rated as hard but it's really uh helpful for learning the algorithm let's take a look at this question so there's a new alien language that use english alphabet however the order amount of letter is unknown to you so basically saying that english alphabet we have a to z and a is smallest and z is biggest so that's the alphabet order but in this alien language you have the same rule but different order so what's that mean is we can take a look at the example one so we have we compare uh the first one and second one and you see the first two is the same so yeah it's harder to tell which one is faster which are smaller then you compare t and f that means t is go earlier than f so now we look at um w and e right here compare this to you see the w go earlier than the e so let's mark it down and e go faster than e yeah the same so now we look at the different one which is r and t right here so it's say r is earlier than t so this is a crew that we find by comparing one by one now we compare this and this so we see r is uh bigger than e so e go faster go earlier than r so that's what we have in here so now how do we know the order for this one so only the w doesn't have any in degree so any of the other one have in degree like r the in degrees e what's in degree mean if t is smaller than f then f will have one in degree so only w doesn't have in degree that mean w should be the earliest one so now we have w go first so now we know e is go later we put e right here and what's e we have r go after e so just say we have r after e and look at r then we see t like a t we have f and this is the order that fulfill all this condition right here and it cover every character in this array so that means this is the right order and you see this output right here and we make this as a string then we output this that's how it is for this question but what we need is we need something to store this information first let's take a look at the drawing so now we have this right here what we need is we have a hash map that taking uh look at this one for first we look through the whole entire words and pick every character in here to put it in the map so we have w in the map and the we'll put the empty set right here to store anything behind that behind the w right here so we have r for sure we get every character in this map as a key so we have t this is t right here and this recover w r is cover and we have f is done we have e's r is gone e has it t we have t and we i think we cover everything in here so this is all the key for the hashmap we give it all empty set right here we also during this time we also need to look through we have something called are in degree table or just say in table to capture for example if we have 26 index 0 will be a and two c so in this case um we have for example we have f so we go to f the location of f increased by one e increased by one t increased by one r increased by one so that's uh all the compilation and we get all this table right here this is two things we need to have uh before we move forward uh later on so now let's build this one right now let's build this two thing uh first and let's see how we do it later let's erase this one and now we have here let's make this first because this question is pretty long so i will try to make it character we have set character as a map so we have the map right here and also we have an in-degree in degree 6 in deck uh first thing we need to do uh is build uh the table that we have which is the hashmap uh we it's called build map and we will call a function build grid new map is how we build it later after we build it and we will do the dfs you get the right order so df and the dfs will return the correct uh order so we just basically return dfs in here so for this build map we will need to put in words and map and in degree so let's take a look at this one right here this step right here first um probably boy i think it's boy yeah boy uh we call build map that take in string array of words also map character set character which is called map we also have in degrees or in degree this is the function and it doesn't do anything but just um put everything uh we try to build this map and also build the in degree in here for this function so first thing we have double loop what we do is we look through the whole entire words to capture every individual character like what we said we capture the individual character let me draw one more time to build those um put it as a key so we can put the lady later character for that key okay that's what we do now so we look through the whole entire words and another for loop for every character c in that words uh we will put that in the map and map.put if and map.put if and map.put if absent so that if that's absent then we put it in there so what we need to put in will we have c which is that character every individual character and we will put the empty hash set in there as the value so now we have an empty template right here so next thing we're gonna do is come here remember we have the like t to f and w to r that comparation how do we come up this comparative combination is by looking through this one by one and then we can start with having a for loop side with ins equal to one and then i looped it all the way to the end so we compare so we have a string first equal to um word minus one so we started right here as index one and we need to capture the first which is i minus one and i is a second so we have first and second then here we need to have edge case i'm not going to talk about it now i will edit later so i just have encountered this problem by submitting yesterday so we talk about that later but i'll come back later so 4 in j equal to 0 and j is less than first dot link which means we look through the whole first all the character in here to find which is the first index that they had a different character if they had the same character like this w and w or and r we can't tell which one is faster which ones are smaller and bigger until we find the different one that's t and f so now we know t is earlier that time we j plus one so we get that key equal to the beginning one which is the first dot chart at um j so in here the key will be t and the value will be f that's how we define so now we key is t f is value now we know we have to check if key is not equal to value then we do things otherwise we pass only when it's different than we do um we have the uh relationship in here so if it's different and also we need to check the map of that key doesn't already contain the value already so we get p contain value then we do things for example um if t already have f now after this t will have f uh and here the f will put it right here for t so for example this is t we put f in this set we check if this set already have contain the f or not because we need to check that because we need to uh also increment the in degree for f in this case put f in this and we also increment f in degree by one so that's why we have this condition checked in here so after checking this uh let me see i'm going too far after checking this yeah we'll have to so now we make sure that the value is not in here then we check in table in degree of this value should increment it by one first next thing yeah since it's not there then we have to edit map.get key dot add map.get key dot add map.get key dot add value in there so after this then we should stop comparing even though they have more later on that's the only uh comparation that we can do so we break out this loop that's the first connection we find from the first place and we continue doing that for these two and we put all this uh relationship in that map and in degree this is this function right here for building the grid let me double check if there's anything missing right here so yeah i think that should be it then we can close this one uh we'll just leave it right here so now we know this is done so we cancel this out so this is done now we come to the dfs right here and we will have dfs we will return a string because we are getting this information here um to find the solution string so let's stop for a while and then i will draw again okay so now we have this two table that we will just build so how do we find uh the string so the first thing uh we will have a string builder but that's too detailed but the idea is we have a queue right here so it's q because we know already uh we have all the keys here this is all the key that we have we look through this key and also look at this table w-e-r-t w-e-r-t w-e-r-t because they have that in degree but only the w in degree is zero because no one give them an in degree since this is zero is that mean this is our starting point so we put that inside this cube then we start with that and we just mean and then we pop out this w and put it to the stream builder so now stream builder right here and already start with w because it's the earliest one and now we have w and then we come to this map we search w to see what is the later part what's after w right and we see we check every value and deduct that in degree we check oh we have one and two we come to this one deducts one in degree if um if that in degree after you deduct it by one because you take out one if this is zero then we put that back put that character in the queue if it's not then forget it and then we come to the second one and also deduct that in degree that's how we keep that in degree now we get this one and deducted one and also check if the in degree for this character is zero or not if any of the character after deducted by one is zero then we put it to here to operate it until we find uh all the order no and we put every time we put out i mean put one from the queue and that's the next uh available to put it to maybe e for example yeah for this string builder we just keep building it at the end we have this string in order so what's that mean uh that means really in order but that's one thing they need to compare is the output and the size of this how many character in here if the size doesn't match then we have a condition here like here sorry for making this mess here if there's no solution and we return the double quote okay and that's the idea in here okay i will keep this right here sorry for making all the mess and now we try to build this dfs right here the fs we have all we need is the map character set character and map we also need a in degree or in degree so we start with a string builder let's be simple new stream builder and also we need a queue that will keep track of every character u equal to um okay q brain freeze okay we have a linked list right here okay we have two what do we need give me a second thinking uh we yeah we looked through this whole entire map to see which one have zero uh zero in degree then we put it to the queue so we have character c we check um map.get we check um map.get we check um map.get set get key get all the keys and we check in if in the degree of this c minus a that's the location of that is equal to zero then we put it to the q the offer c and then sb surely append c which is here we put w to the sp already so now we put every zero in degree to the q now we have to make a while loop to loop through the queue if q is not empty we always do that for dfs and we keep this uh keep track of this uh q and keep looping having a while up here then we know we need to put pop i mean pull one at the character from the queue equal to q dot pull so now we know just in this example we have a w right here so what we do are we look through every character in this hash map we have character connects next character i mean every character after w that in map.get that in map.get that in map.get c is the character we look through that and every time we see one and we degree i mean decrease one in degree from the in degree table so in degree table of that next c oh we shouldn't use here we choose lowercase next c uh minus rc co we deducted by one and it's checked if in the degree next c minus a that location if it's zero in degree is zero that means nothing after that next c so we put q dot offer that next c they put that in the queue we also um have speed a pen um next c so we capture the next c and we put it to the sb so now we almost here i mean we already built sb by getting this to function let's quickly end this function by checking we already captured the sb in the right order late at last we check is sb.link equal to is sb.link equal to is sb.link equal to map.size or not map.size or not map.size or not so if they are they're not the same i mean if they're the same then we return sb dot to string if it's not the same then there's no solution right there then we'll return this empty string oh sorry uh so now i'm just running this one so this two uh function already done let's run this one oh i forgot to put things in there we also need to put the map and in degree in this one already cancel it so this is the empty uh data structure we built and then this one function another function okay run one more time a word doesn't have okay oh sorry for my typo it's a lot hmm maybe you're typing too fast get key see number 39 get key set i think it's not the key side should be key set oh q is not this q it changes all right see if there's anything wrong here okay cool so we pass example right here so this example should be passing and i now have this one right here as this edge case is the updated it doesn't pass my so we have runtime error right here interesting yeah because this case so i re erase this drawing right now because usually when we have uh like we have abc order like alphabet order usually a b always come with i'm come before abc it doesn't have this order right here is anything happen like this is the edge case then we return doesn't that call no solution then we also need to return the double empty string right here and it doesn't work in this case so now let's add this edge case in here we will see uh if first playing bigger than second link which is in here right here the speaker and first dot star with second for that case we will empty this map clear this map and do nothing for that map after clearing return and it just stopped this function right away so it wouldn't go down and that's it for this if they receive an empty map for dfs it will return empty because it's nothing to do nothing for them to process so that's it for this case um let me pass one more time and that's it and it passed uh if you want to know more and then practice more and there's one question really similar to this question and i will put the link which is called score i mean course schedule and i will put the link in the description i will strongly recommend you to go over that one uh again because it's really this concept is really similar so i will yeah if you have any question please comment below and i will see you in the next video thank you so much bye
|
Alien Dictionary
|
alien-dictionary
|
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.
Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_.
**Example 1:**
**Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\]
**Output:** "wertf "
**Example 2:**
**Input:** words = \[ "z ", "x "\]
**Output:** "zx "
**Example 3:**
**Input:** words = \[ "z ", "x ", "z "\]
**Output:** " "
**Explanation:** The order is invalid, so return ` " "`.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of only lowercase English letters.
| null |
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Hard
|
210
|
38 |
hello everyone welcome to learn overflow in this video we'll discuss another electric problem that is the count inside this is a middle level problem and we will understand how we can solve this question easily and by understanding the question better so before moving on if you haven't subscribed to this channel make sure to subscribe for regular late good videos like this the question says the accountancy sequence as a sequence of Digit strings defined by the recursive formula that is the counter step one is one and countercept a is the way that you'd say the digit string from counter say in minus 1 which is then converted into a different digit string okay if we just uh check here it's like given three two five one in that case what will you say we will say a two three and then three twos five uh like one five and one right and that's what you write it and that's how we create a new string so basically what it means is like for one like the first case is like first thing we have is one right uh that's the first thing we get that's the first index one then how we saying like that's one right that's a single one or how we say that's one so for the next uh count to three two one right now how is this there's like two ones right so yeah like two times one is there so we'll say two ones are there so it will write it two one fine then however we will say this one two and this one right so that's one two and then one is there now further if you need to say this how will we say this we'll say this by there's a one time one is there then there's one time two is there then there's two times one is there right that's how we'll say this further how will you go ahead further this three time one is there like three one then two times two is there then one time one is there right so that's how we keep on going uh in this sequence then how we'll do that with our next sequence will be something like 1 times 3 is there one time one is there two times two is there then uh two times one is there right so this way see our sequence keeps on going okay that's how this is that's like we it's like they would say the digit string from count say n minus one okay so this is like uh count say one is this answer two is this counter three is this four is this uh five is this then accounts is six is this also seven is this and this way our paragraph goes on other sequence goes on okay so that's the sequence we are trying to look for now what we are supposed to do we are supposed to find the count say n like it will give us a number n and we are supposed to return Us return this particular value that we come across fine now how will we go to that the first thing like we should go as if as we see like we should go from top to down right we should go from this now we cannot uh go from breaking it because of the back end uh coming back like that may be a difficult one so first easiest way is to just keep going in the forward manner as we found out this values fine now uh what like how will he go ahead of that we will say We'll repeat this step like this the calculative steps for how many times you repeat this test for n number of times fine I'll be repeating these steps in number of time like this calculator we will have a answer so that's here that we will be calling are like using a loop of n right now what we are supposed to do father we need to see like the count of each of the characters one by one whatever the previous character is we need to find a count of each of the character one by one and then append it with like count and then the character itself and then the counter the next character and the next character itself like 2 1 is there so the count of number of twos is one then the character whatever we had there's two itself then this one is there so you could add it a count of one as fast and then the characters are the second so this is the sequence we'll keep following through the whole line fine so this is not a pretty much tough question I think it's pretty much understandable how we can go ahead with this uh understanding or how you can simply go ahead like uh but remember this is like a string okay don't forget this is string yeah okay so how we should do that we should uh be um open to use something like string Builders because we need to append those values our first account numbers and then the values itself okay so we should continuously append those values so be open to use that uh string or rather be open to use that uh string Builder okay so we'll use that and we'll find a solution to that so let's quickly write the solution and then I'll uh show you how this exactly works on what we are saying like this is pretty simple I hope you can understand that we're just counting the number of digits instead adding the count and then the vegetation then the count of the next digit and the visitation so that's how it is going on so let's quickly go ahead and write a solution to this function like this approach foreign so as we discussed that first we will take the first character as uh one so that's the account and say one okay that from 2 till n we'll simply go on uh repeating this steps and in that we will simply call or the string to our count index and return then save it was kind string okay so this updating our string again and after that we'll simply turn our final string our n is equation right so what's happening with this counting so we took a string Builder to just uh do this app in our addition like adding those characters easily so the string bit is helpful for us right so then what we do which is the first character as a character C and we took initial count as one fine if the character is equal to the previous character or the starting character or the character we hold in our C so if that is equal we are simply incrementing our out that is the number of count is increasing so they're like three times four uh one is there so that means uh we are just increasing the count there is a three okay so that person is increasing and else if I know that's not a equal so that means uh the digit is changed now we need to append those values right now we store those values so what we first do we first appended the in our string Builder first step in the count like whatever the county came across okay and then we appended the articular characteristics so whatever if you just look ahead in this example for example we have over here is like uh there's like three two times three right so we just counted like there's two the count became two and then what is the character across three so what you did with this appended count so that means that 2 is appended then I appended the calculator so that means the three is great dependent right and then we uh like initially the values to your kindness so once you found a difference so we are doing this right so what do we did we just changed our current characters like this change the previous character it was three previously so we changed it to a current one that is two so that's what we are doing over here and then we are incremented like reducing count to one there is a current count became one so that's what we did fine and then we just followed this positive and at the end when we end up with the last character so then you see there's no check for the next chapter so what will happen we need to append those values uh by default okay so we did the same thing we simply appended the count and the C right so we simply appended this and if I returned our substrate like the string like as a string Builder or two strings are string right so we simply return the string so this is written this thing will be stored again to the previous s we had in our uh main function the counters are function fine so this is how the question works so I can make you understand how we can uh solve this question and how easily you can think on uh finding solutions to this kind of questions okay so this is like pretty much fast solution but you know this list code has this uh its own uh Madness so it doesn't go for that so that's all about this video guys so thank you for watching this video and hope to see you soon in my next video as well thank you
|
Count and Say
|
count-and-say
|
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1) = "1 "`
* `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string.
To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string `"3322251 "`:
Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_.
**Example 1:**
**Input:** n = 1
**Output:** "1 "
**Explanation:** This is the base case.
**Example 2:**
**Input:** n = 4
**Output:** "1211 "
**Explanation:**
countAndSay(1) = "1 "
countAndSay(2) = say "1 " = one 1 = "11 "
countAndSay(3) = say "11 " = two 1's = "21 "
countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 "
**Constraints:**
* `1 <= n <= 30`
|
The following are the terms from n=1 to n=10 of the count-and-say sequence:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
|
String
|
Medium
|
271,443
|
171 |
hi everyone in this video we will be solving another lead code problem excel sheet column number so we are given with a string called column title that represents the column title that appears in excel sheet and we has to return the corresponding column number so this is the example a is the first column b is the second c is the third and so on z is 26 and so on and if we see a sheet here so these are the column numbers corresponding to a b c and so on and it can go beyond z also uh again it will start a b and so on so that's the problem we are given with these column title and we has to return what exactly is the column number if we see from the left so a b will be 28 and so on so let's see how we can approach and solve this problem before going into the actual column problem let's see how do we represent the number in decimal in power of 10 so let's say have a number in decimal 1 2 3 how do we represent this 1 into some power of 10 and then plus 2 into some power of 10 plus 3 into some power of 10 so we'll start from 10 raised to the power 0 at first place then 10 is to power 1 then 10 is power 2 this is 100 this is 20 and this is 3 this comes out to be 1 2 3 which is same as this one so what we did we started from the end we multiplied this number by 10 raised to power 0 then we multiplied this number by 10 raised to the power of 1 then this number but n is to power 2 so we started from the very end and kept moving left and at the same time increasing the power of 10 in the same way we do for binary numbers also or hexadecimal numbers also let us take another example of binary number let's say we have 1 0 1 which we know is 5 this is in binary now we'll follow the same approach will do 1 into 2 raised to power something then 0 into 2 raised to power something then 1 into 2 raised to the power something so we'll start from very end 2 raised to the power 0 2 raised to the power 1 and 2 raised to power 2 this comes out to be 4 this comes out to be 0 because we have 0 and this comes out to be 1 this is 5. now this and this are same so this is how we convert a binary number to decimal similarly we can follow the uh follow for uh actual column number also it's just that in decimal we have 10 character set that's why we are multiplying by 10 in binary we have only two numbers zero and one that's why we take two here in excel we have 26 a to z that's why we'll take 26 now let's take the first example which was given a now a is straightforward we know for this is the first column so but we'll follow the same approach so a's value is 1 that's why we'll do 1 into 26 raise to power 0 this will be 1 another example was a b now a is 1 b is 2 1 into something plus 2 into something because b is 2 so will he start again from 26 to square 0 and 26 raise to power 1 so this comes out to be 2 26 plus this comes out to be 2 this is 28 now let's take the last example z y now z was 26 this is the last character into something plus this is 25 into 26 raised to the power 0 and 26 raised to 1. now 26 into 26 is 676 and this is 25 now this comes out to be 7 0 1 so that's how we'll be solving this problem we'll scan from the very right most character we'll take this we'll take its numerical value will multiply by 26 raise to power 0 and as we move towards the left we'll keep on increasing 20 raised to power next 1 2 3 4 and whatever is the number we'll multiply by that number so let's see how it works in lead code so as we see we can scan from the end and then keep on multiplying it with the power of 26 and then we will get the result eventually so we'll take a variable plus equal to zero this will hold the actual column number that we have to return and we'll also take power which is initialized with one this take cares of the uh what is the power of 26 that we have to multiply now we will do character in this so colon minus one is a shorthand in python 2 reverser list so this column title will be scanned in the reverse order that you wanted and here we'll have res plus equal to over d of c and minus of 64. so this order will give the sky value of the column if c is equal to a it will give me 65 because capital a maps to 65 and as we has to map from 1 to 26 that's why i am subtracting it with 64 and now he has to multiply with this power also and in the next iteration the power should increase so if currently i multiplied by 26 raised to power 1 then in the next iteration i have to multiply it by 26 raised to power 2 and so on that's why i'll multiply it by 26 also and in the end my rest will have the result so that's it we can try to run this one submit this chord submitted so uh so now we can see what is the complexity of this uh solution so we are looping over this column title so whatever is the length of this column title that would be the time complexity of it because we are not doing anything additional here we are just rotating over it and all the operations that we are doing inside this loop are order of one constant time that's why the time complexity will be order of n is the length of column title that we are given with and space complexity will be constant order of 1 that's because we are not allocating any space which is corresponding to our input we are just taking this these two variables and that's it we are not taking anything extra that's why the uh space complexity will be order of one so i'll break here that's it for this video see you in the next one 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
|
1,463 |
hey what's up guys chung here again so today I want to talk about another at least called problem here 1463 cherry peak number two hard problem okay so let's take a look at this problem description so you're given like a 2d matrix here great with rows and columns and then you have two robots so one robot starts from the top left corner the other one starts from the top right corner and for each step a robot can only moving down right and it can only moving down by one row but on the horizontal level it can move either to the left director directly down or to the right so basically for each of the robots on each movement it has three possible movements here and then you ask you the okay so once this robots at one at this one position here location it will collect the this the cherries on this box and if two of the robot if two robot reach they're the same locations I'd say for example five here right only one of them will collect the chair basically this file only be collected once and it asks you by the time this robots reach the end reaches the last row what's the maximum cherries what's the most maximum number of cherries those two robots can collect right so obviously this is going to be a DP problem right but the question is how can we solve this DP problem right so you know for the we have to deboard here right so that's obviously a DP inj right I&J here right and then but DP inj right I&J here right and then but DP inj right I&J here right and then but then we have two moving objects here right so that's will make us a third j1 j2 here basically that will make us make this three dimensional DP problem here and so that's the first thing we need to be sure right and the second one is the with DP problem if there's a top-down and bottom-up right there's a top-down and bottom-up right there's a top-down and bottom-up right so you know please this kind of problem that the starting point is a it's the like is a fixed positions and then it travels down download the road and the fridge notice here so the ending point it's not a fixed ending point right we don't know on the last row it could be ended in anywhere right so then this like for me at least that would that makes this bottom-up problem a little bit more a bottom-up problem a little bit more a bottom-up problem a little bit more difficult because unless we if we want to travel from top down here right basically in by the end let's say we would want to travel down from first row to the last row if we're trying to use bottom-up solution then by the time we bottom-up solution then by the time we bottom-up solution then by the time we reach the last row we don't know like which element we should use right and to do the bottom-up one way is right and to do the bottom-up one way is right and to do the bottom-up one way is that you have to be basically you have travel from the last row going up and then you know okay at the last step we know the left most point and the rightmost point those two points will be our final answer right unless you will travel from bottom up and if you want to like go to a more intuitive travel from the starting point to the end point right in this case you its we have to use like the recursion call is the memorization to solve this problem basically every time when we have we are angry at this we're at this control here right at the highest row we will collect the corner rows we can't collect the carneros cherries and then we do a recursive call for each of the possible movements on the next level and then we do a recursive call we return that method to the current one and in the end we just return this helper function okay so with that being said let's try to call this problem here so basically we're gonna have a DFS here right so it's gonna be a DFS here are going to be the row column 1 and column 2 right so that's our 3 uh parameters here and okay so this is a recursive call we're gonna have like the memorization problem your memorization here and first thing to check is that if row column 1 and column two is in the memorization right and then we simply return whatever we saved inside there right we save row column 1 and column 2 right that's the first step and then if the role reached the last role here so actually am equals to a grid let me define some variables first lands and then and will be a length of the great 0 right so that's the rows and columns basically if you reach the so we should we stop right we stop when we reach the last column right but when I when we are the last columns we still want to collect the current the last rows cherries right that's why we have to keep doing it so that's why we cannot stop from N and minus 1 we have to stop from n right because for n minus 1 we still want to continue doing that the followings that's why we need to pass the Sun minus 1 to N basically if we're reaching the end which it means we already we are outside after this 2d grid here right we simply return 0 because there's nothing to collect there all right so ok so now at the corner oh it's the bottom of it's the robot 1 and robot 2 column locations so we need to do two things first we need to click the current rows cherries right cherries it comes to what equals to the grade row and column 1 right and remember we don't if we need to check if the two robots are in the same location if they're in the same locations we will only be collecting this once right plus 0 ok if column 1 equals 2 column 2 right basically if the two robots are at the same location we will be adding the second Prime 2 as a 0 basically we're only collecting this current cell once right if they are not at the same location then we'll collect both row and column right column 2 in this case right because if they are the same location we can use either column 1 or column 2 it doesn't really matter but in if they're not we have to be collecting both of the locations right and then the next step will be starting from this Rho 2 Rho minus Rho plus 1 we have to be we need to try all the possible ways and right result basically result from next row right equal to 0 and how can we so basically each of them have three movements right so and we have two robots that's why we need to have a first nested loop here right basically the I arranged what in range - one two - the I arranged what in range - one two - the I arranged what in range - one two - right from minus 1 to 1 basically and J arranged - 1 2 - right that's how we - arranged - 1 2 - right that's how we - arranged - 1 2 - right that's how we - for each of the basically we have to get all the combinations right because for this one can be moved to left down and write this one also left down right to get all the combinations of those two robots we have to do a nested loop right means both 1 - 1 - 2 1 and so basically means both 1 - 1 - 2 1 and so basically means both 1 - 1 - 2 1 and so basically a new column 1 right gonna be the column 1 class I all right a new column 2 cos 2 column 2 plus J right so and now we can before calling the net the DFS method we need to do a sanity check we need to make sure the new column are in are you still within the to degrade right so that's we do a sanity check if this one is reason the range of n right that's the length of the turn the waist width of the to degrade same thing for the other new column right new C - the other new column right new C - the other new column right new C - well less than right if both of them are within the create the we can do this we can do a basically for each of them we track we do a which I'll eat off them and then we will get the max of the FS right row class one since we're moving to the next row write a new column one an new column to write and then for a current for the current level what's the total Cheerios we have here right total cherries we have here is do this one plus the cherries right we currently collected and then answer equals to this right so and then before returning the answer let's add this things to the memory memorization result right so gonna be a row the key is going to be the row column and column two right and the value will be okay so it since the dictionary we have to use a square bracket here the value will be answer right that's how we do with the memorization and then we simply return the answer so here simply return DF s plus 0 and n minus 1 okay right oh yeah let's try to run the code here know what 24:21 huh em hey 24:21 huh em hey 24:21 huh em hey oh sorry here he comes - em yeah I'm the oh sorry here he comes - em yeah I'm the oh sorry here he comes - em yeah I'm the Rose not the end all right let's try to run it cool so it's passed all right just to recap what we have discussed a typical dynamic programming problem the only difference the difference here is the first you have to moving objects that makes this dynamic programming a three-dimensional state here and the three-dimensional state here and the three-dimensional state here and the second one is the second thing we have to be careful here is the up since the ending the stop point is not a fixed place right but the starting point is a fixed place it's so that if we want to get the maximum number or maximum result with minimum results by the time we reach the last row right it's hard to - it's hard to get the value hard to - it's hard to get the value hard to - it's hard to get the value from the DP result right that's why it's better which is better we use the top-down mechanism here basically we top-down mechanism here basically we top-down mechanism here basically we start because we as we know the starting point right that's that make it makes us easy to start and we start from here and then we're just moving down the road right and then we do a recursive call on each levels right and then on each level will be getting the most the max position the max cherries we can peek at this at the current level right and price of what the anything we can collect from the previously level that's what that's how on each level we always get in the maximum we can collect sort of like a recursion class that greedy method right technique here and in the end and also don't forget to use the memorization so we don't have to repeatedly compute the same state more than one time more than once right and then in the end we simply return the answer here so yeah I think that's it for this problem yeah very well interesting DP problem yeah that's why I give it my own output see only three downloads which means this problem is pretty it's very interesting problem everyone likes it okay cool I think that's it for this problem thank you so much for watching the videos and stay tuned I'll be seeing you guys soon bye
|
Cherry Pickup II
|
the-k-weakest-rows-in-a-matrix
|
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Robot #1** is located at the **top-left corner** `(0, 0)`, and
* **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.
Return _the maximum number of cherries collection using both robots by following the rules below_:
* From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
* When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
* When both robots stay in the same cell, only one takes the cherries.
* Both robots cannot move outside of the grid at any moment.
* Both robots should reach the bottom row in `grid`.
**Example 1:**
**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
**Example 2:**
**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
**Constraints:**
* `rows == grid.length`
* `cols == grid[i].length`
* `2 <= rows, cols <= 70`
* `0 <= grid[i][j] <= 100`
|
Sort the matrix row indexes by the number of soldiers and then row indexes.
|
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Easy
| null |
823 |
Hello Everyone Welcome to Date 30th March Switzerland Today's Question is My Negative Effects Lips Try to Understand the Problem Faith in this Question Was Given You Character of Winners in the Form of Energy and Order in Tears in the Tarzan Wonder Means Numbers and Positive Nature and Greater Than What Do We Need To Make For India During Winters All Software Exact Number Can Be Used With Any Number Of Times While Making Me Smile Military Sudhir Very Important Point Should Be Taken Into Consideration While Explaining The Later Part Video How We Are Chal Users Property To arrive at solution also edition only no difficulty products office children product garlic roast children in the ministry should be equal to the product of so notes to connect with children and on the other hand peanut politeness to return gift number for a difficult also recent can go accident Bhalu Vihar to model test paper ninth class festival to examples of state is to force minister took of her home and trees can we make out of this is related to wear dresses three come the first in the to 1000 Atharva Veda is root and to children Want to right and left side that when rudraksh example2 450 home ministry witch can be eaten with ultimate 7 4 how to replace rule 450 treated differently than 400 * subscribe button more 400 * subscribe button more 400 * subscribe button more must subscribe 5210 subscribe Video subscribe problem nod32 grass in the most obscure So let's draw inferences from description not be discussed so fluid to the product of its quite certain death signified this white mukti notes 200 to 250 Daniel mid term policy and avoid the inferences drawn subscribe The Channel subscribe Video then subscribe to the Total number of possibility of us three a new Delhi shoulder second's famous 245 to land and 20 days on Thursday 1000 and 500 in totality of Vikram forces vikram7 stock report subscribe loot New Delhi 84 underwear 800 old and treated differently New Delhi Bihar for To Treat Something Like This Four Days 2128 421 subscribe to subscribe the Channel subscribe button And Darkness To And Cases Which Are Interested In Property The Element Can Give Any Number Of Times Satire Profit 251 Possible Solution Snowfall Kannauj Services * * * * Kannauj Services * * * * Kannauj Services * * * * 46854 Possibility Yagya To Notification Route To Goa To B 420 467 468 Subscribe Button To That In The Right Side Ubuntu Hai Subscribe Wicket 80 Positive A The Police Tried To Understand And Forum Against All The Best Will Be Solving Living In A Technique the na subscribe Video subscribe inter second year jain inter and long and stuart broad border ke do and long and its object the difference between subscribe definitely drop in the number of possibilities number portability subscribe my channel subscribe number account subscribe report handed over are You How Is The President Of The To Do Subscribe My Channel I Will Move From 0.2 Subscribe My Channel I Will Move From 0.2 Subscribe My Channel I Will Move From 0.2 - - - That Bigg Boss Beyond Earth Duty Is To-Do List That Bigg Boss Beyond Earth Duty Is To-Do List That Bigg Boss Beyond Earth Duty Is To-Do List Security The Root Of The Tree Of Birth Anil The Information In The Map Of This Suicide SDO S N 0 D0 Tubelight Process Report Subscribe Now To Receive In This Want To Back Side Reaction Behaved Abs Vwe In This Point For U Ke Laddu Points 208 Aa Je Is Lagna Mantru Ka Anubhav Weak Condition Virvar Louis Divisible By Destroying Subscribe And Up The End Of The Product Also given entertainment awards fibroid j inventory what were trying to quit trying to build e agree with you is volume co inside fit children we have that mode g e want come in plain mode that buy your urgent a is because of this count to 10 Send Your Feedback Contribution Blind Left Side This Remedy Eye Models From This Is The Product Of So Let's Tribes On Duty This Logic On By Taraf And Models To Easy Mode Videos Were Made Content Provided Yogi Ji The Person Bye O 220 Understand And Sandals Logic Postmates Is Weather A Gradual Gift Center And North How Can Chat With R Forward Bases And The Question 118 Compound Like Phate Bhoshade Is President Of Indian Railways Ministry For It's Something Like This Is Members Of Fight Bhai Urgent A 200 Then Models To Is 0 Hu Is The Means Of Z2s Bandhan Tender Mein Unwanted Contenders For But You Can This Be The Voice Of The Year In The Buddha Mahavir And Me Too Update Video 251 Plus Loot Plus 12515 OnePlus One Two Ka Sukh Mil Update Importance Two Volume Inside Condition About 3000 Fidoud Pims Liquid To-Do List Menton Ek Side Liquid To-Do List Menton Ek Side Liquid To-Do List Menton Ek Side Reaction On Ke Ber Khae Is It Affairs 28 This Person The To One List Start With Ja Oo Hai To Jis Din Vo And Then Electronic With Relief Message Center And Note 8 Model Of 2018 By To the flashlight on it and not give up i suresh update account variable account get updated with witch wali the volume the amazing 4222 * amazing 4222 * amazing 4222 * that diwali field par to bollywood and back into this one so let's get updated with one plus to science monitor side reaction subscribe wave soft and smooth dough 21 that anirudh n check weather i and description possible 10th or not that possible hour oct 28 models for easier and 8 rate 8.2 is painter measurement easier and 8 rate 8.2 is painter measurement easier and 8 rate 8.2 is painter measurement notification subscribe bill check water bollywood held in the calling disapprove will multiply this and updates Account Pimpal Suthri Plus Two Ka One Two Three Idiots Five New Delhi Two Minutes After But Why Not Get Updated With Five 210 Institutions Builder Nath In the near term of Delhi will be a town called the numbers unmatched in which the total binary conversion rate and values will total binary conversion rate and values will total binary conversion rate and values will Be held badal use in the name kurban plus to class 5th ed 2nd ed aa akta tab zaroor in the water into well in ashok gautam so you to do subscribe with mother ko input tray se ki vegetables 2451 10th and posting it software undertake tullu sahay and EE 200 came to this garlic gazeb deposit account aircraft you have come to the Get updated with two unless one to back side reaction. To SDO During British Rule and Tech changed the fonts to give peace to the look and not support Indian student hotspot of the map and how to update account with validated Ullu Held in the map Tube Jiban * Bollywood's Held in the map Tube Jiban * Bollywood's Held in the map Tube Jiban * Bollywood's Shotgun to two to the states update account Vid Hai And Bittu Andar That Bigg Boss For Electronic Hydration Business Is That International Weather Any Food Possible Contender For 5-day Tour Not A Contender For 5-day Tour Not A Contender For 5-day Tour Not A Contender Rejected Five Mode And Sports Noted Daru Breaks And Deposit Volume Wise Fennel 5 Gram 512 Approval One Side Reaction Behavior Tank And Is Pointed Is 267 From Girls Dresses Points Ka 10 Volume List Festival Posted At Least To Is 503 Models To-Do List Servi To Subscribe And What Will Be The Counter Multiplication Of Values Into A The Recent Multiplication Of Values Into A The Recent Multiplication Of Values Into A The Recent Bittu That Tomato Next Generation With 40 Models For it is not true content in disputed site question 10th model spider it is 0.11 tender condition 10.2 vidmate spider it is 0.11 tender condition 10.2 vidmate spider it is 0.11 tender condition 10.2 vidmate 35 is present in this to have so let's update account chilli 121 intensive research and 20th had eggs updated return deposit tank mathat suniyat train with solution recounted mole leo club screen free subscribe hai i hope all build this creative and move with according part posting talk about this regard by twisting also rs.12 twisting also rs.12 twisting also rs.12 reduce the number of times pet dal upar se twitter to that a next just one click karenge this rl this channel And hey doctor length is 110 hi dongri jo a ke andar se point name of vipin tractor komal on rent in long certificate one increase the contact leads them in 10th maths wali new ki adityanath alert rai anil raj election 2010 by researchers are don inch Plus app a long account equals that wearable let's start Vijay Luta plus are 51000 half an hour subscribe updated on the soul will update account wa a girl tight arranged not fit into a is vansh huge build account this bill updated on name dot in That if it took merchant and was playing with solution long song to turn's trunk absolutely to retail pack is to end and returned unbeaten entry temperature to lock entry preset MP3 old entries and lock entry preset MP3 old entries and lock entry preset MP3 old entries and developed the total amount of dividend bollywood me entry death valley And Sawan incomplete system data entry date ki hai hua hai do ki entry don't get value allow hotspot on e will simply two models based on the answer a hua hai ki print wali hai a total account models one two three layer six Seven Eight Nine Ten Rock Alarms Pandey A Hai Answer-A The Researchers Are Not Tell The Hai Uttar Sorry For That Is A Unique Scene Hai Hua Hai Do The Love And Support One Extra Space Words That Show The Root Lord Can Be Achieved With All Due to is one time and root char tabiyat to two to one whatsapp text what is the time complexity of this approach to time complexity doctor of science and oil solution settings usko take and login and spirit and destroyed in the ashram of mothers page Drop in the number of cases subscribe please feel free to ask a time for watching the video please don't forget to like share and subscribe 10th
|
Binary Trees With Factors
|
split-array-with-same-average
|
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return _the number of binary trees we can make_. The answer may be too large so return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[2,4\]
**Output:** 3
**Explanation:** We can make these trees: `[2], [4], [4, 2, 2]`
**Example 2:**
**Input:** arr = \[2,4,5,10\]
**Output:** 7
**Explanation:** We can make these trees: `[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]`.
**Constraints:**
* `1 <= arr.length <= 1000`
* `2 <= arr[i] <= 109`
* All the values of `arr` are **unique**.
| null |
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
|
2162
|
45 |
All this has happened Frustrated Hello Guys Anurag website so basically you see back with other site questions and questions the question is jump game two and hard category question the question is easy but there is a scene of complexity in it if like this then turn off the mode If you do, then it is a very easy question and if you want to share the mode of end, then it becomes a little difficult. Okay, so what is there in this, basically we have been given Gare, this is our giver from late, okay, so this is the governor, so that is 11 you are like this. You are standing in the beginning, you are standing here and you I am reaching here to reach the end is your break-up reach the end is your break-up reach the end is your break-up and every index what told left is 2351 then will take it is important so to what told that you reached this index first so from here You can take a jump on two, okay, but if you do something and reach here, then from here you are okay, when one will do it, then you can take the piece and sometimes you can't. What is it to you England that your tight To go from this to this end, please send the minimum balance, how much will it take, how much minimum, when you want, then order it against corruption every day, also a DP that we will not do that, discuss, we will use greedy algorithm for basic in this, like this video, gas ma'am. Ki Agni Aaloo ko kaise ke liye dekh toh main tere ko lagta dobara se to MP3 Is Vansh The one is a phone now what will I do in it I am taking some carrier base you will understand why I am taking it ok that one is my current reach a At what time did I give zero, okay, how many jumps have I taken so far, he is busy, okay, and 1000 villages seem to be the max, I gave him zero, I am saying that I am Giridih Allah, we use What is the meaning of Green Day, from where you are standing, do the maximum thing that is beneficial to you, okay, so I have decided on its time, what will be the features that you can take as much as you can from the place where you are standing. Yes, edit max, take that much, what will I also do, I will do the same, if I stand at two, Allah, if I do 1400, then I will stand here in English, I will write 0230, okay, I have written English, so if I stand at the ends, then it will be maximum two that When I can take it, that is, I can reach here, then I will go something, okay then what will I check, okay brother, I have taken the maximum of two, but from this jam of two, I had recognized till four, this product is water and What is my name, I have to reach four, this is the question that if you want to reach the typing side, then basically what will happen is that from how to, you have reached religious, that the middle birth of that is correct, out of these, you will have to take another jump. So I will have to take one more jump, with the help of which you were finally on 4th passbook collection, who knows from the band it will be very difficult to get cooked by the husband, reaching 301 and then 104, I am asking whatever may happen but it is certain that you You will have to choose one of these two, okay, so what I will do in this is that I will take maximum life and then I can add as many elements as extra, if God means, then I can take it till the end, so I will check on three. I will do it and I can mature on 341 in one way. Now I will see you which one will be most beneficial for me. Okay, okay, why do we do this because we have not reached the end, so brother, you can take one-way on two or three. I brother, you can take one-way on two or three. I brother, you can take one-way on two or three. I can put it on the media, we jumped on the bun, now what are we, now we are standing here, okay and yes, as soon as you came here, you are here, but this is your current reach, now how far can you go? You can go to the technique and then update the entry, you are fine and you got a jump, you felt it immediately, you got WhatsApp to suck, then the exam is done, it is fine and what happened to Mac Sharif, my max is very-2. I my max is very-2. I my max is very-2. I can mack for minutes then I will come here what will I give here how much jump can I take add so I can embroider on one and I can take birth of 3 i.e. total for i and I can take birth of 3 i.e. total for i and I can take birth of 3 i.e. total for i can go till the fourth index in this With the help of the method, I will update the maximum in the middle of your max so that now I can go till the floor. Hey friend, you will say that you should increase its limit, otherwise right now we are just sucking whether I will take three wale dum or banwali jump. I will take it ok when the chick is done and I will be moving on from this because till here I can fall in the exam right before that after I see the things I will take my jaw then I am sucking which birth should be taken Okay so till now I have one thing for done then I you on urban on one but if I see how dirty in descent I can go till plus two third intact then I will see if I can go up to f4 first so this is Juicing is useless so I have mixed it with my next one so then I am checking one more thing every time that if my next one is equal to the current three inches okay if that means I have reached the end now this How long could it go on? It could go back to suicide. It's reached here. If I wanted to push this further, I'd have to take a job. Right, so what would I do if what I had came to an inch? You will make the jump plus and I have already decided in which year I will be born, it is okay to reach here, so this was its Giridih logic, what logic was that you take the maximum jump and the maximum which is from us as far as you jumped. Till there, people look at them from the elements in between and see which of them, when you have to take it, which mobile will be the best, then it is okay for the subject of your ID proof, then switch it friends, make entries, then the jump juice will go the day after tomorrow and one One more thing will happen here, tax entries will also be updated, from now on, if I am moving from here to here, then if you are standing here, then like to speak, then its entry will be added, then when it will increase to go ahead, first thing. One is fine and the tax entries will go to war preparation max equal to 2 inches that now we can go up to Will run high cost From zero to this is less done Whatever its length - Will its length - Will its length - Will run till one What will you do - Mind why see run till one What will you do - Mind why see run till one What will you do - Mind why see Okay now I will come here So how till now Coconuts have jumped to my Current Richer 14th and Maximum rich, he is a gift, I came here, how did I get it done, I can take more of the meths, 1 A+ three, four is done and so already A+ three, four is done and so already A+ three, four is done and so already kept, something needs to be done, then he is fine here on the floor, now when he When it comes to the floor, basically what will I see that the current that has come to me has been recovered, the current has been used, my four, so what will happen here when I will increase one more time, when the plus will become plus, whereas my need to do one. Because I have already reached the floor, so why should I, there is no need to increase the crowd, so what I will do is I will travel my element only till the end minus one. Okay, so if we try this on another test case by coming to every house or Let's see it once again. Now what is it to see again? This is two three live 114. Start my tax entries. 020 Marriage also. 080 In the beginning what will happen after this. I am here for you, what will I see? I have got that request. Please request. The entries are here and before that I will check whether my maximum can be reached, till now it is zero and if I reach here then I will be at 119. My zero plus two means if I break then this Mexico October. I will give it and then how much of one more thing and here, set it from zero, it is equal to one and a quarter inches, which means that if I have to explore the things beyond this, then for that I will have to increase the brightness, so when the plus goes to plus. And my current rich, what will it become equal to maxis, so if I make one thing equal, then it will break when it gets closed, so how far can I plot this, come till here, okay, please explain the thing in this mortgage. Okay, so if I make it 11th Kunwar, then the husband can see in it, I can see more closed, I can see size three in it, and I can see closed, so if I see three, then what will be free and this closed Nifty index. It can go up to four in murders, so this is my maximum, whatever will happen, that update will be released, okay, now what will happen, okay, I will consider that I request to do tax entry, not from the entry, I have not broken the interest yet, then I am here. But I will see that the remix rich look can be so much. Question 3, first there is only one more thing, there is no need to update, but the one that has come to me has already been entered, so why will I bother about things beyond this when it is plus. And give the current reach max, it will be okay, so if you jump to see my further things, then this and the maxims will be as much as we can. Ok ok then I will see how far can I go if I stand here can worship in the dorm OnePlus 3 first there is only one more there is no use go ahead and check this also A request to current not introduced Then I will come here and there is no worship here because I will run my people, that electronic one, I will run it till pan minus one, tips, so basically this is the cyclone, we will fold it and see, so I will reduce the current rich to zero, okay and pant current in mexico I will make it zero and print birth in the morning I will make it zero two then what will I do I will run the loop one of my object from zero is resist name start length alien GTA 5 - one i plus start length alien GTA 5 - one i plus start length alien GTA 5 - one i plus minus one is running till you should understand Okay so far what I will see here is that I just I plus moist cleansing okay aa a personal cleansing means if I my ID here is Vitamin E one okay and the name is the last of cleansing i.e. E one okay and the name is the last of cleansing i.e. E one okay and the name is the last of cleansing i.e. Then whatever is there, I will see. Come, whatever is my phone, I will update you if it is more than what I have reached before. Okay, press f5, moist white, what is this, Great Dane, my current reach, that is mine. The current reach will be updated and the entries will be made. My i plus name cleaning is ok and what else do I have to check that if i request is equal to sorry corruption is the current max on the current that is correct and here how I have to do that I questo if what is my current trichay you then I have to do two things one is you have to increase the jump that when you have to make plus and what have to be signed in the tax entries use current and send it Current maths is done, yes, this is the thing that has to be done, that's itna hi ko dress power adapter toh kya kar dena returned gems return kar dena so we came in our loop we saw that if I take this particular Chamco, will that My which I first put my feet, will he take me away from him? Yes, if he will take me then update him that it is Grand Max and one more thing how to do, what to do, I have reached the end, reached inside him as far as I can maximum. To call further than that, you will have to take a jump and then move the jam forward and make the entries equal to your current back, so let's see by running that deep wound in myself, that the run will be WhatsApp and submit. Sir, this is a very good solution, it is faster 994 memory, it cleans the umbrella in less than 6 minutes, if you are upset, then people have understood that it is an agreed approach, there is no such thing in it that how to set the logic, it means survey. Coming to other things, as you keep practicing more questions, you will start to see that yes, you can apply it in this too, so it happens. If you yourself have even a little doubt, then comment in the comment section below that this is the diet of this argument. Let me tell you the handle, Dobara Se Tak Ram 's handle is At The Rate That Anurag Court Se N U R S G Anurag COD S Quotes Ok so you can mam me on Instagram, go to this handle and send your queries on a screenshot. Whether to send code or runtime error, whatever is the problem, take screenshot and send it and I will try to divert ours. Come, date for the video guys, I hope you understand this and bye-bye.
|
Jump Game II
|
jump-game-ii
|
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i + j < n`
Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** 2
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[2,3,0,1,4\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 1000`
* It's guaranteed that you can reach `nums[n - 1]`.
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
55,1428,2001
|
397 |
hey what's up guys this is chung here so this time let's take a look at lead called problem number 397 integer replacement so given like a positive integer and you can apply one of the following two options the first one is that if n is an even number you can replace the n with m divided by two basically if that is an even number you can cut the number by half and even the uh and you if the n is the odd number you can either increase them by one or decrease them by one pretty straightforward right and they just ask you to return the minimum number of operations needed for n to become one so then it gives you some examples here right so for example from for a to become one we need three options which keeps let's keep applying the options one here seven we have two ways of decreasing decrease decreases to one that's why we have 4 here and here's some constraints here right as you guys can see here so n is pretty big right 10 to the power of 31. so something like a max integers right and how can you do it right so every time you guys see like the minimum numbers of our operation minimum answers right i always try the bfs right or word dp and it happens to be or actually the uh the bfs the dp or the binary search or even a sliding window i think yeah you can even do a you use a sliding window to do a minimum and maximum right and for this problem you know it happens to be both the bfs and tp both work so let me i'll try i'll implement both of them until the first things is that the bfs right so for the bfs you know i think many of you already know the template right so it's just that at the beginning we have n here right and then we have a we have seen sat right so actually so before implementing this thing implementing either bfs or dp so one thing to be noticed that you know someone may have this question you know since the end is soup is very big right and if we just haven't this options two here if we only decrease or increase let's say if we only decrease this number by one it's going to take a linear time for us to decrease the number right into the into one so wouldn't that be tle the answer is no because we have this one more constraints before that we only decrease or increase by one when the number is odd so which means that which means even though we have a huge number let's say we have one nine right so let's say we have this huge number here yes so to decrease this by one we decrease it to 81 but you know once this one becomes a part even numbers we can then apply the rule number two here which means we'll cut this number in half so it means that you know our time complexity will bound it with this log n and not o n because every time we have even here we'll cut this number in half so that even though in the bfs we always have like a pretty huge number somewhere following this following the unwind here but the next time it doesn't i mean the next time the number will become much smaller i mean a smaller by half right that's why we can reach the answer in log in time not all in time all right cool so let me continue this bfs template right so we add n and then the bfs here like this right so for me you know someone prefer to store the answers or stops using this within the queue here but for me i personally prefer to use a for loop to help us track the steps so that we can save some space in this queue here right so that's why i'm going to use the for looping range of q right i mean we have been we have implemented this bfd search many times so there shouldn't be a should be a no stranger to most of you right pop left and then so the template right so it's always good habit you know to finish the template so that you won't you will not forget later on and in case you got distracted while implementing the uh the inner loop here so that's that okay now the base case right so if the current one is one right then we simply return the answer right and then we have like if the two cases basically if the current mod 2 is not um is not zero it means that it's an odd number so and then we can uh we can try this n plus one and then minus one right and before doing that always do a sanity check if this thing is not in scene right then we do a q dot append current plus one okay so we don't need a another brackets here same thing for the uh the minus one case right let me do a minus one so seeing that at current plus one then down below here we have current minus one okay so this is the odd case right odd number else house even number right pretty straightforward even the uh if the current divided by two not in scene right and then we uh we do this i'll just copy and paste here right this thing here and then that yep i believe that's pretty much it is okay let me run the code here all right accept it submit cool so it looks it accept it so that's the uh the bfs pretty straightforward right and then the next one is the dp so for dps it's also like pretty simple you know but one thing to be noticed that you know for dp we already have like either top down or bottom up and for this problem is that it's one of those problems you can only solve it by top down right because for bottom up the issue is that for bottom up you we have to loop through we have we need to have a for loop from one to two to the power of 31 that will definitely tle but with the top down it can greatly reduce the uh the scenarios we will explore that's why i'm going to use the top down here so the current right and then i'll just use the uh python sugar here to help us save few lines of code cache right so that's that okay so and then we simply return the uh the dp dpn right so here we have uh i think the base case is pretty straightforward right so if the uh the base case right if the current one is one then we don't need to do another operation basically the dp here it means that the uh with this number n here for this number n to become one what is the minimum operations it when it needs for this card number to become one okay and when the nut when the current one is card number equals to one but then we know we don't need any operations anymore so we can simply return zero otherwise right so since we're asking for the minimum values i'm going to initialize this answer with the maximum and then the right it's just similar we just also need to explore two scenarios right so the first one is the um is the odd case right so if it is that and then we have a answer because the minimum of the answer dot dp so this is the odd case it's going to be a current one plus one and then we plus one because the plus one means that we need we are going to do our either doing one operation right that's why or the uh the dp current minus one plus one right so that's that else are same thing right we do a minimum of answers dot dp current divided by two plus one so yeah i think that's it so in the end we simply return the answer here i mean so this is over kind of unusual for us for in the dp solution because you know usually when we have a dp especially when the uh the number keeps decreasing we are only expecting current minus one right because for the current plus one if we keep doing it you know we'll never end basically no so if there's a branch that the number is going in the opposite direction as our base case it will tl it will in the it will start in the infinite loop but like i said since we have a condition for this dp plus one is when we only do this dp plus uh current plus one or minus one when the current one is the odd number and even though we are we're increasing this by one but for that number the next time that number will become half because it will not go into the uh to this if branch the next time cool so i'll just run the code here yeah accept it submit so yeah it also passed all right so and i think for both of the solutions here the time complexes oh they're both o of log and log n yeah because we have this divided by two scenario right and the time complexity is bounded with this one yeah i think that's pretty much everything for this problem it's a pretty standard bfs word or dp you know either way it's fine you guys can choose whichever which way you guys prefer but i think i personally always prefer the bfs as long as it's applicable right because it's more it's easier to implement the template is more straightforward the dp1 i mean you can still do it but for dp1 just be careful if we if you don't have this kind of con special constraints here you know it's very easy to end up in an infinite loop or it'll tle cool thank you so much for watching this video guys and stay tuned see you guys soon bye
|
Integer Replacement
|
integer-replacement
|
Given a positive integer `n`, you can apply one of the following operations:
1. If `n` is even, replace `n` with `n / 2`.
2. If `n` is odd, replace `n` with either `n + 1` or `n - 1`.
Return _the minimum number of operations needed for_ `n` _to become_ `1`.
**Example 1:**
**Input:** n = 8
**Output:** 3
**Explanation:** 8 -> 4 -> 2 -> 1
**Example 2:**
**Input:** n = 7
**Output:** 4
**Explanation:** 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
**Example 3:**
**Input:** n = 4
**Output:** 2
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Dynamic Programming,Greedy,Bit Manipulation,Memoization
|
Medium
| null |
1,227 |
welcome guys so today we want to talk about is called the airplane seats assignment uh probability so this problem is really famous in uh the brain teaser and the interview okay so i also personally got this uh same problems okay in the interview question so let me teach you how to solve it very quickly okay so this is a brand teaser so the okay so you guys can first see the question first you get basically you have a passenger and uh seats and the first passenger losses ticket and the pick to see randomly and the rest of passengers will uh take their own seats if they're available or pick rc randomly when they fighters is occupied so for an equals to one and then what and the question what's probability that the final person get his own seats okay so n equals one answer is one because it's very stupid and equal to the two that's very easy that equals two you the answer is two okay so let me tell you a solution the solution is that n equals to one that would just return one it's one larger than one the answer is always point five okay so uh so key points that we want to briefly expect so proof so when an equals to one the answer is once so when an equals the two so you have a and b two people and you the first one the second one so the first one if the first one go to its own seats then the second one got correct if the first one get wrong then the second one cannot get so the answer is also 0.5 okay so how so the answer is also 0.5 okay so how so the answer is also 0.5 okay so how about n equal to three so what n equals three we have one two three uh three seats and uh okay so let me use abc and one two three okay so how about how to do this okay so uh there's a chance that the first one get the correct one and in so in this case we have one third probability then in this case the second will go to b because second people does not lose their ticket and the third people does not lose their ticket so the answer is one was one of three and uh so this is this one and another case is that the first one get to the b graduate b i'll get to the c okay so if the first one get to a b uh by the way if the first one gets to a c then there's no way they there's no way that the second people uh the third people can go the goal is position correctly okay so there's a one third chance that uh this one go in please okay so you see uh if this one going release let me become a second one second person so now the second person has two positions if the second person takes least then there's no way that the third person can get correctly if the second person goes a then it can go correctly so times half so this is this okay so i don't know where you guys already see the pattern okay so now we proved by a mathematical induction so i suppose the answer always be 0.5 if i suppose the answer always be 0.5 if i suppose the answer always be 0.5 if one is larger than two okay suppose we have n plus one people so there's a the one over and plus one chance that the first one the first people gotta correctly answer then the final people must get the current answer and but there is another case that uh um plus there's a if the these people get the least uh get this wrong position so there are a total of minus one of lane then suppose you put it here okay then the second people will go incorrectly but for deaf people but for like k people that k people will start to well i cannot go into this but this situation is the same as the previous before it's in a minus one person so this is the answer so we just compute this uh okay so sorry just release then plus one okay so the answer still be 0.5 still be okay so the answer still be 0.5 still be okay so the answer still be 0.5 still be 0.5 0.5 0.5 okay so this is the proof this is a proof and this is for a famous brand teaser so i suggest that you just use mathematical induction to answer this question and i will see you guys in the next video
|
Airplane Seat Assignment Probability
|
number-of-equivalent-domino-pairs
|
`n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105`
|
For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap.
|
Array,Hash Table,Counting
|
Easy
| null |
906 |
hey everybody this is larry this is day eight of the may league daily challenge first day of the second week hit the like button to subscribe or enjoy me on discord let me know what you think uh and it's mother's day weekend here in the us so happy mother's day do your mother's out there but anyway uh today's problem is super palindrome so let's go over it um so i usually solve these live so it's a little slow watch on 2x fast forward skip ahead whatever you need to do and okay let's say you have a super pound room it's also the square of a pound what does that mean square of a palindrome oh okay 60 76 but okay so four number okay that's interesting so there are a couple of strategies to think about here um you know the number of them so maybe you can pre-compute them so maybe you can pre-compute them so maybe you can pre-compute them to be honest um it's a little bit tricky though because for 10 to the eighth it means oh sorry 10 to the 18th it means it fits in the long so you can't really do them um in a naive way because you know that 10 to the ninth um number of numbers to square right otherwise if this was like a smaller it was ten to nine then you could usually just do 10 to the fourth or whatever it is 10 to 4.5 or whatever it is 4.5 or whatever it is 4.5 or whatever it is and then you know pre-generate all of and then you know pre-generate all of and then you know pre-generate all of them and then do a binary search or just look up search or whatever um but yeah but in this case uh the first thing to know of course hmm is that you know you have some f of left you know um another way to write this problem is instead of looking between uh left and right you can also do something like this right uh and this is from zero to so instead of maybe another way of writing is from left to right is equal to f from zero to right minus zero to left minus one something like that uh usually i mean not usually but it comes in handy a lot and i'm trying to think whether this makes sense i mean at least it simplifies the question in that you don't have to do some weird math about starting but maybe in this case you might maybe it's interesting let's see on four digits the only four of them i think maybe what we can do some maths on it so palindromes how many palladromic numbers are there right well the number of paradromic numbers in there are for this problem actually i guess yeah so basically okay i guess the math is kind of not tricky but it takes another layer for me so yeah so for example so you know that the max case is going to be 10 to the 18 and you know that if you can do that means that the regular pendulums have to be ten to the nine um in that range right and here we can count how many paranormal sequences are there in ten to the nine well that's actually just ten to the nine over two say right um because for a pattern drum you only have to generate half of it right because for by definition or half the digits because by definition um you know for example you if you generate them intelligently instead of just doing it one by one you can just see that it's one two three four dot all the way to nine and then instead of doing ten you can see that this the two digit ones have 11 22 33.99 22 33.99 22 33.99 and then you know 100 and then you do 10 which is what you reflected to three digit is 101 202 303 dot and this is not technically an order because um you know you could see one uh maybe technically i should have done an order actually that's my bad um so that's 11 which is reflected 12 13 i just did it in a silly way and all the way down to 999 right and of course you can see that you know here for generation you only care about half the digits so this is roughly 10 to the fifth and by that you can generate every number um every palindrome and then check whether um well you could generate every pound drum and then you could check whether um the square of that is a pendulum and that is relatively cheap per se so yeah so let's get started on that then i think the math is actually kind of interesting for maybe i don't know um let's see and a couple of cute ways to do it if you want to uh take advantage of certain things but i'm just going to do for loops for i think okay i'm gonna keep it dumb and silly for now yeah i mean maybe not maybe it's fine that's the while loop and then we'll just break when it's ready um i'm trying to think so what i'm thinking about is whether it's true that let's say one dirty let's say you know the right is equal to some number x right and we have some we're going over some current times current uh and where current is a palindrome is let's say we go um this number is greater than x um then in this case i was just trying to think about whether this is always going to be true right because if this is always true and i mean okay now that i've printed out it seems uh maybe obvious but i was just thinking in my head whether um that is the case so yeah so okay so let's start with current is equal to the little bit tricky part is depending how you want to do it what i mean by that is that if you want to do it lazily like i was going to do and do the odd and even numbers at the same time then you cannot terminate early because you have to do the single digits like for example if you your um maximum it's going to be smaller you have to do the digits maybe that's not true yeah maybe i'll just do them in two separate loops that makes sense i was gonna do them in the same time but that's fine um yeah and do we have to count zero no okay one uh the link is one cannot have leading zeros does that count as a leading zero with left is it's not really oh okay oops the next line would count me there's no zeros so that's fine so then now we let's do the odds and then let's do the evens i guess oh yeah odd digits oh wait that's kind of awkward the way i'm doing it i think that's why i was worried about it i guess i'll just terminate earlier only on the odd digits because then the even digits will have more digits so then you can al it always generates all the art digits so okay maybe it's a little bit inefficient but it you know we'll figure out the correctness and you know when you want to uh improve yourself afterwards you can figure out how to up solve it but uh okay so yeah uh let's see let's also just convert left to end and right to end of course in your language it may be a little bit different because in python these are uh these have enough precision right or bits or whatever uh okay what i want to do okay i'm trying to think about whether doing string operation is too slow but okay let's do it this way and then um and then we'll think about red if it's too slow we'll do it i'm just a little bit lazy to be honest this is there's nothing uh whatever about this but um yeah so let's just have a set though i think this is unique so you don't really need a set okay and also if p is greater than great we break okay and now we do even oh this is i lied about this is not our digit this is our digit and then now we're going to do even digits so maybe i'm wrong on this one i always i don't i never know how to do it with negative index let's try that though it's really in the efficient but for here now we're gonna just copy and paste i'm not gonna lie usually i type it out but today i'm a little bit tired uh that's my story and i'm sticking to it but we don't break on this one uh okay so then just return kinda way and then let's give it a spin one and two is the other ends that they give us ooh that's not right all right i'm dumb of course um because i forgot to do the squaring part um as we talked about because this is a superfan drum not just regular band rooms this is probably right in regular boundaries i don't know why i cooked on that box but um let's go super uh um i think there's a walrus operator oh super is a uh a keyword forgot i'm just checking real quick whether this is um this wall is up right haven't really gotten good at walrus operators yet because it's kind of new so we'll see if this is oh yeah this would always never terminate but at least it doesn't count i mean because if it doesn't work it would complain about um because this is infinite loop because i was just lazy but if this didn't work it would give me a syntax error so that's all i wanted to check so that's fine um and then now we do this is an x so yeah so we're also going to do a lazy i guess uh let's just do this yeah whoops hmm uh that's not i mean i wanted to do two things but wait square so we wanted only the square okay how did i do this oh um that maybe that's fine good enough and oh this is this doesn't need a function anymore so well i mean it's quite good abstraction but i am just a little bit whatever about it um and that's why you don't copy and paste because the second you have to type it twice and the second time you might just mess it up and i have messed it up many times before but for now this is short enough and i'm a little bit lazy today uh into object oh right um that's awkward i don't want to do another thing uh let's don't try this at home this is bad python i think but uh it's just goodbye fun but good enough fight fine it's fine still bad ah it's reference before the whatever where's my code i thought the walrus would save me oh this is wrong though this is x and maybe that's what i was talking about i didn't read the message but uh okay so that looks good let's of course try the obvious ones like the cases six nine okay so that's really well don't i would also say 70 numbers is really small how do you get this so wrong though that's awkward hmm did i miss something hmm maybe even just start something smaller there's also this clearly so what i would also say that if um i might actually do something offline in theory um and then because now that you know that there's only 70 numbers which maybe they shouldn't give it away um you can actually just print out a table and then submit that but of course maybe you wouldn't do it in an interview but that's besides the point did i miss something why am i under counting so much so i am under counting for a reason so i think my concept should be right let's see i just tried the smaller one because this is going to ruin me might still point out too much um this does what i've wanted to do what is 100 is a little awkward oh i'm this is wrong that's why what i don't want is the first uh i skipped this ahead too much i meant just removed the last digit oops see the easiest is that the right answer now it's better to answer i don't know if this is right answer so that was just a little silly a little fun debugging time okay so that's good and as i mentioned if i um i'm going to submit this now um but if i had kind of a time limit exceeded or something like that i would just you know uh do this offline generate um an array of 70 elements and then just do a binary search on it or something like that at least for a contest so yeah so what is the complexity of this as we talked about i mean we did it in the beginning of the thing because we don't want to implement something that's too slow um which is that for the domain of uh u is equal to 10 to the 18th of this once in roughly 10 to um how do i say 10 to the 18th of the 18 part over four so yeah so that's basically how long this loop takes uh i do things very inefficiently to be honest the way that i did it with converting it back to string and back and forth but you know as i said i focus on the problem and there's definitely optimizations that you can do here as well but i don't i personally don't generally care about running time unless it's too long um and well i don't care about it if i have to write roughly right complexity and this one should be okay um yeah so this is basically our worst case for time and for space we actually don't even well i mean okay maybe conceptually if we do create the way that i did it create a lot of strings you know and references and stuff like that everywhere but uh but if you do it in a slightly not dumb way like i did you could probably do it in all of one space by just reusing uh the correct memory in a lot of places but um but yeah that's all i have for this problem it's kind of tricky it's a little annoying them but i think the hard part about this problem is not necessarily from you know implementation you know i got that wrong too with the i put the i was just going too fast and i wasn't thinking about what i want these to be and debugging time end up costing me more anyway so i need to slow down a little bit but anyway yeah the implementation is not that tricky conceptually and i had some copy and paste stuff here um there's some uh do not repeat yourself that you can clearly see i'll leave that to you for you to do at home this is not code that i'm super proud of per se but yeah but the hard part about this is saying 10 to the 18 do not freak out and try to analyze what your algorithm could be um because i don't think i do anything to any high machinery or any high power thing i just kind of think okay we have a power drum let's just generate all the pound drums instead of whatever right um yeah that's all i have for this problem let me know what you think hope y'all have a great weekend hit the like button hit the subscribe button join me on discord and you know happy mother's day to all your mothers out there and yeah to good mental health bye
|
Super Palindromes
|
walking-robot-simulation
|
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`.
**Example 1:**
**Input:** left = "4 ", right = "1000 "
**Output:** 4
**Explanation**: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome.
**Example 2:**
**Input:** left = "1 ", right = "2 "
**Output:** 1
**Constraints:**
* `1 <= left.length, right.length <= 18`
* `left` and `right` consist of only digits.
* `left` and `right` cannot have leading zeros.
* `left` and `right` represent integers in the range `[1, 1018 - 1]`.
* `left` is less than or equal to `right`.
| null |
Array,Simulation
|
Medium
|
2178
|
377 |
welcome to april's legal challenge today's problem is combination sum four given an array of distinct integers and a target integer target return the number of possible combinations that add up to target the numbers guaranteed to fit in a third two bit integer we're given a list of numbers that are all going to be distinct and we have our target four so how many possible combinations can we make to create a target of four see here we have four ones two ones and one two but in a different order one and one three so on and so forth but the big thing to note is that different sequences of these numbers are going to be counted as different combinations the only exception to that is when we use the same number again and again so all these ones because we're using the same one if we even if we ordered this it would still be counted as the same combination okay so normally with this kind of problems there's usually a brute force solution there's a recursive solution and then there's going to be a dp solution now with a brute force method there's really kind of hard to do that because we don't really know how many nested for loops we can have the only thing we have is our target we don't have a limit to how many numbers we can have in our combination because we can use the same number again and again so we can do it recursively we could probably start with one and go down kind of a bottom-up approach to find kind of a bottom-up approach to find kind of a bottom-up approach to find every single possible combination that has the target of four but that's unless we do memorization that's not super efficient we can just do a iterative solution here by using a dp array and building up our target so what i mean by that is say we had this example of one two three and target of four let's build up a dp array of all the targets that we can have all what this dp array represents is going to be every target all the way up to the main target that we're actually trying to calculate so with this here our target of zero this will always be one because there's only one way to form a target of zero which is no numbers at all now all we have to do then is to check every single one of our numbers and look back in our dp array if our number is less than the number that target we're checking it right now or less or equal to the how are we checking right now just look back and see uh subtract the number that we're checking with our dp array and see if we can uh add up whatever number we had there which is the number of combinations we could have formed with zero to the number we have right here so when we're checking one we can see with one is less or equal to the target that we're checking so we'll subtract one check with zero and add that here 2 and 3 are going to be greater than target we're checking so we skip those now with 2 we start with 1 we move back 1 and we add that 1 here and with 2 we move back 2 and we form two here so basically what's happening it's like it's kind of like the climbing stairs problem where we're looking back to see how many combinations we could have formed at that point because we know if we subtract two at this target we know that uh whatever we had at the base case zero or whatever base case or whatever case before that we're checking for we can add that up to our next target so it's kind of a bottom-up tabulation or bottom-up tabulation or bottom-up tabulation or dynamic programming solution and at the very end we should have our total number of combinations for the number that we're checking okay so what we'll do is first create our dp array start with all zeros and have target plus one and the reason we have plus one here is because we need our zero as well as our base case so recall that dp0 is going to equal to one always now for t and targets are actually t in range of one to target plus one we are going to check every single one of our numbers for n in nums if the number that we're checking is less or equal to target let's update our dp array for dp t to equal or plus or equal dp t minus n now at the very end we should have our answer to just return our ep target okay so let's see this works okay typo okay so that looks like it's working so let's go and submit it and there we go so time complexity is going to be of n times o of t or n times t and we do have our dp array so that's going to be o of t space now i knew this answers this problem because i've seen it before as i was trying to solve it again i was realizing that this is more difficult than i remembered even though the solution is simple getting this logic um getting the intuition down was actually more difficult than i remembered one thing to note is like if we had negative numbers allowed here how does this change the problem well that changes it a lot because now we could have an infinite possible number of solutions that we had negative one and one how many ways can we form zero there's actually a lot of ways we can form zero we have negative one we can have negative one is infinite right so we have to have some sort of limitation a maximum number of numbers we can use to allow that to work now would this solution still work for that customer problem i'm not sure so that's something i want to think about before i try to answer that anyway i hope this helps there's definitely a lot of solutions to this recursive solutions definitely work as long as you memorize but i like this because it's very simple okay thanks for watching my channel remember do not trust me i know nothing
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
1,945 |
hello so this question is sum of digits of Str after convert so you basically you give it the string and then you convert to the integer so I represent 99 and then the K represent how many um like iteration of addition you're going to have so when K to one you just know do it once if k equal to two so when you got the value for the first one so it's going to be 1 + 2 5 + 5 and then at end going to be 1 + 2 5 + 5 and then at end going to be 1 + 2 5 + 5 and then at end 3 three then you want to start it over so three will be becomes 3 + three so three will be becomes 3 + three so three will be becomes 3 + three so you want to return six so this will be you know the iteration based on how you um Traverse right so convert to integer and then later on we you know check a uh how many times for K and then we just reset the sum equal to zero every single time and this will be it all right so first thing is we need a sh Builder to actually store the value so for Char C and A that two Char R and what I need is. p c minus a + one R and what I need is. p c minus a + one R and what I need is. p c minus a + one so I'm actually convert this to integer in the Stream format right so um yeah so checking my length if this is equal to one I can convert this so to sh so I can convert this to what to the character so character you know s integer so get numeric value and it's going to be S SP do two string. chart add as zero so this is actually giving me the integer right so if not then I'm going to say okay um I using this value for string so equal to Builder and also sum so you can say result doesn't matter an IDE you want to return result so while K is greater than zero we need to keep traversing right so when K is squer than Z so k- squ than k- squ than k- squ than Z and also we want to make sure the length of the Val is greater than one so we can keep doing this and so some so result will actually reset to zero every single time and yeah so val. two string uh sorry val. two Char so this is going to be the integer right and I just keep doing this so the one of the reason why I don't want to convert to integer for the Val is because you know um if this is a pretty long oh it's not long but whatever and I'll just keep adding so result plus equal character get numeric value SC see so once I finished all of the traversal so 9 + 9 + 9 + 9 so comes 36 traversal so 9 + 9 + 9 + 9 so comes 36 traversal so 9 + 9 + 9 + 9 so comes 36 so I'll just you know add a value so Val becomes string. value the result so um yeah and then once you de okay and if you break out a full Val then you return the result so you get a So you're using a string to convert to what uh in value and then uh later on you want to you know come right back so this is a trick all right so let's talk about time in space this space so I will say it's all of what all of s represent the sh s and time this is also time and the worst case going to be what this one right all of K times all of v represent s so uh SV uh SK sorry all of SK all the time and all of s for space so this will be it and I'll see you lat I
|
Sum of Digits of String After Convert
|
finding-the-users-active-minutes
|
You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum of its digits**. Repeat the **transform** operation `k` **times** in total.
For example, if `s = "zbax "` and `k = 2`, then the resulting integer would be `8` by the following operations:
* **Convert**: `"zbax " ➝ "(26)(2)(1)(24) " ➝ "262124 " ➝ 262124`
* **Transform #1**: `262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17`
* **Transform #2**: `17 ➝ 1 + 7 ➝ 8`
Return _the resulting integer after performing the operations described above_.
**Example 1:**
**Input:** s = "iiii ", k = 1
**Output:** 36
**Explanation:** The operations are as follows:
- Convert: "iiii " ➝ "(9)(9)(9)(9) " ➝ "9999 " ➝ 9999
- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36
Thus the resulting integer is 36.
**Example 2:**
**Input:** s = "leetcode ", k = 2
**Output:** 6
**Explanation:** The operations are as follows:
- Convert: "leetcode " ➝ "(12)(5)(5)(20)(3)(15)(4)(5) " ➝ "12552031545 " ➝ 12552031545
- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
- Transform #2: 33 ➝ 3 + 3 ➝ 6
Thus the resulting integer is 6.
**Example 3:**
**Input:** s = "zbax ", k = 2
**Output:** 8
**Constraints:**
* `1 <= s.length <= 100`
* `1 <= k <= 10`
* `s` consists of lowercase English letters.
|
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
|
Array,Hash Table
|
Medium
| null |
338 |
Hello guys welcome back to take devotion in this video you will see accounting this problem wishes from list dated 28th challenge 16 personal problem statement the problems the giver negativity born for every number white range of do to calculate the number of waves in the Representation And Toys For Example In To-Do List Number 90 Toys For Example In To-Do List Number 90 Toys For Example In To-Do List Number 90 And Individually In Hindi Latest Will Start From The Number 01 02 Apr 19 2013 This To-Do List This To-Do List This To-Do List Loot Is Vansh Encounter Set Button Five Physical Activity 29 This Process All The Number From CO2 And This Is Not Know Who Will Return This Is The Problem Solve This Problem With Number 90 Individually And Problem Simple Number 102 And Value Every Individual Will Give The Name Of All The Best 30 Subscribe 151 Soon Subscribe To The Number Tweet Message Case From Two Numbers Will Be For Bat Traversing Teacher Aged 110 Will Be Equal To One Like This Will Ask All The Counterfeits Introduction Every Number 102 End Mon Rate Time Complexity After O'clock Traversing Between Every Number 108 Times The Number Travel End Points Number Division Number Four Thursday Laxative In the range of the time will do any problem on the maximum value subscribe button No Veer E will be equal to the number of seats in More 307 323 See The Number Subscribe This Is The Difference Between The Subscribe Latest Channel Subscribe subscribe and subscribe the Channel Will Always Be Set That And Dividing By Two Is Nothing But Right Shifting Of Number By One But Sorry For The Last Date And Were Right Setting The Number One Beat The Last Set Will Be Lost In The Afternoon Number Awal Admit S Compare To A Recent Debate Number Isi 10 Significant Will Always Be 2009 Subscribe Now To Receive New Updates Number 210 subscribe to subscribe our Number Two Number And Set Se X Is Equal to the number of seats in Noida and this is already explained latest job is one number five video number to the number one number to the number is the number which is the largest one digit number to the number of the latest busy schedule number and Last Will Always Be With Us Dard Is Website By One But In This Last Will Be Lost Souls Will End Up With The Number-10 Which Is Equal To The Number Of The Number-10 Which Is Equal To The Number Of The Number-10 Which Is Equal To The Number Of Seats As You Know This Is The President Will Also Be Considered A Representation In The Most Obscure Number 90 Number To The Number Valve WhatsApp To The Number To Go To The Number 2 And Not The Number To The Number Five Video Solution Udayveer 127 Ki Similar For This What Is This And Even Numbers For The Number White Heads White Oo Will Be Having Same Number of Rabbits Number Four Wheel Chair 39 Sight Mark and Number Date for Years Back to the Numbers Will Be Having One Playlist Sweet Will Be Having One Plus Overbusy Similarly You Can See Your Job Also Subscribe Cancel Problems and Use This Solution Not to Solve So problems will start from 0 to which will start from left to right the solution for the number Thursday subscribe to the Page and weather this number is and event and will you simply adv1 and 80 to find the solution so let's not solve the problem to understand And Computer Current Account Using Back To In Order To Calculate The Contact Number 102 600 800 To 1000 Will Start Getting From The Village Of Dhirwas Subscribe 120 Number Of Votes 0.00 For You And One And I Want To Be Next Element Which Do Not To This Vansh You too easy This is the Video then subscribe to the Page if you liked The Video then subscribe to subscribe the Video then subscribe to subscribe Free Loot Lo Quantum Set Beg Se When Will Be Equal to One Plus Account Upset One by Two Which is OnePlus This 223 Luttu This 80 Account Upset With Equal To This Point Ko Is Point Se Zara Subscribe and subscribe the Channel Every Bit Of Solution Latest Simple Veer Value Which Is The Way Want To Add To Numbers 09 2012 102 Number 90 2012 Kuch Der Format 0 Will Start From Equal To One And Got Accusation And How To Calculate This Is Nothing But They Will Have To Look Back To You Want To Avoid You To Back To Which Is The Current President Effigy Number-21 More Number 204 Number For Storing Din Tarzan The Solution in different languages Subscribe Like Share and Subscribe
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
108 |
hello everyone welcome back to the channel today we are going to do convert sorted array to binary search tree let's understand the question first then we'll move to the approach given an integer array nums where the elements are sorted in ascending order convert it to a height balanced binary search tree a height balance binary search tree is a binary search tree in which the depth of the two sub subtrees of every node never differs by more than one okay so we have been given an array a sorted array and we have to convert a height balanced binary search tree this is the question so let's understand it how we can approach this question so as we have been told that we have to create a height balanced binary search tree okay so the first thing that comes in our mind is if the array is sorted then we can have the middle element as our root node okay so let's try to create the binary tree for binary search tree first and then we'll see how we can do it programmatically so if i take 0 as my root element i'll have 5 and 9 to be on the right side or right on the right subtree and this two elements minus 3 and minus 10 will be on my left because they are smaller than 0 and 5 and 9 are greater than 0 okay now let's again create one more node so what we will do we'll take middle of this two elements that there is no middle so we can take either three or we can take either ten so let's take 3 over here now we know that minus 10 is also smaller than so we'll create another node and it will go to the left here also we'll do the same thing because there are two elements and there is no middle element so either we can take this or this so we will take 5 and then we will take 9 so this is how this is the one binary tree that is possible the another one can be like we can have minus 10 over here and then we can have 3 over here similarly we can have 9 over here and we can have 5 over here like this one more tree can like there are multiple options that we can create so we just have to return the one possible binary search tree which is height balanced okay so how we can approach this question the simple approach will be that we take the middle element of the array and we create the root node and recursive like and we call the recursive method to create the left subtree and to create the right subtree so what i will do i will get the middle element okay middle element and i'll create like for example my middle index is 0 1 2 okay so my middle element will be index will be 2 this will be index and it will be 2 what i will do i will create new bst with norms index 2 okay then i will what i will do for this is bst okay suppose now this is bst dot left i will call the same method recursively and for right subtree also i will call the same method now how will i identify so for that we will pass the range the start index and the end index of that array so let's try to understand this on the coding screen so we are on our coding screen now first the first basic condition uh we can have is that if nums dot length double equal to zero we will return null okay now what are we going to do is we'll create our helper method okay so we'll create a method with return get bst okay we will pass the array we will pass the starting index of the array so currently our starting index is 0 and we will pass the ending index the end index of the array which will be nums dot length minus 1 okay now let's create our helper method so this will be public public end sorry the return type will be tree node public tree node get bst we will accept integer array one will be my start index another will be my end index okay now what we will do the i here the base condition for to like to stop the recursive call the base condition will be if start index is greater than end index we will return null okay now what we will do we will create our bst so we'll do tree node bst is equals to new tree node and we will pass the value okay let's pass the value and the value will be nums of start index okay now we need the middle index also okay yeah because start index will not be my root node correct our root node will be the middle index so let's find out the middle index first middle index is equals to start index plus end index divided by 2 will get the middle index and we will create our root node with the help of this middle index okay now what we will do bst dot left is equals to get bst this is our recursive call and we will pass nums now what will be my start index for the left subtree of so left subtree for left subtree the start index will remain start index only but the end index will be middle index minus 1 correct similarly for bst dot write get bst our recursive call nums are array now start index will be middle index plus 1 and the end index will be end index correct at the end we will return bst okay let's try to run this code we have some error yes so this is start index and end index what is happening return null okay let's again try to run this yeah this is working we don't have any compile time errors yeah this works so if you like the video and share with your friends and also don't forget to subscribe the channel thank you so much for watching the video bye
|
Convert Sorted Array to Binary Search Tree
|
convert-sorted-array-to-binary-search-tree
|
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** nums = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted:
**Example 2:**
**Input:** nums = \[1,3\]
**Output:** \[3,1\]
**Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs.
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in a **strictly increasing** order.
| null |
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
|
Easy
|
109
|
1,402 |
Do that Awadhi kaise saare berry lover point welcome recharge nakul help we have reached but number 181 maximum has been reached here we are broken heart problem if I say then don't be afraid we want to say hard that today EMP Such problems of 2002 BDP which have been hot marked on the lead are going to solve this different problem. The question in front of us is that the name has been reduced in this ad during discussions. This question comes that Saif is taking a data backup. So basically you have it near you, inside the input, you have the address of satisfaction where you said, this - address of satisfaction where you said, this - address of satisfaction where you said, this - banal this - banal this - banal this - 80851 this - manner 80851 this - manner 80851 this - manner is good, okay, so this is that satisfaction level. And the end of this thing, I said that this is a little late, this is the conditioner of Everest dish, this is third, this is forced, this is your satisfaction, love of all these dead cells, okay, what to do now, one word will remain one. I get one shape and one time to make a dish, only here you can subscribe but by building industrial projects and development environment and subscribe and it will become the strongest profile, all those who do it in Cuttack, you here they Let's go and do your personal lives together. You are going to meet the assistant so that you can attend the meeting regarding your dream job that is WTO, what you have to do. Using that, you can get the maximum possible discount on it and everything is free. If you can unlock the thinking, then you will immediately go into it, use the gender, drop it in a page and read it towards the proof, Free Trial Now, we like time, confident of different, how will you fashion the lifetime of any dish, this word, its lied, like time. There is no way to fit in, his time remains mandi black, this is how you will get it out from his satisfaction level, it was said, okay, Meghnad, maximum evening of life time, official decade, depression, okay, then you will be able to get maximum time out, maximum like time, you will be able to get it out. Don't do anything and be mental about yours, look carefully, I want Maximum Value of Life Time Corporation, there may be confusion, the telecast will be Manchurian for sure, let's do a test and the control will be less, let us know if I had the data - Wall - data - Wall - data - Wall - 805 - 805 - 805 - Sexually, I don't do this, I do this, what did we do? Scanner, we said, I selected two here, two values, all are absolutely great, contra voucher, this one and this one, rather, the divide medicine is no longer big, say here. Not just and discard some dish, so I edited it, I said, I am making it because I need it in the mixer, we need a contra voucher, now when - 1090 is forgiven, I when - 1090 is forgiven, I when - 1090 is forgiven, I came to the answered gram - 121 because first a came to the answered gram - 121 because first a came to the answered gram - 121 because first a secondary will be made, plus less than 0.2 Hey, this secondary will be made, plus less than 0.2 Hey, this secondary will be made, plus less than 0.2 Hey, this will become plus, if you do this, it will become MP. Gaya - 100 plus Gaya - 100 plus Gaya - 100 plus 1515, so this is a solid reason soon brother, no problem, now let's understand this, there are all the apps here for four, three, so I have to discard the date on duty. No, just shift it to how to make hair care, first right to Kamakhya Kapoor, now what did I say to it, bride two cups 2011 to it, ministry 312 to it, I am recent 4133 light, making it here, it will feel like a disease will be cured, then this which I will make one more and only it will appear that the investor is making a meet from the Puranas, then it has come, then after this an option will appear, first the other girls got married and then they live separately, then the team has come from here, then two plus 6 plus 1280, you understand the answer to this. How to remove Gaya Nal Vikas - One Minus How to remove Gaya Nal Vikas - One Minus How to remove Gaya Nal Vikas - One Minus Point, if it creates any obstacle in the negative company of all of them, then that MP set is saved, then the matter goes to Answer Tyagi, blessings in it. MS Word is doing this to me, what all things? You tell me that we also do dry ginger, we also dry and see for yourself that in adolescence, I can ignore any one country if I want, and if I want, I can also include it, so it is a thing. I have it, if you want, you can edit it, if you want, this is a map for a few days, so please send a clearly simple question to me on many graduation patterns, why is it written to increase the height, but simple, send a question on the upset pattern, here we are If you look carefully, do you have any set from late, it is set to the satisfaction level where there is a sarcasm, there is also one that has been given to me. Always know that the one who made the first rally 108, the one who included the second welcome two, I am going to do this gooseberry at any cost, who is going to force Tiwari under, what is this 1234 brother, I would rather have given time on the starting off, 1 will be the big cricket or Then the time will become yours, then your time will become free, then your time will become real time and all this is this section level, so I have selected their commission time multiple is accurate, that is interesting inside, see this, air tight, this is how to do now. Message me that what should I discard and what should I hang out, put on the phone, have done the ghee volume, whether I want to take anything or not, and have dimples 101, I am the same problem with you till 2018. There is a request on the pattern from the net, here I have 14, 10 and 1 - Magh 10 and 1 - Magh 10 and 1 - Magh Shukla, I will do it, that is, first set it at less and set it at two, then what is the answer, then the answer is - 1480 camphor, - 1480 camphor, - 1480 camphor, now what does my mind say, Amrit mind, this Said that or what should I do now, should I search on them, this text is ok, my mother's funeral pyre is ready, after the garden, I have the option either I input this - mind or I either I input this - mind or I either I input this - mind or I input this minus one, if I If I input this mixture, then my answer will be there, why will it take my answer, I will give my own answer - 411 notice - flight can be done, - 411 notice - flight can be done, - 411 notice - flight can be done, those people, so what is inside it, lol - 150 grams of flowers and mine. The answer has become - One - 150 grams of flowers and mine. The answer has become - One - 150 grams of flowers and mine. The answer has become - One OK, my A. Here I am the empire at the ends, so I ignore it or destroy it, if I do the measurement, then village vinegar is the romance part plus that I am inside the answer - love is about to happen, then inside the answer - love is about to happen, then inside the answer - love is about to happen, then its absence - department. 04 I have come here, its absence - department. 04 I have come here, its absence - department. 04 I have come here, my answer is still not Maan Shukar, I will use it in printed form, so I have made a note of this, if I go for going out, then this is the formative view of my pregnancy, inside 12 plus puberty, then what about me? Will be - Forced to be done, the then what about me? Will be - Forced to be done, the then what about me? Will be - Forced to be done, the work has been completed, it has come out, it has been in the answer, 12 plus minus one Dr. Okay, then the ghagra load came out, when he became unconscious, if you do this on my bus mirror, do you write in this section or not, then one The answer is to hear the expenditure here, to increase the extra, it has been collected - the entire amount of Rs. 150 has been paid, the collected - the entire amount of Rs. 150 has been paid, the collected - the entire amount of Rs. 150 has been paid, the answer is also MS Word, it will be invested here, it was done, he became happy, okay, so he should go on another journey by joint Done from here, will take extra Engaged, okay, in the same way, from here you went to that, in the same way, here onwards, Mahesh Kumar must have visited the camps here, tears have formed, call your window here, or will I call my slot here, while doing this, Crops, oh how? Those bases will remain as if my maximum auspicious 1234567 will be transferred to such a sum, then I will give a simple answer to the final answer, this is not a game or anything else, so I said that I will make a late review, I will install it to invoke the function. What is it that at this time I have passed level 267, I have passed level 167, and send message, send letters, do the work, send message, send letters, I am working, that's it, and at what time I am now, I have passed that, then pass the induction. Why is it important? What is the meaning of repeating office element? What is the current element? Passing the time is important. Passing the time. Why is it important to pass the time? So that I can find out what I need to do from the tip to the tip. Write on your own Edison. The level has to be played tight, so the thing is, time has to be passed for this, time has to be passed, by selling you, I said simple, before long, if your induction is a 1222, I have already come out of your satisfaction dot size. Roshni coming out of the turn off side is the same thing as applying obscene hair to hair, which I can say if it seems that if I make a request, if I ignore a current element, if I repeat the current element, then I am the answer. What will become a pimple here? Now simply if I am recording the current element then I have found their item fit. Complaint satisfaction and a different times have rather that satisfaction of water in index right by asking for time with time is sung. Disco alarm on this, how much time will it take? Time plus Mal Iqbal Kana. This will be and which way to come will install it next. Okay, next is the save part, if the save part is front, I told you that I am solving the chord of this one. And this qualification and the record of worship made for the whole year will ask us about those quantities, for whom have we passed the satisfaction, the index will move forward, my time will also move forward, okay, this is how I did the Swiss Roll now. If I write the active case here, write the case with one slot, then I said just select one, will there be any lifetime profit plus in it? The element on which I was standing, I was not taking Cancer 80 in Gurgaon at that time, it will be considered as replaced and moved ahead. Solved satisfaction and here I have not written the element but the sum of the time from the time and with the turn on this moment that the expert of the experts has left the field like this and wrote moving and similar will come directly inside it quickly check the Let's check, wrong answer has come, sir, why because you had left it, that we have to do that, I am the last two celebs caught off-guard caught off-guard caught off-guard alarm set, this ancient dot is Android, now just try it one more time So you are wondering whether this method works for I think or reminding me what I do, I hope for ma'am, I have taken it. If you have not subscribed then let's find out the value of AR Rahman on Friends. Quickly speak is equal to safe research that Sachin out size is fine, whoever has come late that in plus one and tractor maintain plus one, I have agreed to this - maintain plus one, I have agreed to this - maintain plus one, I have agreed to this - with now I have called, passed at this time, subscribed, see this Okay, so I have done this medical store and returned it, first chapter, sorry, but to create it, to make sure to subscribe, to make a return, after selling the pain, go and check, the answer is still lying inside the home DP, if Deputy Governor Arnold is lying, then get it returned, it is not just for pimples, if it is difficult, friend, the answer is lying, that return said, if why are you making recharge calls, Amitabh is like that, it is absolutely right brother. It did n't work, I said, try driving it and see if it runs or not, you also did not talk to me immediately brother, I said sorry, you should try driving it, now mount it and try driving, he said DP Call here to try it now try it picture read always commented check and so on ok so we have built the top dip solution till now Till now that feeling is not a question, simple affection has till now given me the girls of my kind, I have speeded it up to maximum and the DP apps have created waste oil, after that the DJ ones have left the DJ pickup dance and returned and told them. The second one collided, after which it is absolutely fine, I pulled the next one, I will do it through WhatsApp group, now I will do bottom-up through Russia, so I do bottom-up through Russia, so I do bottom-up through Russia, so I said, I boarded it, passed it inside myself, but the satisfaction level is director by level, what to do now. Have you laid down half of the slippers, take it, you guys have written that I love you too sexy that I love you too sexy that I love you too sexy that modern cricket has been made letter after payment details pain plus one kill letter in 110 plus one has become an expert phone now what? What should I do now, I used to capture its best questions and answers, did he reach and update, he said that the index of is favorable for acidity world tour and drop, then the answer is neither that much, the cent has been raised, so it is not necessary to strengthen it. Now if you look inside the top downloads solution here, if you look inside your top dual listing, you will clearly see that you are clearly owed the patience you have shown in the index parameter and the time parameter. The value of both of these was definitely sent in the beginning. Okay, and how far did you go with your index? Start with your indexes till the end. Time is also going to throw you the same. Your time is going to throw this. If there was a cash deposit option and a loan in the above section, if this was the last one, then you would have taken a tower bottom approach, you would have reversed the same trend, while some of my bottom approaches would start from the water and make withdrawals, how is this absolutely correct, so I What did I do, I said that the loop will run, that will get the admission, start ad contact, start network work, phone, I said, which one is totally last, if it is Edison size, if the end placement is this side, then which one will be the last one, what will be the last date and end? The last section will be the answer for the button. In the video I told that I can find it in any case. If I take you to the grocer, then I have told you that 80 are needed in Anikesh, but if it is the gate of Tighra, then follow it. Which is the MS Word extension called next9 More Advanced Psychic Himanshu Call Record Your Intellect Subscribe Like Other Time - - Time - - Time - - Very good for - - In this way I Very good for - - In this way I Very good for - - In this way I said what to write inside it, now let us send simple also above You have written the recording, bring it inside and present it, then when the suicide note has not been found, okay, then I played it here, I pasted it. Sir, then what to do now, you said, the reason is simple, there is nothing where the recording is. And from the replacement OTP tell the pimples here index plus one and time plus one and also some eggs inside I heard and saw friend this is done TP of conduct Laxman has given to Ajay and this time plus one is fine his this gives pimples faster Do it, I have Yogurt DP of induction and time so all this is done ok and after that I am doing the answer of playlist is done, I have to install it but DP of index and time is inside next time. Inside this whole story and Ram Sir where will it start, if you start the top material present then end comments were coming here, if you are starting the paper with Ma'am then told you that 2000 is lying then you can message MS Word. If you are starting then how far will you go? That DPO is the golden answer on medium flame. The resistance must have increased so I edited it and returned it to DP of 40. Now I tried it once and tried it. Its update. I will do it, return it, solve it, show satisfaction after listening to it, 84, show it is taking a lot of time, it is accepted, submit it, show that it went well, so in this way, we have also done the bottom approach, if we talk about time chemistry. If I change my total then time complexity seems to be that do only one thing and enter the need to. Now the question arises whether I can reduce the space of this NCR or can I make it medium flame. Yes please remind me whether there is a scope or not, I will check, I will have to check, it depends on the dip, so I have answered here, the camera is different, so the time is ok, so the tip off that the induces time depends on what, not only by covering, it also depends. These lakhs of rupees per kg of rice depends on the defeat of district public. See, it depends on your DP of index plus one time plus one. Okay, this time the next one or it depends on the different express time. It is up to you to pay attention and see, you understand. I came to know what is this Next and Time has become an electronic Next Talk about Next9 Time Plus One Next If this is my control this is control and this is the current column Subscribe from Next9 Newsroom Now you understand this Is it that my DPO contacts from time depends only on the next process, if I have only the next my crying is not for the whole studio which I have made, this whole of mine will not break only by taking more, I will marry you only for this You should sleep after noting the upcoming notes. Okay, so if I am trying to find out the answer to this one, then just tell me the form of the next one, nor will the balance increase there, tell me the reason, I will get it out from you, then I said, ok. So I quickly copied this code and I fitted another function named one small tattoo okay it is very simple look at this attack two Russians one disease name is vector 's paint current whether science barrel From above 's paint current whether science barrel From above 's paint current whether science barrel From above many houses inflation amazing districts thus made Waheguru that restaurant next removed it so much that I am written here loot is ok one thing how to make and after every alteration every time a Hydration will be complete every time, do one debit exactly like this. Basically, what if I explain to you from the bangle studio, will you understand that when Solkar was trying by the studio, you will roll like this, do this, then you They were questioning on this that friend, here in the setting, what are you doing, you are building up the G, it is okay by using all these balances, whenever you are doing this, by using all these. You can use all these if it is me and I can say that I am here next subscribe to that I have added the root of our cold officers next9 Now I called the function of solitaire two once and ran it and tried to front it. This is accepted, I said submit the phone, this is mine, it is very good, so in this way I asked this question, where turn off the first one, you were following me by using this door, using this. After this you can see this subscribe here I can turn this side off this question that I can solve this problem within the turn off one so I said yes then I said yes absolutely do it It is possible, it is good, the last option we did, we will keep it in the fund, or will we mind 21 batteries, the next one with a little current, if we want, we can do it with a single chapter also and that single bed is on the 53rd. If I can switch on then brother how rd I explained to you how you can do it in servicing within 10 minutes call a question then you will reach here the solution should be there and it is also possible inside the forest there you can do it once daily You will have to do the next 9 yourself, brother, how is it happening in the over? I have checked once and come and you will finalize the match. How can I vashikaran him using 3D alarm? If it is difficult to make this round, then we will help him in this. I cut it down, I don't understand anything, what is written on this very old question, I had asked it last time, but it is ok, interesting skill, if I ask you tomorrow, Pallav, this question is worthy of being asked, that's why some such child The condition may get worse, we will make you understand like time, fashion a little time set, I am not able to understand anything except related to protection brother, how to do it has spoiled it is a good important question, it was good, how much is the code, a little fold will not do anything. So simple is coming as written, I haven't done anything special, simple is simple, nothing has been given dynamite to simple, I will meet you with your next question in the next video, but to make number one, what is happening in between so much time? It's time, I should call. My phone is not my phone. Time is time. Tomorrow 531 and 532
|
Reducing Dishes
|
count-square-submatrices-with-all-ones
|
A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time.
**Like-time coefficient** of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i] * satisfaction[i]`.
Return _the maximum sum of **like-time coefficient** that the chef can obtain after dishes preparation_.
Dishes can be prepared in **any** order and the chef can discard some dishes to get this maximum value.
**Example 1:**
**Input:** satisfaction = \[-1,-8,0,5,-9\]
**Output:** 14
**Explanation:** After Removing the second and last dish, the maximum total **like-time coefficient** will be equal to (-1\*1 + 0\*2 + 5\*3 = 14).
Each dish is prepared in one unit of time.
**Example 2:**
**Input:** satisfaction = \[4,3,2\]
**Output:** 20
**Explanation:** Dishes can be prepared in any order, (2\*1 + 3\*2 + 4\*3 = 20)
**Example 3:**
**Input:** satisfaction = \[-1,-4,-5\]
**Output:** 0
**Explanation:** People do not like the dishes. No dish is prepared.
**Constraints:**
* `n == satisfaction.length`
* `1 <= n <= 500`
* `-1000 <= satisfaction[i] <= 1000`
|
Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0). Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.
|
Array,Dynamic Programming,Matrix
|
Medium
|
2192,2193
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.