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
31
Hello guys welcome back two decades and you will see the next permission problem between this point number-31 100 latest the between this point number-31 100 latest the between this point number-31 100 latest the problem statement in this problem Thursday graphically greater attention of number in this channel it is not possible to rearrange the lowest possible replacement used only So let's see what does not taken for example of elements 12141 and subscribe the Channel subscribe button more that in the second example of wealth element sir givenness 1243 this updater sequence is made for 132 400g sugar ativ vittu and subscribe the Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to subscribe the Channel sweater sequence because element is actually more digit number you can also give the darkness is nothing button number entries numbers 1400 21012 next two numbers possible Otherwise sequence no latest example printed number one two three idiots subscribe The pic chanod appeals to the left and you will have the great width greater noida xu2 please like this ki wo ke 1000 research right 100 this is and greater element but is not the number 123 liberties subscribe The Channel and subscribe the Channel will have to the number is 12332 not 12332 so a greater than 12323 for the next greater sequence David Greater enrichment of this basis will decide which 1251 increasing in the last but not least subscribe this All the element in order to find quarter element you need to Modi speech to the left birthday wishes suggest neck cigarette element will not possible for you Will Have To The Problem 9 News Simple End User Name Of The First Element Thursday Must Subscribe For This Is Not Subscribe To May On Let's Move To The Great Khali Way Om The Next Greater Sequence So You Will Have To The Pick Up The Life Is The Winner List Weightage By The Way 0.2 Pendant Three Layer 323 34 Weightage By The Way 0.2 Pendant Three Layer 323 34 Weightage By The Way 0.2 Pendant Three Layer 323 34 In Ascending Order Which One Will Have To Leave With Position Which Will Move To The Element Which Element Will Be Having Not Affair With Prayers For 31243 Subscribe To Element Renovated And any other on the lancet ok facility immediately after some time complexity friend is and of baroda of birth traversing enemy friend but not a special case a that newly latest see the other how switchgear mix graph noida 1234 to 1342 e according to the preservation in order To Form the Next Greater Sequence Can Easily For the Greatest Man Can Win Pick Developed from The Greatest Threat That You Want to Connect with Later Sequences and Not Just Any Other Better Sequence Dr. That in Order to Find the Greatest Wealth Will Have to Melt Subscribe This Channel subscribe to the Page That Nearest Smaller Element Festival That Day Rest Smaller Element Will Be Having Low Avengers Complete The Element To The Laptop Soldiers With Subscribe And Subscribe To The Channel Is The Greatest Fear Of Elements In Ascending Order To Make The number possible be the first to last elements one and you want to form the least possible number of you are sending you servi will always be in ascending order will make the element subscribe 2012 lowest possible number which will assist you have replaced with All Elements Which Will Always Be Greater Than 3000 Half Limit Anything Wishes For Dal This Sun 2008 Will Always Be A Greater Service Element At Least Plus One The Current Element Water Element To The Number Possible They Will Give Me Three Do And The Last Decreasing Were Increasing The Number Three Do You Mean By The Last Hour In This Problem Is Required Lipstick Example Share The Element To Three Four To Avengers Pe Element 148 149 323 427 subscribe to the Page if you liked The Video then subscribe to our Channel Apne chhodi di greater than there original number OK new number must be greater than the original number and its debut is possible so you have increased number of you want to two. Two to Three Subscribe The Worst Position subscribe This is the Video then subscribe to the Page if you liked The Amazing 1234 Subscribe Candidate Element Subscribe I have explained that you need to move the app to the left and right the previous model element at Index Cases Even Tho Not To Speak But You Can Replace This Point With This Element Great Value In Between The Subscribe 1234 To Acid Like Share And Subscribe Our Element Will Get After Delhi Will Always Airplane Mode On If At this time with five bigg boss-5 savings care unit value ok and were replaced the boss-5 savings care unit value ok and were replaced the boss-5 savings care unit value ok and were replaced the same with the same position subscribe 3512 4521 subscribe to subscribe and subscribe the subscribe 54321 subscribe that chords issue of finding any element between these foreign five To the light on this descending from it's not present's tasty five 14 four wheel less hair fall welcome and pure graph change language share it will be 500 to 1000 and different but after dropping you will get the benefit of all these elements are not the least Possible For The Least Possible Subscribe - Possible For The Least Possible Subscribe - Possible For The Least Possible Subscribe - 151 - I Total Time Complexity And The 151 - I Total Time Complexity And The 151 - I Total Time Complexity And The Meaning Of The Name Of The Position Of A Finding Any Value Which Is Line Between Reduce Is The Previous Element Of The Pick Please Pay Element Pimple Twist To Draw A Line Between Two The Telegraph Candidate for Replacement Will Change the Way for You OK after 10 loot points to the last pick not know who will check the residing there will be no really mean middle aged subscribe and elements in ascending order descending order with special report subscribe now to the element in between this previous element of elements Will replace last date that value last entered ok morning this what they are doing a name from tiger alarm set last entered minus one and from name 28 platinum saturday that house will simply updater access value rights will not be selected value has a value class Chapter Twitter The Page if you liked The Video then subscribe to our Channel subscribe Videos Thank You
Next Permutation
next-permutation
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. * For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`. The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). * For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`. * Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`. * While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement. Given an array of integers `nums`, _find the next permutation of_ `nums`. The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[1,2,3\] **Example 3:** **Input:** nums = \[1,1,5\] **Output:** \[1,5,1\] **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 100`
null
Array,Two Pointers
Medium
46,47,60,267,1978
1,038
hello everyone today we are going to solve the report problem which is 1 0 3 so now and we have to convert it into a great tree such that every key history is changed to the original key value plus the sum of all the keys greater than the operation of the pst so as you all know that bst is a binary search tree in which the every no every node in it contains all the nodes which are right side to the node are always greater and the nodes which are to the left side of the node is always smaller as we can see over here that the node four the right side all the nodes which are in the right side of the tree is always greater than four and the nodes which are on the left side of the tree is always smaller than uh smaller than the four so as we can see in every node this uh this property satisfies that on the right the subtree which is on the right side of the node is always greater it contains always the greater element of the root node and the subtree which is present in the left side is always contains the smaller elements so over here as we can see that it is a binary it is a property of the binary search tree so what we need to do in this question like we are given a binary tree and we have to make a tree such that the node is ripped every node is replaced by uh the elements which are by the sum of the elements which are greater than that node so now let's get you into the our screen and see what the node says it says let's make this tree so that i can explain you out so over here the node is given four 0257 seven so what the string should be saying after the result it should be like as we go on the seventh the sum should now let's assume that this tree is given so what the result we need to obtain is that like as shown in the tree like over here uh should be converted into 15 which is the sum of 7 plus 8 is equal to 15 and the 6 should be converted into the 21 which is the sum of like 8 plus 7 plus 6 so let's for the brief understanding let's go to the one node and so that i can explain you briefly what this means so actually so how should we approach that this 7 should be replaced with 7 only this 6 should be replaced with 6 7 6 plus 7 and this 5 should be replaced with 5 plus 6 plus 7 and this 4 should be replaced with 4 plus 6 plus 7 plus 5. and this one should be replaced with one plus two plus four plus five plus six the 7 and the 0 should be replaced with all the sums like 0 plus 1 plus 4 plus 2 plus 5 plus 6 plus 7 so in this way this uh their whole sub tree should be transformed so what we need to do is that we have to get the tree like this only so what we will be doing as we all know that in a binary search tree let's give us the sorted order so if the if we made the inorder traversal of this tree it would be like 0 1 2 4 6 5 sorry 1 4 5 6 and 7 the inorder traversal of the kind of this tree should be like this so what we are going to do we are going to make an approach which is in the post order so as we start traversing from here and when we reach over here as we start transmission from here and when we reach over here then we initialize this as the sum of one let's make this tree again to make the for make this better understanding okay so find it out once this tree is saying to us this gives us two so as we uh are moving in a post order so we will be traversing still here now at this position our uh static variable which is sum would be initialized with the zero so as soon as we reach over there then we when we would be in order then the sum would be incremented ah the value of the node would be incremented with the sum so when we move to the 6 then in this way this 6 would the 7 the sum would again be incremented with the node value that is 6 so this sum would become 13 and now as soon as it goes on the left side as we are going in the post order so this sum would become 18 as soon as we again go to the this side this sum would become 4 and as soon as let's make it over here now as soon as we move to the left side as we are going in the post order the sum would become 23 as soon as we move towards this side the sum would become 25 as soon as we are pursuing from four so this sum will go toward this as we are going in a post order so this sum would become 24 and now we move to this so this sum would become 25 and this would remain 25 as the known value is zero and in this way it goes the whole traversal get completed and the whole tree would be substituted with the value of the sum so uh as soon as the value of the sum is incrementing at the same time the value of this nodes is or would also be changed from uh its original value would be replaced with from the original value to the summation value so as we can see that let's make this tree again so basically this is a tree now what we need to do we need to traverse order travel in post order and we need to make a function like perform the function rt functionality in inorder traversal so simultaneously we would be doing we would be traversing in the post order and performing the functionality in order and initializing the static variable which is our sum so let's compute it again so as soon as we start from over here we start from this node we start traversing in the post order like this so initially as we are traversing in the post order so initially no functionality would be performed until and this with each to the uh end node so uh when we reach over this node this then the load value then the node value would be that then the sum would be increase with the node value so as it was initially was 0 now it would be 7 and the node value would be replaced with the seventh so there would be no difference as it's a left the rightmost value so when we go in between reach to this node the sum would become 13 and the node would become 13 okay and as soon as we go on this reach on this value the sum this node would become 18 and the sum would become 18 okay so as soon as we reach over here node operation would be performed when we reach over here then it is uh in the in order form so we need to increase the sum that is 22 and then replace this value with the sum that is 22 now as we go again in a fourth order we reach over here then the we will increase the value with the node value increase the value of the sum with the node value it becomes 24 and this also becomes 24 we replace the value of the node with the sum as soon as we reach over here this would become 25 and again this and this was implemented so this so sorry again the value would be 25 only okay so in this way the whole the required tree would be obtained so let's write down the code so that we can submit this question so as we all know right uh the signature is given in it so first of all we make the static variable let's just tap it and sum we have to just make sure that we have to initialize it every time with the zero otherwise the report would not initialize it again and again so we need to initialize it let's make this bst to gst let's make the function first copy let's name this out okay so let's call this function out from here okay so as you all know we have we need to traverse in the post order so first of all we make the base condition that is node is equal to null then return otherwise we have to call b g s t as we are traversing in a post order so dot in order we need to perform the functionality so that would be node sum is equal to sum plus node dot value as this is uh asking for the tree node so as we are traversing and changing the value of each and every node so we would return the same node now i think everything is correct let's just run the code so as we can see that all the test casings are getting passed this is separated out so it's a hundred percent faster than any other java solution so in this way this leaf problem can be solved very easily with a different approach so i hope you like the video and you learned something please like share and subscribe thanks thank you
Binary Search Tree to Greater Sum Tree
number-of-squareful-arrays
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val <= 100` * All the values in the tree are **unique**. **Note:** This question is the same as 538: [https://leetcode.com/problems/convert-bst-to-greater-tree/](https://leetcode.com/problems/convert-bst-to-greater-tree/)
null
Array,Math,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
47
143
hi everyone it's cin today we are going to solve reorder list problem the problem is that we are given a list and we need to reorder that list for example in this case we are given this list one two three and let's say that it's an element or there are some elements this is the n element and we need to represent it in a way that one points to n uh two points to n minus one and so on so for example in this case 1 points to four and the to Four Points to two and two points to three and so on so how we can do that the way we are going to solve it we are going to starting from the middle of this link at least we are going to reverse that and then we are going to the first one will point to the first note in this one second one uh will point to the second one and so on so what we are going to do we are going to create two pointers uh a slow and a fast so slow We Are going to move X time faster so when the fast pointer will reach end of the array end of the link at list slow will be in the middle of that so after that we are going to reverse that list so now after that we are going to have four and two four and three right after reversing and we are going to start from the beginning of the array so one so now we have one and two and the four and which we have reversed so now one will point to the first node of this one which is four and four will point to the second note which is two and the two will point to the second note of this link at least right that we have reversed and that's that is the result that we are going to return okay first thing that we are going to do let's check our Corner cases if head is equals to null or head next equals to null then in that case we are just uh returning from here next one is let's set up our slow and the fast pointers least note let's call it slow and the same way least note let's call it fast and um now let's find our fast and let's find the mid of our Link at list so for that let's move our fast and slow pointers if fast uh next is not equal to a while fast next uh fast next is not equal to null or our fast next to next not equal to null also what we are going to do we are going to move our fast pointer twice and our uh slow pointer once so fast next and uh our slow next for the fast and for the slow it's just going to move once okay all right so now we have our mid which we are going to Define here so let's just uh call it a mid and it will point to our slow that's our mid so from starting from there we need to reverse our Link at list so for that let's just create one more variable let's call it a current now we are uh let's just call it current and we are going to uh reverse our Link at list so it will point to our slow next okay so while our current next is not equal to null what we do here we are reversing our Link at list starting from the middle right so we say that our we are creating a new list note here and uh next which is equal to current next and then our current next what it's going to point to our next and um our next is going to point to the mid next right is going to go point to the m next and the mid next is going to point to our next okay we reversed our Link at list here so we'll find the mid element and from starting from the meat we reversed our Link at list now what we need to do we need to merge these two lists so for that let's create a list Noe let's say that uh L1 list no list one let's say right it's pointing to the head because we are going to start from the head for the first one and for the second one we are going to start from the middle and uh from the starting from the Middle the list is reversed so it's going to point to the mid next right now let's merge those lists so for that we are going to say okay while our P1 is not equal to um Mid so which means that we are going to use P1 till the mid of the our Link at list so we are moving P1 and the P2 at the same time so not P1 but the L1 so L1 um and then what we are going to do we are going to take the meid next right it's going to point to our L2 next right and uh how about the L to next will point to the L1 next and uh L1 next will point to our L2 and the L1 uh about the L1 will point to our L2 next okay and uh find finally our L2 will point to our midn next okay uh let's run it not or actually we need to end here yeah we didn't set that they are pointing to head here and the same for the fast let's run it okay great it works as expected uh let's calculate the time and space complexity for this solution what's the time complexity is that the AL now we are first moving this is the first time first pass we are moving uh through our linkit list we are finding the mid element then we are reversing this is the second pass from the meat and then we are merging these two lists but uh it's 3 n but we are going to take that we can ignore the constant part so our complexity time complexity would be of n how about the space complexity in this case is uh since we are not using any extra space we are not using any extra uh Link at list so space complexity is going to be uh con it's going to be constant okay uh let's go over our solution one more time so what we do here we first find the mid element mid uh so first we are finding the mid element of our Link at list and then starting from the mid of the element we are reversing our Link at list at this point we have two lists so at this point we have a pointer to our um to head of our link list and also we have to our midd of our Link at list which is reversed so starting from here we are merging these two list in like first comes the first element of the first list then comes the um uh first element of the second list and uh we are progressing further merging those lists and time and space complexity is of N and a constant respectively hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
1,307
I had also continuing on this late code contest 169 per the last problem 1309 verbal a thematic puzzle so the problem says given an equation represented by words on the left side and the result on the right side we need to check if the equation is solvable under a set of rules and so the rules are first every character is decoded as one digit between 0 and 9 which means basically that it's mapped to one digit and every pair of different characters must map to different digits which means that no two characters have the same digit mapping and each word and results are decoded as one number without leading zeros which means when decoding numbers decoding each world of the words and decoding its result it should not give us a number with a leading 0 the last one is that the sum of the numbers on the left side which means the sum of the numbers for the words should be equal to the number that the result gets the decoded add as and then we're gonna return true if using these rules we can solve the equation and false if we can't so if we look at this one send more money here if we do this mapping where S will correspond to 9e 2 5 and all of this we would get send the word send gives us this number you can see here it's not it does it doesn't have leading zeros so to follow the rules there and more gives us this and the Sun gives us this and money also is M basically which says 1 which is 0 so still have this correctly and which is 6 this one is correct E which is 5 so this one is good a Y which is 2 so this one is good so the question is sort of a possible trade show and the similar thing happens with the rest in terms of the current we have that we have at most five words and at least two words and the length of each of them is between 1 and 7 and we have only uppercase English letters and the number of different characters use it are at most ten and that's like very good because otherwise we won't have a number to assign and we'd have to assign two letters to the same number which contradicts the rules so this here guarantees to us that it doesn't okay so now let's see how we can solve this okay so let's see how we can solve this problem so I think the first thing we have to just get familiar with is what the problem is asking so in the first example that we had it was the words were send and more and the result word was money right so this was results and so what the problem actually means is that we add send two more like this and we want to do a mapping such that sum gives us money like this and using the mapping that the mapping using this mapping here we're basically s would be nine you would be five and would be 6 and D would be seven and would be 1 would be 0 and I would be 8 and Y would be 2 so doing that what will happen is that we'll have here send would be essentially 9 u would be 5 and n would be 6 D would be 7 and we do plus more M would be 1 or would be 0 r would be 8 and you would be 5 and this essentially will give us 2 5 6 0 1 right and this basically means since we already mapped m to 1 so that's valid still right so that's this always mapped to 0 so that's good n is mapped to 6 so still valid E who already mapped it to 5 so still valid - which is why we can what we valid - which is why we can what we valid - which is why we can what we haven't mapped it while yet so we can just map it and so we say sure because there is no contradiction between the mappings right but a different way you can like her formulate this problem it's just a slightly different thing is that you could say okay it's just send I just want to find a mapping such that sent a plus more - money plus more - money plus more - money should put em in front so - money this should put em in front so - money this should put em in front so - money this should get me zeroes right because that's literally the same thing right a plus B equals C which means that a plus B minus C should be equal to zero right so instead of doing this because we want to find the mapping that is consistent between all three so we could just find something that gives us zero like this here and we would be solving the problem that way right and one thing you can notice here is that there is no way for us to tell from mapping right that is yeah you can't think of some kind of risk or something that we can so we can come up with the mapping and so when you have a situation like that we need to think about exhaustive search or backtracking right and so that's what we will be using to solve this problem and since maybe because there are a lot of possibilities we maybe prune a little bit using some of the rules that we have one handy rule that we will can use is that the that it's easy to forget because it's kind of just one of the rules it's that we shouldn't have any written zero no word or no result should have leading zeros which means basically that you can't have you can't map em here to 0 and have 0 8 5 right because they're gonna have these feelings eros or let's say you map o to maybe 2 and M to 0 and then you end up with the writing 0 or this we shouldn't do that so that's one of the construct for the mapping and so what we can do here now is every time let's just make sure we have a 0 we can have a 0 and have a carrier let's say for example the difference is 10 and have a carry that's fine because maybe we can still have 0 with the results afterwards right and so what this means is that if we so since we are using exhaustive search we need to find the state of our function okay what's called search here all right what would be the state of that function so one thing you can notice here is that well we could just make these consider these columns right each position because that's where we want to end up with a zero right so just consider these columns right and then consider this here each word and the results considered these rows right so that way at each position we can say okay now we will need to add because it's a plus and so we add the number and then for the result it should be minus so we subtract the number and if it's the last row we need to check if it's a zero because if it's not zero that's not a solution we need to exit right so what this tells us is that our search estate should be row and column right and something else maybe so what is that something else so at each position here when we are here we need to know the sum we have so far so that when we subtract we can check if it's equal to zero so let's just call that balance here because we want it to be at the end zero for each column right so we want balance to be zero for each column right okay and so another thing is that if we are in the last what are they our exit from this exhaustive shell swoon do we know that we are done right when do we know that we have a solution right so when do we have a solution and when do we exit right maybe we don't have a solution but we should exit right these are all questions that we should ask during when we are implementing something like this backtracking or exhaustive search and so here what we one thing is well if the current column is bigger than the number of columns right that means we already process it all columns for the current row then at that point we can just return whether the current balance is equal to zero right because once we finish it processing this column here we want to know if this is zero because if it's not zero that means this is not a solution and we should exit and so we return immediately and we will return immediately and check if the balance is zero that means it's a solution another state is when we are at the last row here when we are at the last row maybe for this one here sorry here I mean comes so it's actually because we are going from the left we are going in this direction it's actually for this last one here and when we are here and in the last column that means we are done right so we need to check a zero for the last one because that's the end now when we are in the last row so we are right here this is the last row what should we do so when we are in the last row which means equal to rose so I'm just know just one thing to notice here to note here is that column the columns is like the number the length of the law of the longest word and Rose is the number of words plus 1 y plus 1 because I'm adding the result as a row right except it has minus in front of it and here when I say the longest word including result right because that's also one of the rows and so here if I'm at the last row I should check right if I'm at last row I should check this here so I should check if the modular of the balance so I don't care about Carrie I can have a Carrie I will check it later for the next column right but I'm interested in that the modular of the carry should not be more than zero because if it's more than zero I might have to here and at that point I will no longer have zero as the final result and so that's not a solution so I need to make sure that the balance modulo ten is equal to zero and then once I do that for the last row I can switch to the next column right and so I switched to the next column like this and search for column plus one and the next throw for them since I'm done with this column I'm going to the next the first row right because I want to start from this here and so it's row zero and what's the balance is whatever is the carrier right so balance divided by ten this will give me the carry so these are when I have a solution and then when I'm the transition to another row right this is the part where I can exit if I you know that I won't have any solution right so this is the first part of the code now after that I need to transition to the next row if from done with the column but it's not the last row right so if it's not the last row and I just finish it this I think I need to write this again here so if I'm not at the last row let's say let's do this again so send plus more - let's do this again so send plus more - let's do this again so send plus more - money so it should be zero so if I'm at the last so here I have my columns and then I have my rows so if I'm at the last column of the let's say this world here if I'm that at the last column since I'm going this way so if I'm at the last column which means basically that I am at this position here what should happen I should go to the next word right so when at the last column or a row go to next row right at to the column zero right so go to the next row two column zero so that's what I'm going to do here so first I will just take the curl of the word at this row right so it's just words row since I already handled the last roll result so I know this is must be one of the words I can check if I'm at the last column so to do that I just check that my column is the last column and I check that by making sure that it's bigger or equal to the length of if actually just equal to the length of words that would be enough sorry the length of the current word now if it is I need to go to the next row so I need to search in the next row and I need to pass down the count the ballots that we still have right so here I'm going to the next row sorry I mentioned here that it should be column zero that's not true it should be the same column because we are processing column by column and so when I'm done with this one M here I should go to this o because I want to subtract it so I can see if it's zero right and so that's why I searched in the next row at position column and I still have the balance and since this is not the last row I don't need to check if it's zero yet I will check if it's zero only at the last row because the last row that's what I subtract the result right okay so now I'm at the now that I did the transitions for the cases where I'm at the boundaries so for the cases when I'm at the last column when I'm at the last row and when I'm at the last column for one of the rows right so now what I need to do is continue do it for the for these cases so for example when I'm at this R I haven't specified that yet so something in the middle that isn't one of the boundaries so for that one I will need to check if are here already has a mapping then I can just use that because it is say for example I'm at this here right so this e here it already has a mapping defined in this e so I should just use that because the same letter should always map to one unique digit but if I'm at a new letter like this case an error then I need to try a new mapping for L and try multiple different digits to see which one works right so for a letter basically what this means is that for a letter in a word a result that is not in the boundary there are a lot of details and this problem but just keep going keep repeating if you don't doesn't understand the section so for a letter in a word or a result that is not in the boundary we have two choices right so either there are it is already a mapping for that letter because we encountered this before or there isn't yet a mapping for it there isn't yet a mapping okay so we have only one of these two cases so if there is already a mapping for that letter that means that I should just use it right so use it right here try all the remaining digits the remaining and assign digit digits right to find one that works and if you exhaust all of them and we didn't find any one that works well we just exit and say this is not solvable and this is what backtracking does to find one that works and basically here we backtrack where here is where we backtrack when we don't find out like that works if we don't find a digit mapping that works and by works I mean and by works here I mean that it yields us a zero here that's what I mean right and so that's what we'll be doing here so first we check if a digit has an assignment and to do that we check just we need a map right so we need two maps for this we need a map to identify what has been assigned and two what letters and we need another map to identify if a letter is to identify if a digit two has already been used so I need two maps I'm running out of space here so I'm just going to put them here you can think that this would be at the start of the function but I would have two maps one is or a map and maybe an array so I would have letter to digit that has the mapping so this one here has the mapping of assigned digits and I need something to tell me for the second case here if a digit is remaining and assigned if a digit is unsigned because if it's assigned I don't want to use it and by using the map from letter touch it has two digits I can't tell because the key is a letter and so I need something that tells me if a digit is already assigned or not so I would have just digit two letter that is just an array of none and so if digit is not assigned it would be none and so if it's assigned it would have a letter at the value position and so here I have from zero to nine digits so those are ten digits so multiplied by ten and so here to know if a letter is assigned already has a digit are assigned to it so I need to check if letter is in latter two digits but there is another thing to remember is that I'm going from the right I'm going here so to find this position here this is just n minus 1 right and this position here is just n minus 2 and you get the idea so in order to get the letter here remember this is my current word so to get it I just take word and take the letter at position n minus column right because that's what the columns are present it's this is what column is and in Python this can be re-written in a handy way using just re-written in a handy way using just re-written in a handy way using just this operator here and so now that I have the letter I can research so what is the column I should stay at the same column right because I want to go to the next row but stay at the same column and go to the next row but one thing that will change is what is the balance now so if I'm going from here it's plus I need to add the value in letter to digit right if I'm if it's a minus I need to subtract it so I need to have the current balance plus the letter two-digit value all right which is later two-digit value all right which is later two-digit value all right which is later two digits for letter right just one thing though is how can I tell what it's plus or minus well it's - if it's the plus or minus well it's - if it's the plus or minus well it's - if it's the last row and it's plus if it's the not the last row right and so to do that I'm going to compute a sign right so I'm going to compute the sign here which would be minus one if it's the last row and one if it's not so I say one if Rho is less than rows minus one otherwise it's minus one because it's the last row and so I could just multiply the sign here to add or to subtract from the balance right and that's pretty much so this is the first portion and then I have the else for the second part so this is the this portion here there is this portion and this is the first portion there is just one thing that I written down here which is we don't want to have leading zeros right so there is a constraint in the problem that says I forgot where did we put it but the constraint in the problem in one of the rules is that no leading zeros right so here if this is the first column if this is like this column here like the first one we don't want it to be zero we don't want to map this s here to zero because if we map to zero we'll end up with something like this and this is not valid and so we need to check HERE either that the column is not the first one which means it's not zero or that the column is not is different than the last is different than the first one right so it's not the last one here because remember we are going this way so we need to check either it's not here or it's different than zero and so to do that we are going to say the condition here which is and letter two digit four letter if that or the column is not the last one which means it's different than the length of the word minus one so this is just for leading zeros right now the elf's case which means we don't have an assignment yet for that digit so try all of them and so to try all of them we'll do a for loop for a digit and a letter so this is none if the letter if the digit is not assigned and remember we keep track of that using digital letter so it's not if it's not assigned so in digit to letter so we need to enumerate it to get both D index is the digit because we start from zero until nine and so I would say enumerate digit to later and if C is none that means it's not assigned right if C is none that means the digit is not assigned and here we also need to check that it's not at writing zero so we do the same thing and D which means D is different than zero or the column is different than the last one and so it the digit is not assigned and this is not updating zero then we need to do the backtracking which is well we are going to try a digit if it doesn't work we are going to backtrack and try another digit and so that is basically let me just give myself some space here that is just doing first the choose a step in backtracking which means basically please go back look at I have a video about backtracking take a look at that if you don't know backtracking very well but this deal out of the step the first step is choosing something a choice and then trying it and if it doesn't work we backtrack and try something else so choosing here means that well we are going to assign to the letter of the current column for the current world who are going to assign this digit which means letter to digit for that letter is going to be this digit right and we are going to mark that this digit is assigned so we are going to say digit to letter so that we don't assign it later in the next step for letter for D is equal to letter and now we are going to do the search for the next step and we check if it's if it gives us a true answer that means we find us so we found the solution so if search for the current column remember we process column by column so and go to the next row with the balance being what we do the same thing so we have the sign that we already computed which will be minus one for the last row for the result and one for the other rows multiplied by the digit for the letter so a letter to digit so that's just D right so multiplied by D if this is true that means we found a solution so we just return true otherwise we backtrack and try something up and try another digit and so backtracking here is just this and choose a step where we reverse what we did here and so to do that while we need to say that la we need to delete the assignment for letter two-digit so we need to for letter two-digit so we need to for letter two-digit so we need to delete letter to digit for the current for this letter so that it no longer is assigned to D and we need to mark D that it's not assigned and so to do that we'll just say that digit to letter for D is equal to none now so that it can be reused used in the next step and if we try all digits and we search here and nothing works then we need to just return false and in there like the upper level of the function so this is the definition of the search function in the upper level for the is solvable function we need to start searching with from the first column the first row and with balance equal to starting at zero right and so that's pretty much the whole code for this it's a contains a little bit too much but the main ideas that we are doing here is that we process the edge the edges which means last column whereas last row and we search in the either it's the last column and we need to just check if the balance is equal to zero or at the last row and we make sure that the value at that column of the last row is 0 and then we go to the next column for the row after that sorry for the first row or we are at the last column of the current row so which means we need to go to the next row the same column right so this is basically just handling all the transitions when we are at the last column or the last row and then we go to the step where we are into one of the middle things and so a letter is either already assigned so we have to use it has to have the same mapping or it's not assigned yet and so we try all the possible digits and that's pretty much what we are doing here and we backtrack if we don't find a solution and that's pretty much it so let's type this up in a more clear way and see if it passes the test cases okay so I just type it the exact code that we just saw in the overview which is we need to have this solvable function and we need to define our Maps and this is just making words contains all the row including the results all the rows including the result and then we start out with searching from the first row first column and balance equals to zero we define our search function here and we do the cases that we mentioned which is either we are done in which I give the bowels equal to zero well at the last row we check if the current columns result is 0 modulo 10 of course in 0 we can have a carry and we search in the next column for the first row to start processing the next column and we pass the carry over or we are here at the last column of a current word not necessarily the last word then we need to go to the same column but go to the next world so that we can add it to the balance and then we are at the last letter and then we get the letter the current letter from the current word using this here we get the sign which is if it's the last row then it's the result so we need to subtract otherwise it's 1 and then we here we do the two cases either there is already assigned an assignment for that letter so we use this right away or there isn't an assignment so we try all the remaining digits so if there's an assignment here we make sure that it this is not a leading zero digits and we search for the next row the same column and we add to the balance the current value that we just assigned that we just used in the that we just find in the cannot roll otherwise we try an assignment for a digit from among one of the remaining digits we make sure there's it's not relating to zero again and we choose by doing this processing here basically assigning a letter to a digit and assigning a digit to a letter this here we used to know that a digit is assigned or not and this year we use to know the value that we assigned to a letter and then we search in the next row in the current column of course we add to the balance in the same way we did here and we and choose which means basically we backtrack from the choice that we made here and if trying all of this didn't give us any solution that means there is no solution so little force and that's pretty much all the rest's to the solution service run the code and submit okay looks good for submit okay so this passes the test cases yeah so yeah it just contains a lots of details but otherwise it's just a backtracking problem if you spent some time with it I hope it will be easy to understand yeah so thanks for watching and see any
Verbal Arithmetic Puzzle
ugly-number-iii
Given an equation, represented by `words` on the left side and the `result` on the right side. You need to check if the equation is solvable under the following rules: * Each character is decoded as one digit (0 - 9). * No two characters can map to the same digit. * Each `words[i]` and `result` are decoded as one number **without** leading zeros. * Sum of numbers on the left side (`words`) will equal to the number on the right side (`result`). Return `true` _if the equation is solvable, otherwise return_ `false`. **Example 1:** **Input:** words = \[ "SEND ", "MORE "\], result = "MONEY " **Output:** true **Explanation:** Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2' Such that: "SEND " + "MORE " = "MONEY " , 9567 + 1085 = 10652 **Example 2:** **Input:** words = \[ "SIX ", "SEVEN ", "SEVEN "\], result = "TWENTY " **Output:** true **Explanation:** Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4 Such that: "SIX " + "SEVEN " + "SEVEN " = "TWENTY " , 650 + 68782 + 68782 = 138214 **Example 3:** **Input:** words = \[ "LEET ", "CODE "\], result = "POINT " **Output:** false **Explanation:** There is no possible mapping to satisfy the equation, so we return false. Note that two different characters cannot map to the same digit. **Constraints:** * `2 <= words.length <= 5` * `1 <= words[i].length, result.length <= 7` * `words[i], result` contain only uppercase English letters. * The number of different characters used in the expression is at most `10`.
Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result.
Math,Binary Search,Number Theory
Medium
264
62
Hello everyone welcome you are going to do video number 63 of my channel okay and you can follow this playlist for DP concession questions if you want to understand DP from scratch okay and today's lead code is lead code number 62 very AG questions actually in simple regression and the bottom can be there for all of you, I will tell you in a separate video, either in this for DP consistency questions, I will tell from both bottom up and in memorization, okay so I will tell in that today. The question will be formed with a simple reaction, there is not much unique text in it but it is a popular question, it is given by Paytm Amazon LinkedIn wall mode, it is also fine, so I wanted a good suggestion from you guys, which one you think is right. You can tell me in the comments. You would know that in the playlist of DP concepts that I am running, I am also teaching 1 DP. Right, that too is in progress, now I will come after that, okay, I am not doing it right now in the beginning, so IF you. Want, I can take 2db into a separate playlist so that it remains similar to digital DP, there are many more DPs, I can take them into separate playlist too, if I create separate playlists like that IF IT IS FINE BUT YOU GAS DO LET ME KNOW OK SO I NEED INPUT IN THIS YOU GUYS TELL BY COMMENT OK AND THE QUESTION IS VERY SIMPLE IT IS A ROBOT M CROSS AND HE HAS BEEN PLACED IN THE GRATE OK WHO IS TOP LEFT I.E. At key 0, the OK WHO IS TOP LEFT I.E. At key 0, the robot is standing, try to move to D bottom right, it has to go to M - 1 and -1, okay and the robot go to M - 1 and -1, okay and the robot go to M - 1 and -1, okay and the robot can move in only two directions, either Dr or Right, it is okay, you are great. Rover pen has given return D possible. Okay, from right here, went down left, from here too, if I did Dr, then one thing happened, then went right, so total three are possible. If we look at it, then the question is very simple, I know. That all of you have prepared it, you must have already prepared it. If you look at this question, then what you have to do is, where can you move the robot from any cell i to i, either Dr or Right Dr means I plus one. I will go to K. Right means I will go to comma K plus one and as soon as it reaches M - 1 M - 1 means when I will reaches M - 1 M - 1 means when I will reaches M - 1 M - 1 means when I will become equal to M - 1 and at this time J will become equal to M - 1 and at this time J will become equal to M - 1 and at this time J will become equal to N - 1. What does it mean become equal to N - 1. What does it mean become equal to N - 1. What does it mean that he has reached the finish line, he got one thing, okay, we will figure it all out, okay, so its function will be very simple, solve, I only know that it is standing at zero comma zero, right. Yes, I made it zero yesterday and see how simple its calculation would be. I came here and took it from here. It was okay when I told you that if the minus becomes one then simply return what can I do, make one of one. Got the text where you have reached the finish ok but also check that i should be less than zero sorry i should be greater than sorry if i &lt; 0 or i should be greater then equal &lt; 0 or i should be greater then equal &lt; 0 or i should be greater then equal tu becomes m Or if k becomes &lt; 0 tu becomes m Or if k becomes &lt; 0 tu becomes m Or if k becomes &lt; 0 or if k &gt;= n then it is or if k &gt;= n then it is or if k &gt;= n then it is invalid, it is okay to return zero, it was simple, after this what I said is that two possible rights should be run i.e. right plus. To do this, I will have to take only 2dp, look, two variables are changing, so I am doing a simple 2d, okay, this is a very simple problem, so I hope you have understood, let's code it quickly, finish it and take time. Think about the complexity, what will be the time complexity. Simple, I will visit all the cells once. Ok, that will be the time complexity and whatever is Java, you will get the get link in the description or I will write it in the comment too. If you are okay then let's go. Let's quickly finish it in the late code, so let's finish it quickly by supporting it, okay and let's start, simple, what did I say, simple return is standing there, it is simple like I told in my explanation and I comma wait. This current robot is here, okay, first of all, put the check of out of stop, if i &lt; 0, or i &gt;= m, or if i &lt; 0, or i &gt;= m, or if i &lt; 0, or i &gt;= m, or j &lt; 0, or k &gt; = let's say, you pass that example. -1 then return -1 then return -1 then return tee off is fine and here store tee off i comma here before returning initialize your green from minus one size of tee is fine so hopefully now this gets submitted After this, I will tell you one more small thing. Look, have they actually solved this question? Ok, look at one small thing. Whenever I and K are there, take them as zero, they will not go to zero because see, either I + 1 is happening on I. because see, either I + 1 is happening on I. because see, either I + 1 is happening on I. Mines are never happening so these two will never get out otherwise the one with &lt; 0 can be removed by 6, there will still be a run for both of them, they should pass because if it is not happening then how come they will never come, ok someone There is also doubt in the comment area video thank you
Unique Paths
unique-paths
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The test cases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** m = 3, n = 7 **Output:** 28 **Example 2:** **Input:** m = 3, n = 2 **Output:** 3 **Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down **Constraints:** * `1 <= m, n <= 100`
null
Math,Dynamic Programming,Combinatorics
Medium
63,64,174,2192
188
hi guys welcome to Tech geek so today I am back with another lead code daily challenge problem that's why and sell stocks for so talk about why I'm not making videos every day having been pinged by many of you for the videos so basically I'm preparing for Google I have opportunity there so the last rounds are remaining hope so that works well so let's see what goes on so just making clear sorry for not being available but for about the job opportunities I keep on posting them daily on my LinkedIn as well as telegram channel so it's better if you join that if you are looking out for jobs changes or referrals okay let's see what the question and what we have in this so this is the fourth version of the best time to buy and sell stocks the initial ones are like you can say an easy to difficult one this type of question basically belongs to the DP but that's kind of programming uh quite tricky one so termed as Hearts now let's say what the question says you are given an integer array that is prices with a price is the price of a given stock on Eighth Day okay and you have been given one integer now what you have to do is you have to maximize the profit whenever you buy or sell a stock if there is a profit only when the selling price is higher and the bot price is lower the maximum difference will be there then only we'll get a Max profit but now we have been given a k that says that you have to complete at most gate options okay now there comes out a constraint that says you have to complete at most K transactions I hope it most word is clear if you are at most refers to from let's say 0 to K okay this is what it most means like number of transactions could be from 0 to K to Maxwell as a profit now you must not engaged in multiple transactions simultaneously that means before buying another stock you must sell the first one again okay let's say uh you cannot perform Buy sell sir buy and sell cyber tradings now you have been given an example k equals to 2 4 1 no let's see this example first here K is to this is your prices add okay two four one now before using uh without using anything or that comes in your mind let's just see it initially it was Zero oh sorry initially there was nothing you saw the prices too and in the coming day of the prices for obviously you will get a profit okay coming out to the next one if you bought on to when the price goes to one you will be at loss so obviously we are not considering this now if you bought at four and sold at five a sold at one you will be at greater loss so what is the optimal thing that comes out the optimal things comes out that buy at two select for in that case your profit comes out to be two no what if we change this a little and add few things more okay I'll just add a few numbers which is not 2 4 let's say this was five one nine that's it this is our Arena again coming to the same thing if you bought on Thursday okay you will check the selling processes now selling whenever you sell you must see that buy price should be less than the settings now what are the conditions four yeah four is greater so what could be the profit The Profit here would be two okay let's consider it at once but if we see are there another good numbers yeah there are 2 and five okay the price goes out to be two and five what is the difference three the same routes better option come into one is it fine like if you go no that's a lot so let's take it as zero we are not doing anything or let's try some any sort of anything coming to two now two and nine obviously this is a greater profit seven this was when we completed one transaction but as said we can complete at most two so let's answer the condition that we have another transaction that happens okay let's consider we have another transaction that could happen so what we have to do in case of any in case of no what we'll consider the profit that was occurred previously that means we didn't sell on first we considered that we sold all the first uh day that was prior to okay so this is what we'll consider now talking about this second transaction now again the thing comes out to be zero obviously nothing possible talking about two now if you took on this sold on this the same thing comes out two and two so let's take the greater one so greater is obviously two coming here if it sold on two okay what you have to do what you uh I'll just explain you sold on five for this okay bought on four and your previous step the previous day profit was this again you sold on to any of previous step so which is happening okay that's what you are considering so in that case your previous profit gives four and this gives three plus three six okay let's come here again you sold on first two one three again let's see what could be the possibility if you sold on Port no not possible because it's one so obviously the price Remains the Same that's the previous day profit here comes out to be three coming to nine now nine will check what are the conditions that goes on nine minus 1 that's 8. obviously a higher profit that comes up okay but taking up the previous day profit it gives 11. okay because your profit gives 11. so according to this which is the higher one 11 so what could be the condition we going through the conditions we went through is okay sorry I just wrote it in a different way this is eat yeah what we went through is that we took one transaction of this and one transaction as okay that's how things go up now this is what you need to do now let's just Frame It Up what you are doing is you have profit I and you have some transactions let's create transactions and you are at that height that's they improve so for that particular transaction an ID what would be your value will be the maximum of okay the profit of that transaction let's write a transaction okay whatever you want the previous day with maximum of whatever is the price now price at that day comma price at the other day that's true okay we will be running two Loops plus the profit of the earlier day the thing we were following the profit of the other link this is what we are doing and now each of us goes on okay J is actually your zero to I minus one um because we are running two Loops in this case and we will be checking like which goes better and which goes not but if you talk about this kind of condition what we are doing is we are running I is also going from 0 to n j is somewhere going from 0 to n then we have the K Loop so n Square K which is not at all optimal we are checking each and every condition and this goes on to be n Square K so this is not optimal so what we need to do is we need to improve it somewhere so what we can do it we can improve it by checking the maximum profit gain by selling the shares on the I think at some constant time that's a constant day we are considered okay and then we can notice what would be the difference that occurs so that difference is what we need to improve if we do the same part just to reduce it into the value that's n into K okay that's uh bring it out into you can say kind of quadratic format if you do that in that case what we'll do the profit would be for that day for that transaction that they would be the maximum of profit of transaction on the other day comma the price on that day plus the max of the difference we had that's the previous difference which we were taking and the profit on the earlier day earlier transaction minus the SE so this is how you can get the actual profit that's being done okay this is point of uh removing it and making it a quite easy one you can say now let's see some the second one also I'll just explain you that too in a different way this is our array okay K is given to be 7. now this is your array that's given and you have been given a value that's sorry Case two I just wrote seven so sorry your K is given out to be 2. now you have to decide what you have to do which particular condition would you be applying just give it a thought what we have two options two particular transactions have to be completed and the thing what we have to do we have to maximize the word that's the profit now that's what we need to do if we actually see something like whenever we deal with uh profit-based questions or anything uh profit-based questions or anything uh profit-based questions or anything like that what we do is we take the maximum Rift maximum drift is the maximum difference that's the highest selling price and the lower buying price so that's what we'll be using now we have a price window okay Now using this price window what we are doing is we are taking a transaction let me do this so zero one two three four five yeah we have these five so for these five what we'll be doing is let's do this and then we have k equals to 2. so for k equals to 2 let's write this okay this is your Arena initially make sure all the zeroth indexes are 0 that means you're not doing anything okay now when you buy on that day what you have to do you have to maximize the profit of I minus 1 3. now that's what we need here let's consider in the first day that's 2. you sold on to bottom three okay you sold on to bottom three plus your earlier day profit this gives minus one this gives you a minus one obviously which is not optimal and your previous job profit was Zero so in that case your result should be maximum of this so it gives out to be zero coming to the second one six minus 3 and 6 minus two previous day profit zero which is Maximum take the maximum value three and four is your maximum Max of 3 and 4 comes out to be 4 take 4 what we are doing we are checking which is the optimal result again come to five check for all of this 5 minus 3 5 minus 2 5 minus 6. plus your earlier day profit early day profit is again 0 so 2 3 and minus 1 which is the maximum three Conformity from this five minus two again coming to zero okay now three was coming out to be this what you have to do now once you have three you have to check is this three greater than the previous transaction is it so is your 3 greater than the previous transaction no so what we are going to do we are going to take the previous transaction only so this is where you go while taking out the difference make sure that it is greater than the previous transaction or greater or equal okay only then you will cancel it otherwise take the previous transaction why because we need to maximize the profit and that's the main base condition that goes on so make sure to maximize The Profit now again talking about this another one that's zero same thing comes out to be zero it's not possible take the previous profit for three is it possible 3 minus 0 in that case if you check it's 3 minus 0 it's 3 previous year profit was zero that's the above one previous day profit for that particular transaction was Zero so it's three again maximum will be 4. now if we had just one transaction and we had to find the distance this would be the other side but now we have the second day transaction tool let's come to the second end again coming to minus 1 again the same thing zero 6 minus 2 no 6 minus 2 is your this previous transaction comes out to be zero what is the possibility that comes up three and four maximum of three and four is again four so your answer comes out to be four next come here check this five minus six goes up 5 minus 2 and 5 minus 2 these are the possibilities that you will check again the maximum comes out to be 3 but what is the maximum here 4 consider the previous transaction right again coming to 0 now you have the zero value again you will check the same thing this is the second return transaction just keep that in mind so zero things go on again four maximum comes out to be free not check for this three one what we are doing is when we are three we'll check for three minus three zero three minus two one three minus 6 not possible three positive three minus zero three so maximum difference sums out to be three okay take the previous profit is 4 3 plus 4 Max comes 7 now out of the score and seven obviously seven was the maximum so you will take seven hours maximum so if you see the result now is your last value that is seven so what we actually did in this thing oh I'll see what we actually did for this particular condition let's say for every key for every K or let's write this for every key and let's have some value of I what we were doing is we were taking the value of that prices okay we were taking the value of that price is first of all and then checking for that Value Plus DP of that index that is the biggest thing we I hope you guys know it or not let's uh just have a go through first and check for every value what we are doing is we are taking the prices this okay this was a prizes first of all make sure whatever you do we are taking this prizes up to whatever value it was Zero from zero to two this K gold went from 0 to 2. what you will do you will take the price of J minus the price of your K value okay plus DP of whatever your value was if you are at 1 this will be x minus I minus 1 and this goes with key this is the proper condition that you would form I hope this was clear if not then please have her go through once again keep with uh you can say you can keep stopping the video check it on your own because that's what's important you just have to keep a track of this table how each and every uh past element is going on and we are comparing and you have to take the maximum value of it okay let's see the code now this is a bit optimized code because instead of taking all of this as you can see we are just considering the previous one while comparing so what I did was I just took the previous ones instead of this so that's the code you can go after the order of NK code 2 this is order of K code into n sorry this is out of NK code when you have optimized the space and to most of you I like that you can try on your own because that's what's important when you are trying out a DP question don't go with the solution just try it on your own I'll just give you example what we are doing for the same thing what we do for uh K going from 0 to K we were giving an example so it's not going from 0 to get it's just going from one okay the same thing that comes up uh the zero elements have been with zero that's why we are running an opposite Loop comparing the maximum prices the same thing we did it turned in opposite way where we had the answer in the last box here we have the answering post that's it I hope the question is clear if there are some doubts and do let me know sorry for having such a lengthy video because this was tricky question and needs to be explained very well and for all those looking out for job opportunities Raffles I have reference for my own organization so you can ping me anytime keep following the geek and do join the channel on telegram for latest job updates thank you
Best Time to Buy and Sell Stock IV
best-time-to-buy-and-sell-stock-iv
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`. Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** k = 2, prices = \[2,4,1\] **Output:** 2 **Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. **Example 2:** **Input:** k = 2, prices = \[3,2,6,5,0,3\] **Output:** 7 **Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. **Constraints:** * `1 <= k <= 100` * `1 <= prices.length <= 1000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Hard
121,122,123
1,443
Hello Friends Updated On A Criminal Directory Consisting Of Important Notes For Students With This Translates Apple Do Not Subscribe Thank You A Total One Word Problem Solved Will Start In Turn Will Cost Mid Cap And Mid Day Aug 12 How To Build First Term Movies Twist French twist ok now pick up notification Rafi how to spend two cigarettes post no ok tour number of Madhya Pradesh Road Development Video Channel and subscribe the The President and Apple Select Chennai Central to Shakal Hai Pimple Interest Vid Ooh Vo Hansi Thi A Vacation Open Play Store Settings on Bluetooth Backbone and St. Vincent Peel and Two Second Fruit and Nut President Left Side and Twitter Follow Us On Aaj To Amit Pandey Tractor ki Panjiyo 15 Fab The Indian Fold Phase Others Let's go in Hello friends this pack that taxi Do this is zero do a poster on airplane mode turn it off that fifteen I will make a puja karte ho ko unmute fruit main aapse meri list film suit photo khila tha I will just making this daitya ne ki soumya ko match ki bill bake appear operate and return gift ok definitely after 40s vitap hai the best take Child Welfare Dr who has given a pic and painted on 56001, immediately after that, when is it active, when is a request to work, what is your time, what is the time, if pimples return sometime, we will edit the people with them at 200. Why love sensitive and the cost price loot subscribe weather in flash light of time text into a short note on 2016 cortisol notification acidity country how to list for b id college turn off that noida parents polish notice to taste it will not come up on And Pintu updates point child is first that and child is on the side introduced in New Delhi and child on I am your comment and toxins then but will do this light set on a vision of the superhit film Reddy Time Taken up A Plus 108 Posts Next Post Mitti Dave Liquid Is Here Every Child With Rate Details After Notification Fruit Of Birth Date Love In The Dark That NGO Lead To Website Tarf But In The And Only To Be Credited To Notice British Rule Trying To Withdraw Support This Channel Subscribe that Akshay is this start second that Kanodia loot from airport that test draw is a product of 90 e will be updated and equal to 168 is fire brigade test record e agri is busy this style condition textile is on that entire placid under development center Fruit List's Parents Paint on Return Form Will Subscribe to Health Channel It's a and Listen Bhai Sadho Adapted for Different They Have a That Child with Prince Samput 10 Thumbs Up Police Arrests This Man Like this Pack to Support Ki Cigarette Understand the Subject You Reading Channel Previous Benefits Rewind Video MP3 Treks Planets Simply Worth It
Minimum Time to Collect All Apples in a Tree
minimum-distance-to-type-a-word-using-two-fingers
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex._ The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`. Additionally, there is a boolean array `hasApple`, where `hasApple[i] = true` means that vertex `i` has an apple; otherwise, it does not have any apple. **Example 1:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,true,true,false\] **Output:** 8 **Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. **Example 2:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,true,false,false,true,false\] **Output:** 6 **Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. **Example 3:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], hasApple = \[false,false,false,false,false,false,false\] **Output:** 0 **Constraints:** * `1 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai < bi <= n - 1` * `hasApple.length == n`
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
String,Dynamic Programming
Hard
2088
1,277
welcome to Mays LICO challenge today's problem is count squares some matrices with all one's given an M times and matrix of ones and zeros return how many squares some matrices have all ones let's say we've been given a matrix like this a point this point here you can see that there's a 1 by 1 matrix square of ones but there's also a 2 by 2 matrix of ones and also a 3 by 3 so at this point there's actually a total of three possible squares with all ones here there's gonna be itself as well as this square here so there'll be two squares and so on and so forth with a total of 15 in this entire matrix in order to solve this you could simply write a multiple for loops and check at every point to see how many ones total like all are going to be one so here we can check it's a zero so we can just skip that here we can check ok there's at least one square what about the 2x2 what about the 3x3 and do that for every single point but that's tricky and also inefficient because you'll be writing a lot of for loops to get that to work what if we changed our thinking a little bit instead of starting considering this to be the starting point what if we considered that to be the starting point well then slowly as some sort of dynamic programming solution comes to mind the only thing we need to check really is the point at the top and the point at the left and the point right here diagonally all one's or at least greater than zero and if that's the case then we know that there's at least one more square here so think about that for a second like if we just checked here to see okay how many subs like sub squares of ones are in this square here we can traverse through the array and kind of sum up how many squares at each point that we could have summed up and if we that slowly we begin to see this greedy method occur and we can take the minimum point Wells okay so say we checked here and if all three of these points are greater than zero take the minimum one out of these three and add it to this matrix here and now that's going to be a two and what that tells us later is when we move down here we can check the same thing and if all of those are greater than zero we'll take the minimum point because that's going to be the minimum number of squares that were in all the sub squares before that and add that here and that actually allows us to soul slowly build up the number of sub squares there are and we can do that in one pass we don't have to do these recursive sort of calls or multiple forward loops it's very similar to the minimum path problem and hopefully it'll start making sense as we move forward so like imagine we had a matrix like this right and forget tot the top row and the first column because those whatever there they are aren't ever going to have sub squares inside of them right so if we start here we can check all right are all three of these greater than zero and it's not so it's only going to be this square here at this point so we can just move on but what about here we know that all these are greater than zero so there's going to be at least one sub square so we take the minimum between these three and we add it to ourselves so that's going to be two what about here well the minimum they're all greater than 1 or zero and the minimum is just gonna be still 1 so at the end date is still 1 just once one extra square so we just add two there and we can move on moving forward like this and what about here though well now that we've gone to this point we see all two of these have twos so there's actually a minimum of two squares before of what we've kind of accumulated so now that's gonna be three and we just add up all these that's going to equal to 15 so we can add those amounts we traverse through the array so hopefully that makes sense let's see if we could solve it or cut it out so let's start with the height and Heights gonna be lengths of matrix right give me a number of rows and what about with that's going to be length the matrix and 0 like that okay cool let's initialize count and say 4 well let's start with the top row okay so we'll go let's see 4 mm I guess column and with we'll just say well we can just add item up count and say matrix whatever is at first row and column just add those in there cool so now we can do the first column and that's going to be for row and height and one thing to note is will actually need to we don't want to double count so we'll have to skip one and we'll say all right we'll just go range of 1 to heights like this and again we'll just add up everything in the car so this will be row the first column so great now we could start our traversal and that's how that's gonna work is we'll start at 4 row in range of 1 of heights and for a column in range of 1 of width like this okay now what do we need to check well first we need to check if this is even equal to 1 because if it's not them doesn't matter we can just go ahead and move on so if matrix of row column I'm gonna copy paste sex I'll be writing that a lot if it equals 1 and if the top is greater than zero and the left is greater than zero and the diagonal is greater than zero so to get that to work we'll say top the call - that to work we'll say top the call - that to work we'll say top the call - whoops so our left and to our diagonal all of these are greater than zero then we know that there's at least one more sub square at this point so what we'll do is we'll take the minimum between these three and we'll add that to our count so count goes plus equals the minimum between these two these three points okay and then after that we can just add our point here so if it's like whether it's zero at one we just add that to account it might be fine so that should solve everything you see that actually worked mmm Oh see here the object is for calling with so I must have got the range okay Oh looks like we skipped one range of heights equals 1 greater than 0 go 2-0 count equals 1 greater than 0 go 2-0 count equals 1 greater than 0 go 2-0 count min ha squeak don't try if that works okay yeah so I forgot that you actually need to update the comp index itself and okay so taking accepted it's a little bit hard to explain but it's really similar to the minimum some path problem the only difference is we'll also need to check the diagonal point because in the minimum path problem all you can do is go down or right but here we'll also need to check this diagonal point here but we don't need to check everything from the back because we'll be it'll like iteratively summing those up as we go along okay thank you
Count Square Submatrices with All Ones
largest-multiple-of-three
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3. Total number of squares = 10 + 4 + 1 = **15**. **Example 2:** **Input:** matrix = \[ \[1,0,1\], \[1,1,0\], \[1,1,0\] \] **Output:** 7 **Explanation:** There are **6** squares of side 1. There is **1** square of side 2. Total number of squares = 6 + 1 = **7**. **Constraints:** * `1 <= arr.length <= 300` * `1 <= arr[0].length <= 300` * `0 <= arr[i][j] <= 1`
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Array,Dynamic Programming,Greedy
Hard
null
65
foreign this is the 65 problem statement in lead code is the hard level here we are checking that whether the given stream like this what are the given string is valid number or not how do you save it is really valid uh when it is it contains only numbers this is nothing but integer or float contains character and something double value will be e to the power of kind of thing will be there normally we will face this type of problem at the time of reading command line arguments from the chameleon arguments into character ah what is that a string array so whatever the number we are giving that number also stored in a stream format now how do you understand that then what do you do once you are taking the string formatted number it may be a integer it may be a float it may be a double that will be converted it into Target format so when it is converting it should be a valid how do you know whether it is valid that function will validate the code this is the formula we need to use inter that will be used internally whether it is valid number then only it will be converted and assigned to the Target variable otherwise it won't do that now here we are taking the same thing a value number can be split up into these components first if it is a decimal number r decimal number or integer number and optionally sometimes we may give a scientific notation like e to the power of 34 e to the power of 3 4 5 like this small E capital will also be there in integers and decimal number can be split up into these components what is it a character plus minus can be there sometimes you may give a sign symbols also that should also taken as a value number and one of the following formats one are more digits followed by Dot and one or more digits followed by Dot and followed by one more one or more digits and here a DOT followed by only uh one and more digits like this whatever so the disease is followed by another digit also like this now in integer format it may take optionally it is a sign character if it is even if we are giving the sign character it must be treated like a value number only and this is must be one or more digits you can see that now here what are the possible combinations valid combinations what are the invalid combinations you can identify that two double zero eight nine minus zero one three point one four point like this so whatever the numbers we are given here it above all are valid combinations now coming to this place there are invalid combinations so finally it has to return the valid number invalid number or something here valid in the sense it must be true otherwise invariant number means it must return false it is singular okay so here these are the test cases what we are giving but here s consists of only English letters both uppercase letters and lowercase letters it is 0 to 9 plus 2 minus and dar symbol will also be there something it is power of E capital is small you will also be there in that now after that here we need to write a code for that first of all we need to check what are the various combinations are there in the given string based on the combination values you can check it for now we can check it out first up to here up to this we can check how many different number of combinations are different type of characters are there as it is given in a string format we are converting it into character array and character array index starts from 0 and N is at length so up to n minus 1 we need to take I is equals to idx is equals to 0 to n minus 1 we will go that now every time we are checking that whether it is plus or minus if that is plus or minus and num form sine found decimal form any one of the thing is true then we will return false and otherwise sine found is equals to True like this so here dot this is about the sine symbol this condition about the dot symbol means in one floating Point does decimal equations will also be the right so this one also we are making it as formula else we are going for the character whether it is e so it will be taken as like this so we have exponential found raised to true and we need to break from there otherwise else return false finally it will return true or false for this now this n is directly we are calling is number right so it will return but here it will keep on moving to this place return false F exponential this one return first but here internally we need to check it out sine fund is goes to false num found is equals to false if sign is not there and number is also not there then idx is equals to dot point and it will return False only dot is there means it won't treat like a number and later we need to go for plus and minus again sine form written Force num form written force or sign found is related to like this each and every character we need to identify whether it is satisfying our rules or not so these are the two level of condition checking as it is the lengthy code but we need to if you travel from zero index to last index every time we will take a status what is the status of sine phone is sound sign is there or not sign symbol plus or minus is there or not and decimal found these are not is there are not means if there is a DOT we can make it a decimal number found or not either or not and exponent Expo found in the sense e to the power of e value is there or not so here I'm running this program just absorb yeah successfully it is accepting I'm submitting this code so one case is failing capital e in the sense I need to go for I need to add one more capital E condition I'm running this see oh it is a capital e capital E sorry capitalism yes all three text cases because in our condition they have given something right Capital here in a second condition itself here so we forgot to do that okay so this is the code I am submitting this code okay everything is good okay thank you
Valid Number
valid-number
A **valid number** can be split up into these components (in order): 1. A **decimal number** or an **integer**. 2. (Optional) An `'e'` or `'E'`, followed by an **integer**. A **decimal number** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 1. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An **integer** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`. Given a string `s`, return `true` _if_ `s` _is a **valid number**_. **Example 1:** **Input:** s = "0 " **Output:** true **Example 2:** **Input:** s = "e " **Output:** false **Example 3:** **Input:** s = ". " **Output:** false **Constraints:** * `1 <= s.length <= 20` * `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
null
String
Hard
8
33
Jhamb and teachers by many in this video number six in question number six will do the name of the question is search na rotate sorted. Okay, the special thing about this question will be that before this we have made the same question with its solution in the previous videos. It will be okay just to tell the party that if you understand this concept using that can set your results old main question the FD Good Night Have you understood that cancer app well then let's see the question first if you understand it well then before that Let me tell you that this is a very asked question place, you can see how many places this question has been asked, no, quite a lot of companies have asked this question. If this question is ok, then let's see the question. You will be given a rotator and a target. You will have to fry the intact of that target and if in this decision, if that target is not present then it is okay to return minus one. So let's see you have given the input, the target is for okay, so I am the president here, yes. This conductor one, so we have returned one, the question is simple, just what is the road, it is yours, it is rotated sorted, that means it must have been rotated 113, so I have kept the same example, okay and your target is four, okay. So first of all, open the target and first think that if it was sorted then you would have found the target by doing a simple binary search. If it was sorted then it would be completely sorted. But now it is not completely sorted. But if you pay attention. You can divide each other into two parts, which is the shot that you are seeing, this part is sorted and this text is sorted in itself. Okay, so why don't you do this that you both of these are sorted, these are both of which are sorted parts. Put binary search in them, isn't there any restriction in it because it is sorted for free, write 457 380, then for this write furniture, 129 in which you get four, from there now make a grand index, okay, here you get four. So return it is a very simple solution that you just have to apply - simple solution that you just have to apply - simple solution that you just have to apply - but you have to divide, the purpose of both the rays is how to find this part is to be divided on the index, part, this part is to be divided on the index, so you remember I have said this in many previous questions. It has been told, okay, let's see the thing now, I have to pay attention to the oil here, I will press it so that it becomes a little clear, maybe okay, I will remove this also, okay, look at the thing, from where I have to do the division that I have to do here. I have to design from that, this is the element in me that I have to revise in this entire work, okay, and the other remaining thing is this, okay, it is possible that you have got the minimum element intact, let's assume that the recipe is correct. There are three of these, you have got that interest, okay, let's accept it is generally called stomach, okay, stomach coolness, you have got the testicles three, now what will you do, from 0 to 80 to favorite and X minus one, you will apply candy crush to sister. Here's another pet index, take the end minus one, its side end is restricted to MS Word, in which you will find your silver, set your index there, remember, I had asked a question in the play list of my binary search, find. You keep thinking that the minimum is inverted, it is absolutely exact, you find the minimum, find the index of the minimum from here to that which I told you and now it is just out, you apply binary search, so in this lesson and in this post, okay, so let's see. Okay, till now I have to extract, so you think for yourself like I have Malu, here is my left and here is mine, first I have extracted it in golden letters, then let's see what happens, I will extract it. What is plus and minus and wide two? Place 10 plus foreman more two so this is my good okay so here I will tell you one thing in one thing okay which pay attention it will be useful to us on the question somewhere in the future okay so you know that when it is sorted when Bread taste remains then 112 more than 80 and then you will stand on any element. If you compare yourself with the right element then now you have become smaller. Right A trident and a treasure hunt means either from the brightness element or from the right element. Whatever title you feel, you have become small, okay, you are a tomato, that's why it is happening that now I am standing here in a minute, okay, hey, I am coming to the maid and compared with others, I got five, this is mine, hey after mid -day hey after mid -day hey after mid -day and I got hey of r which is what I got 4 uh ok and 5s greater than four which is wrong right short what happens in the dark the element you are standing on all the elements to your right should be bigger than you So this means what happened here, I take a condition that this great Dane is of mate that this Great Dane are of you that we are getting a condition here that you will grow from R, this is at home right, it means right. I am liking my answer somewhere on the side, my rotation point is on the right side, not on the right side, I will get my minimum element, so the first element and the first thing about roti is mintu, so it means the rotation point is on the right side, reason. Will get it which is one here How to bay I get my search page cash withdrawn on the right side Next time now just shift it So what do I have to do to shift tight L I will do the movie Okay okay now Be careful, what will I do in the afternoon? I have to turn off the e-mail. He is a off the e-mail. He is a off the e-mail. He is a reader of Bigg Boss. Okay, the e-mail will be deleted from my palace. e-mail will be deleted from my palace. e-mail will be deleted from my palace. I am doing a plus one. Okay, right now I am here, I will tell you. You have come to know that it is Arif Mirza, if it has increased again, then erase it, if there is no big management, then erase it, then put it like this brother, because it is a great plan, it is ready, so it is done, no one can ever answer me, so erase it. So from my space, after a minute, I will keep eligible to meet plus one, my code will come in made a plus one were correct, even what is looking is right, now let's take it out again madam ok free plus 4 - Read by two is equal to two three free plus 4 - Read by two is equal to two three free plus 4 - Read by two is equal to two three four, so this is where I got my attention, okay, so I write the media, what should I do again, I will do the same thing, I will extract the energy of off, I will compare it with other, okay, how much was that for me? There is one, hey my friend, how much have you been there, okay, then this thing is listed here as one, which is where we add character ride increase, what is one two three 500 where you are standing, you are smaller than the element on your right. If it is done then remedies are less than two. Hey, if you are coming then the character is the right water, I am the meat one, it is smaller than the elements and art, so there are chances that medical may come my difference, right, okay, so what will I do in the male condition, AR. If there are chances that mid could also be my answer then I will not mind meeting because then I will miss it otherwise I will keep all my options and the complaint is at the most important point of this question that it has become a request of all. If we look at it in Chile, I think this question itself is broken in the middle. You have written from your condition, what is the purpose of aloe vera, then you have given a question awards and that's it. Okay, this is the most important point, I thought to do this question. I am you should know why Ali Recruitment Plus One was done, why media was not done, so I am lying here, hey, he is bigger than me, so now he can be like this in the mail, so medical will be cut in this and edited in it. Freed after alcometer and in such a condition, how is it? Hey and Middleton, hey man, the media is small, hey man, maybe it is because of this that it hurts me, she has got the article on maintenance, instead of discarding it, we will keep hope, I have one, everything is fine. If I wanted an important point, then I would have seen the code. If I was Kotli, well, let's see it by doing one button, then we were meeting my article. If not, then see, we would have completed the entire chapter on our Android. So, this is equal to I. Mute it here. I am giving this article to meet and now look at the oil and one place, okay one more important point, Ellora has come here, so what do we do once, let's take something out again and see what comes, okay this is another important point. Let's keep telling the points that she says to you plus 3 - 3 by two, answer has come, she says to you plus 3 - 3 by two, answer has come, she says to you plus 3 - 3 by two, answer has come, remember three, earlier also the meet was here only, I used to meet here earlier also, so do it again at a lower price, all these medicines are admitted, it is free. Is it from Arif? Hey, my working requirement is big, otherwise I will go in this condition, what is the end condition, R is equal to two, if it is happening, then 8 record will come again three, brother, okay, and so already Sharif again. If you spread it, you will get the same thing again for free, now again you will get trapped while doing the same thing, but people will get trapped in the world, neither because of the binary search which will be my breaking condition nor OLX money and I will have to keep it because if garlic record if equal to and If I keep it, I will keep getting stuck in the loop, I will take it out again and again, it will be false and I will go to this condition and mute the bar again and again. Okay, and the glass is nickel-to-made, but if it has Okay, and the glass is nickel-to-made, but if it has Okay, and the glass is nickel-to-made, but if it has passed, then this look is on the way. This will continue, we will keep it next Tuesday, that's why we will not keep it, we will keep giving electrical balance. Okay, so your problem is how all your corners will be saved from it. Okay, so let's see once. A good, what will happen that I, let's see a question, that is. There will be a road via you and you will be given a target, okay it will give you a star and there is an indication of resettlement like here the target is zero, okay then its NSS is 0123 then it is okay and given in the question Humor in front Gautam with he was logged in income Tax credit means two pleasant things, it rotates after a short term, you heard it and the login is also saying, brother, then what else will you use other than external search, okay, then fold it exactly like I told in the video. Explanation: It was I told in the video. Explanation: It was I told in the video. Explanation: It was told that first of all take out the size. It is ok. After that, what will happen after that? We will take out the pet index. Neither will we get a function nor will we get the fine paste. Is it okay? After that, we will take out the ticket. What did I say that I will take out the binary search? Okay - Got a patent in both the hands due to research, I will apply Okay - Got a patent in both the hands due to research, I will apply Okay - Got a patent in both the hands due to research, I will apply brain research in both the hands, first I will put int side effects, binary search function, don't write it now, I will also write it, okay, where were the indexes from where first, then the stomach index is on the left side. Let's see the sharp index from zero to one - one index from zero to one - one index from zero to one - one till date what to fry in the map so that to find it okay this if the ID acts who is not equal to minus one means I have found the element then I will return the addition and if not found then I D Till then we will salute you, we have to find the pan research target, okay, and in this case, we will extend the idea, okay, whatever comes, if not found, the side effect minus one will be returned, okay, first the scientist writes, okay, sorry and find tweet. Do it, I had told that for fine paste, exactly the same function has to be written as in Find Minimum, we had written rotated total, okay, then on the side and norms that pass the MBA, we have worked out, so it is okay here, so what did I say? - It seems that LIC's what did I say? - It seems that LIC's what did I say? - It seems that LIC's 20822 advance is fine, it will be equal to youth and will not be done so that we do not get trapped in the internet, this is equal to what will be the help plus and minus. Bittu is fine, now first of all I had said that Nam Summit if better. The name of the day is Saunf R. Okay, okay, Namaskar, Girdhar, Humsafar, meaning, I am the first person who will get me on the right side, tell me the circulation and I, the answer can be no because the minute is big, brother, I need measurements, yogic treatment plus one medico. Ignored the Alps, will go to the left side and will ask why the minute can stop. This is my answer, this is my measurement and while doing this, we will return you in the end, this will be my pattern tax, let's get West Indies, wrote the second caption. This will be the Id function from the in itself and research. If you know this very well, then we can write, binary search, okay, what are you passing, let's take left and right, let's pass it as vector. Is the phone number and what are you passing the target if it is ok then apply - Walden equal to and then apply - Walden equal to and then apply - Walden equal to and inter result assuming the result is written in the index edit is small in minus one ok can tie in the middle will write ok is written in the last Add will be ok first then remove mit nikal lo and made easy way to wealth plus and minus album to ok is kah nam soft made possible to target the hai to kya karenge mil gaya main id x is equal to made and breaker go press Will go out of this group and will add, if it is not so then there can be two conditions either the numbers of minutes are the laddu target i.e. on the right side our laddu target i.e. on the right side our laddu target i.e. on the right side our target will become eligible to make plus. Absolute festival recruitment - 3 - Absolute festival recruitment - 3 - Absolute festival recruitment - 3 - is simple. So none of that will come out. Okay, let's make this smaller. Let's make this also smaller. Next 9 Newsroom Rent Turmeric Sample Test Cases That's All 500 Grams Per 10 How Left Side Submitted From These That They Are Able To Pass All Details How Chunat A Grade also MS Word This Question Dowry Cent First Great Commission You understand it quite a lot If you think about it then I made my break and applied binary search and also the code file for breaking will be visible Hmm I have done it before so it was quite simple Still I have explained the logic behind extracting saffron, then again in this video, so that you can have a clear understanding and I am also fine, if you have any doubt, press in the comment, this is the birth of these three things. X video, thank you brother.
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
413
That Hey Guys Welcome Back To My Channel In This Video We Are Going To Solve Arithmetic Slices Its Dates Key Problem Of Marksheet Challenge Know What Is The Given Statement Here And Interior Is Called Arithmetic Shift Kar Sister Of At Least Three Elements And Difference Between Any Two Consecutive Element Same for Example 1357 972 - 52 - 5 - 9 RS Matric Sequence 972 - 52 - 5 - 9 RS Matric Sequence 972 - 52 - 5 - 9 RS Matric Sequence Given in Pims Return the Number of Arithmetic Understanding of Dreams What to do in Sweet Problem The number of the way is to be defined and the elements of the sub add will be between them. The difference between two consecutive elements will be the match, so the first example is that here is 1234 so the answer is Kshatriya because the difference which is my first three elements is the difference between two consecutive numbers is one and two is three four. This will also be a sub editor for the free size, the difference between this is Romantic F1 and a survey of 12345 will be made and now the difference between these elements is that light and for example, my number one is bill size one. So what to do in this, whenever the size is that unique return will be made zero. Okay, how will we solve this problem? Let's see, the answer of the first is 1234, so how will we do this year, we will take three poor here, current total and defense initial, my current one. My total will be 80 and the difference which will be the difference of the first element, then there is a difference of 121, here is the description, here the difference of ₹ 1 is here is the description, here the difference of ₹ 1 is here is the description, here the difference of ₹ 1 is free, the next two elements will be less, check that after all - 26 - two, its difference is one, after all - 26 - two, its difference is one, after all - 26 - two, its difference is one, so this is Equal a difference of the previous if my dear Kunwar what you will do is increment that time point will be YouTube After this what will we do for the total what will we do here we will see whether the shoulder which is mine is get thumb equal to or not And if it is there, then what do we do in the total? We will add the current account by minus one, then two is my minus one. If it is warm to minus one, then we will add one. Then what will we do? We will check the next two elements and the difference within the fourth class. It is one, this is a request difference query, so what will we do on that side, again we will increment one, it has to become three, after getting free, we will see whether the one who is my friend is there or not, if it is, then can't. After doing this I will do minus one, this cant virus is 128 villages, so here today we will take plastic till Kailash element, what will we do, we will return the total, zero plus one plus two, three layer myth TV was needed, okay and keep this cream of second in it. What will we do and take 3000 1000 in the current session of Vano's or my total is zero in the initial and the difference will be of money in one today because two minus one is mine what is one of Vano's or after that we will check the next two levels of this Difference is free - 2018 Previous Quarter is free - 2018 Previous Quarter is free - 2018 Previous Quarter What do you do, we will update the current, we will increment, then what will we do, we will look at the total, what will we do in the total, Cant - Vansh's, look at the total, what will we do in the total, Cant - Vansh's, look at the total, what will we do in the total, Cant - Vansh's, when my current which will be get them is equal to two, then here to follow this. If there is two, then how much will I add to the total? Current -1.2 is two minus one world. Current -1.2 is two minus one world. Current -1.2 is two minus one world. After that we will see the difference of next two elements. Five - Do 15 - What is two Five - Do 15 - What is two in me? This is not difficult please. So what will we do in this condition and the difference. Will update from current to current means friend difference remaining after that what do we will favorite the guide from WhatsApp ok after updating again we will see the next government's six five is its differential oil this is the previous superintendent so again I am now Will add one and also update the cant Cutting 101 was already there then tell me I have to do one ok then we will see intake of next two elements - 60 will see intake of next two elements - 60 will see intake of next two elements - 60 this is quality scenario so what has to be controlled here if increment has to be done then that Whenever Girdhar is equal to two, what do you do eight in total, current - current minus one, two minus one, - current minus one, two minus one, - current minus one, two minus one, what will happen after that, we will do one more intake, toxicants are one is isolated, so again what to do is light. Will we make amendments to what will happen after incrementing? If I want to become free, this is a gather request, so consider it as a treatment, the total will become free - 1.2 consider it as a treatment, the total will become free - 1.2 consider it as a treatment, the total will become free - 1.2 and I have come till the last one, but I have to return my total, one plus two. Four will be army only and how will forward for be filled with, see, this is 123, they have to become mine tomorrow, 6 7 8 is 156 and one has to be played, it is 578, so it is four, how to code, let's see, we will fry the installment current size, we have come. Will take current can diminish God will be Edison and there was a gallery in total six in total which is in it that even today where is my tab equal to one will be equal to one will explain will return will be zero that and what is the difference so in my tension of off first element Let's take out the first woman, now we will do vegetable reconnaissance, then what will we do, then we will start from the end act, then Addison and Plus, we will check that for the next two Cassie, the number is cashew, difference and now my previous difference is Kunwar or not. If it is equal then what did we do by incrementing the CAT? What did we do after the increment? What did we do by checking that my gate is recovered daily? If it is equal then we used to update the total of dogs. We will update the total on this after updating from Cantt side. I come, what will we do? Hmm, if the differences are not equal to asparagus, what did we do at that time, we used to update the exact, we will update the right, Namaskar, we used to update the minus one and point, we will add it once, and then what should we do here, total no. Turn on the torch light, from time to time we tell the court that this is just a time to thank you.
Arithmetic Slices
arithmetic-slices
An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. * For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences. Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 3 **Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself. **Example 2:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 5000` * `-1000 <= nums[i] <= 1000`
null
Array,Dynamic Programming
Medium
446,1752
1,798
hello everyone let's take a look at the code on one seven nine eight it's a sub problem in the birthday context but acceptance rate of this context is on about 30 so it's not very high but actually this problem is not a very hard problem okay let's take a look at how to solve this problem okay and if you haven't read this problem you can use the descriptions you can take one minute to read it let's take a look at the first example we have two coins one and three so uh if we don't take any coin we can make some zero if we only take one we can make some one so we can make two consecutive integer values starting from zero in the second example we have these four coins so we can um have those combinations for example for seven we can just collect all coins so we have seven for example we can take four then we have four so we have eight possible consecutive integer values starting from zero so on this operation here observation here is that the longest consecutive numbers that must start with zero right since i imagine that if it does not start with zero that means um for example we have coin four we have coin six they are not consecutive we like if some coins are consecutive there must be a coin one since um like four plus one is five plus one six so there must should be some point one to connect them right so we can just sort our coins we can just start with the smallest coin since the answer is always start with zero which means for example if we use first coin we can contribute zero or one to any value if we take second one we can contribute zero one or two to any value if we add three we can contribute like zero to five to any value right four is one plus three five is one plus three if we add four we can contribute third to nine to any value if we take ten we can contribute zero up to nineteen to any value so the answer is twenty what if the 10 becomes 11 we know 1 3 4 the maximum value is 9 and 11 says the gap 10 so if it's 11 then we must we shall stop here since my energy level is gap so the code looks like this first we sort coin and the current value is there's kind of mean six seconds maximum number in my consecutive results so we just for loops coin from smallest coin to the largest coin if current number plus one is greater equals than coins then we can include this coin for example previously we know the country is 9 and the coin is 10 9 plus 1 is greater in 10 so we can take 10 since there's no gap if the coin is 11 count is nine current plus one is smaller than coin so this gap we cannot take 11. so here of course one optimization here you can just break since we know the coin is sorted so if this condition does not hurt and does not hold and you can just break to optimize your program okay that's it so it's a little bit greedy see you next time
Maximum Number of Consecutive Values You Can Make
max-number-of-k-sum-pairs
You are given an integer array `coins` of length `n` which represents the `n` coins that you own. The value of the `ith` coin is `coins[i]`. You can **make** some value `x` if you can choose some of your `n` coins such that their values sum up to `x`. Return the _maximum number of consecutive integer values that you **can** **make** with your coins **starting** from and **including**_ `0`. Note that you may have multiple coins of the same value. **Example 1:** **Input:** coins = \[1,3\] **Output:** 2 **Explanation:** You can make the following values: - 0: take \[\] - 1: take \[1\] You can make 2 consecutive integer values starting from 0. **Example 2:** **Input:** coins = \[1,1,1,4\] **Output:** 8 **Explanation:** You can make the following values: - 0: take \[\] - 1: take \[1\] - 2: take \[1,1\] - 3: take \[1,1,1\] - 4: take \[4\] - 5: take \[4,1\] - 6: take \[4,1,1\] - 7: take \[4,1,1,1\] You can make 8 consecutive integer values starting from 0. **Example 3:** **Input:** nums = \[1,4,10,3,1\] **Output:** 20 **Constraints:** * `coins.length == n` * `1 <= n <= 4 * 104` * `1 <= coins[i] <= 4 * 104`
The abstract problem asks to count the number of disjoint pairs with a given sum k. For each possible value x, it can be paired up with k - x. The number of such pairs equals to min(count(x), count(k-x)), unless that x = k / 2, where the number of such pairs will be floor(count(x) / 2).
Array,Hash Table,Two Pointers,Sorting
Medium
1,1830
905
hello everyone welcome to day second of main eco challenge and i hope all of you are having a great time although it's monday all of us are having monday blues but no worries we still have to be consistent while with respect to solving the lead code daily problem the question that we have in today's sort array by parity and even before jumping onto the details of this question let me just introduce myself my name is sanchez i'm working as a software developer for at adobe and today i present day 673 of daily lead good question here in this question you are given an array of integers and you need to move all the even elements first followed by the odd ones to your surprise for all those who have been associated with the channel may know that i have already solved this question in the month of august 2020. these were the initial days when i started the channel i just went through the video i have clearly explained the algorithm and the first month is very close to me because that was the inception time of coding decoded i am attaching its link in the description below do check this video out i have coded live for you guys and i've clearly explained the algorithm start from 0.22 seconds 0.22 seconds 0.22 seconds here it is where i have told the complete algo once you are done with this question and you want to level up the complexity then what you can go for sort array by parity 2. i have already solved this question as well and i'm attaching the link to the descript in the description below for both these videos so do check them out treat it as a division opportunity so that you get a good hold of the concept and the concept seeds into your brain with this let's conclude today's session i hope you will really enjoy both these videos up and i will see you tomorrow with another fresh question but till then goodbye your friend your mentor your catalyst in this journey of yours also if you like these videos then please don't forget to like share and subscribe to the channel thanks for viewing it in advance
Sort Array By Parity
length-of-longest-fibonacci-subsequence
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted. **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 5000` * `0 <= nums[i] <= 5000`
null
Array,Hash Table,Dynamic Programming
Medium
1013
986
in this video we're going to take a look at a legal problem called interval list intersection so we're given two lists of closed intervals uh first list and second list where uh first list at i is equal to start and i basically we have a start time and the end time so each intervals is pairwise disjoint and in sorted order so sorted by the start time okay and uh return the intersection of these two intervals list a closed interval which is a b with a less than b denotes the set of real numbers x with a is less than uh x is less uh yeah a is less than or equal to x and x is less than or equal to b so intersection of two close interval is set of real numbers that are either empty or represented as a closed interval for example the intersection of 1 3 and 2 4 is a 2 3 right so we have a intersection of the interval between those two right so here you can see we have an example of two intervals right so you can see we have two intervals like this uh those two intervals and the intersection of those intervals is going to be the start time which is the maximum start time between those two interval and the minimum end time between those two interval which is this one right so you can see that both of those intervals contains this interval right so in this case that's the intersection of those two intervals it's gonna be from here uh one second from here right all the way to here okay and that's why you see there's like a little uh time interval at the bottom that's the answer that we're gonna return um and then here you can see we also have another interval right which intersects with this two interval right here so you can see that this is equal to this so we're returning the same start time in this case it's 5 right and then we also have an intersection between here and here so this is going to be 8 to 10 okay in this case we're just trying to return a list of intersections for those two lists right so we return that in a 2d array right so array of intervals and uh if there's no intersections right so there's no overlapping then we're just going to return empty or empty list right for example here you can see they're not overlapping with each other then we're just going to return um sorry there's there is overlapping my bed if there is overlapping then we're just going to make sure we find the overlapping and return it and they find the intersection and we turn a list if there is no overlapping then we want to make sure we're returning none uh we're pretty much return empty list right so let's take a look at how we're going to solve this problem so first i'm going to talk about how can we find the intersection first so to find an intersection just like i mentioned we're going to let's say we have two intervals like this where they're intersecting with each other right so to find the intersection point is going to be here and here right so it's going to be the start time is going to be the maximum start time between those two which is here and the minimum end time between those two is gonna be here okay so that's why we have a intersection which is basically the maximum of the start time between those two the minimum and time between those two so it's gonna be those two right so we're gonna return we're gonna save it in a um array two uh integer array with size of two this is the start time this is the end time we're gonna add it to our list and uh one more example if we have a no intersection or i should say no overlapping then we don't have to add them up right um and let's say we have another example like this where we have something like this right we have to get same thing we have to get a maximum start time which is here the minimum end time which is here so that's going to be the intersection for those two lists right or i should say those two interval so now you know how to find the intersection now let's take a look at how we can be able to find all the intersections right so normally what we're going to do is we're going to compare the overlapping intervals right so if there's no overlapping so for example this one what we're going to do is we're going to move the i pointer so i is going to be the upper one and j is going to be the lower one or the lower um interval right now we're just trying to figure out which interval should we compare with so in this case for the above two examples right example one example two you can see there's no overlapping so if there's no overlapping we're going to make sure we move a interval that is um in this case is a smaller interval right where it happens before or the interval that happens before then we want to make sure that we move that interval where the end time is less than this end time then we want to make sure that we move this interval one to the right so we can compare with the next interval uh in the first list right and then in this case if we have an end time if there's no inter overlapping and the end time is less than the this end time right here right then what we're going to do let's say this is e1 this is e2 if e1 is less bigger than e2 and there's the overlapping we're just gonna move the e2 one to the right so that we can compare the nest interval with this interval right here right so next interval let's say somewhere around here we want to compare this with this okay so then here let's say we have overlapping like this so what we're going to do is we want to make sure we find the intersection which is here and here okay like i just talked about right so now we know there's an overlapping and we want to make sure we find the intersection save it add to our list and then what we're going to do then is we're going to move on same thing same procedure so whoever has a smaller end time where we'll move the nest move the pointer one to the right so in this case this has a smaller end time so e1 is smaller than e2 then we're going to move the i pointer which is the list one pointer move one to the right and same thing here once we find overlapping we're going to uh save those in this interval right the intersection interval onto our list and then we can do is we're going to compare to see whoever has the smallest end time will basically uh like move that pointer one to the right so in this case it's j because this e2 has a smaller end time than e1 so we're gonna move the j point one to the right okay so now what we're gonna do is we're gonna uh focus on how can we like define if this is a um if there's overlapping right because i can have something like this right i can have something like this and uh we can say that oh there's overlapping because in this case s1 let's call it s2 because this is the lower one and this is s1 right in this case we can say is this e1 is bigger than e2 right if e1 is bigger than e2 there's overlapping then what if we have something like uh like this i'm going to show you an example right so let's say we have something like this is e1 and this is s2 right d1 is still bigger than s2 so how can we identify if there's overlapping well a good way i think in my opinion a easy way and identify if there's overlapping like basically we want to check to see if s2 is between s1 and e1 if it is there's overlapping right so what we're going to do is we're going to find the intersection and so on and same thing here if e uh if s1 is between s2 and e2 then we're going to know that there's overlapping then we're just going to proceed get the um intersection interval right so now we know how to solve this problem let's take a look at how we can do this in code um so first what we're going to do is we're going to define the list that we're going to return our land that we're going to return at the end so our result list once we return define our result list we're going to define um in this case the endpoint right so we're going to have the length of the uh so m1 which is basically the length s first list and uh basically define n1 and 2 which is the end of uh the length of the uh second list uh then we're going to do is we're going to iterate right so while um we're going to define our pointers right so define pointers so we're going to have our i and j so i is going to be the pointer for first list and the j is going to be the pointer for the second list and then while they are less than n1 and 2 we're just going to continue to find our intersection right so we're going to find uh interval intersection okay so what we're going to do at the end we want to make sure we return the result list all right so let's try to define those intersections so we have a result list which stores a integer array okay so then we're gonna define our n one and two so what we're gonna do is we're gonna say integer and one which is equal to first list dot length that length okay and then two is equal to second list that length all right and we also have our pointers which is i is going to go to zero j is also equal to zero so i is basically uh mainly for the pointer for the first list and the j is going to be the pointer for the second list um and then we also going to say is this we're going to say while i is less than one and j is less than n2 we going to find the first uh we're going to find the interval section right so what we're going to do is this uh let's say if there's a situation where we have none overlapping right just like i mentioned we're going to move the pointer 1 to the i pointer 1 to the right or the j pointer one to the right and if there's overlapping we want to get the intersection right and then we want to move the pointers so we can move the pointers uh part last right so move the pointers but first we want to see if there's or intersection so add enter section right there's an intersection we added so we're going to do is this so if okay so if first let's try to define those values so let's so you notice that we have s1 s2 e1 e2 now let's define those so we have s1 which is equal to first list at i right at zero that's the first start time we also have e1 right which is equal to first list i have one okay we also have s2 which is equal to second list at j right make sure we use j zero okay integer e2 which is equal to second list j at one okay and once we have those variables what we're going to do is we're going to compare uh we want to first see if s2 is between s one and e one okay so e s one is less than or equal to s two and s two is less than or equal to e one that there that means that there's an intersection and we're also going to say if or right or if there's a situation where we have s1 is between s2 and e2 so s2 is less than or equal to s1 and s1 is less than or equal to e2 okay so then we're gonna uh you know in this case we're just going to find the maximum right so in this case the maximum starts so the start time is going to be maximum between s1 and s2 right we just talked about this we want to find the maximum start time and the minimum end time between those two interval so and is equal to the minimum that minimum e1 and e2 okay once we find those we're going to put them in a right so current is equal to uh s and e right and then we're going to add this into the integer array onto our results okay so once we add the intersection we're going to move our pointers right so uh what we're going to do is this we're going to say if the current and if e2 right is bigger than e1 right this is e1 this is e2 if e2 is bigger than e1 we're going to move each e1 right if e2 is bigger than e1 we're going to move the e i pointed one to the right so if e2 is bigger than e1 i'm gonna move the iphone one to the right otherwise we can just move the j pointer one to the right and at the end we're gonna do is we're gonna continue to do that until we find all the interval sections right so we basically define those variables um and then we're going to check to see if there's intersection we add the intersection if there is um and then what we're going to do then is we're going to move our pointers right so if the end if n2 is bigger than n1 then we're going to move the ipod and one to the right if in this case otherwise if we have uh and m1 e1 right e1 is this bigger than e2 and we're going to move the j point one to the right now the end we're going to return results but we want to make sure we return in a 2d array right so in this case it's going to be 2 array it's going to be result.size it's going to be result.size it's going to be result.size and then for each interval we have two slots start time and the end time now let's try to run our code all right let's try to run with few more examples okay now let's try to submit our code and there you go uh this is how we solve the interval section or intersection so the time complexity in this case is going to be big o of m plus n m is going to be number of elements or number of intervals we have in first list and n is going to be number of intervals we have in the second list so there you have it and thank you for watching
Interval List Intersections
largest-time-for-given-digits
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
String,Enumeration
Medium
null
367
hey guys persistent programmer here and today we're gonna do another legal question valid perfect square okay so let's understand what the problem is asking so we are given a number here and we need to find out if it's a perfect square or not and we're not allowed to use any built-in not allowed to use any built-in not allowed to use any built-in functions like square root because that would be very easy we just find if it's a square root of something and then we turn the answer okay so for example if we're given a 25 we would return true because this is a perfect square five times five and if we're given a number that's not a perfect square we just need to return false great so let's look at some ways we can solve this problem well the first solution that came to my mind is just to iterate from 1 up to n so let's say our n is 25 and then at each point take the square so one square is 1 2 squared is 4 and then compare if this is equal to our input or not so 3 squared is 9 4 squared is 16 and 5 square is 25 so when we find that match we can just go ahead and return true now this is not the most optimal solution as we would do off n operations here or off n over 2 and why do I say that's because we need to observe that if we are looking for the perfect square of this number it cannot be more than half of the values so let's say our input is 16 and the maximum we can have as our square root is half of this lot because if you go beyond this you won't be able to it will be higher than our input so there is no possible way that we can actually find the square root of the number when it's higher than n over 2 so that's one observation we need to make and you can try this out yourself you can go through each of the elements and see okay is it possible to do this and it's not because it needs to be half of our and size so that's the first observation and then the second observation we can make is well this input if we take from our first point to our and over to this is a sorted array and what is the what is one of the most optimal ways to search in a sorted array and the answer is binary search and that's exactly what we need to do here to solve this problem in the most optimal way okay if you haven't done binary search before I recommend you do a few examples before trying out this problem because it will be easier for you to understand also if you want me to do a separate video just on binary search then let me know in the comments below and I can organize that video just focusing on binary search okay back to this problem here so in binary search we know we need to have a left and we will have our right so our right index is going to be our n over 2 index because our answer cannot be higher than this rightmost index and if we take this array our mid will be 4 here right so this is our mid now what we need to do is each time we find a mid we need to square it and see if the answer is our input and it's just as simple as that so here we would take 4 and then 4 square equals 16 and we can just go ahead and return true and let's take our example where we need to return false so if we're given an input of 10 our left would be here our right would be here and then we would have our maid over here so well we can see that 3 is actually less than our target so 3 squared is 9 is less than our target 10 so we need to move our mid over so we will say the next mate is 4 and then 4 is 4 square is 16 so that is greater than our input right so we would just return a false in this case it would just not return true because we didn't find a case where our mid is equal to our mid square or our mid times mate is equal to our target okay so to review what we need to do is we need to make our upper bound and over to because we can't find a case where we iterate over the entire array and the last element is the square of itself like 16 square is now going to be 16 and the second thing we need to apply is binary search so if all of this make sense then we can go ahead and look at the code great so I'm back in the code and what I've done is I've initialized or left to 1 because we are going to start our index from 1 in this case and our right is going to be our number over 2 and I've taken the sealing function of that because if we have an input 1 we need to take the higher value of that ok so what I'm gonna do is just start with a regular the same way we'll do a regular binary search so while left is less than equal to right what I want to do is calculate my mid so I'm going to do mid equals we need to take left + right and take divided by 2 and take the floor function of that so this is how you would do that in Python and then what we need to do is find the target we are looking for to compare so that is our square so this is our mid square so we can say square equals mid time Smith okay and that we just need to check if this square is equal to our target lung so if square equals none well in that case we can just go ahead and return true okay else we need to control our boundaries so if the square is less than um then we need to adjust our left side so left equals made plus one and else we need to adjust the right side so else write equals mid minus one and if we can't find the number then what we're gonna do is go ahead and return false okay so let's run cold okay we have a runtime error okay there is a typo so we need to say you know not nums here you have one code okay great so my answer is the expected answer and then I will go ahead and submit awesome accepted so if you liked this video give it a big thumbs up I hope you enjoyed this video if you like my videos please subscribe to my channel alright happy coding guys
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
958
so welcome back and this is March 15th and this is today's daily Lee code problem so today it was another binary tree question and it's honestly been the theme of the week where each problem so far they've been giving binary tree questions so this is great tree practice so what we have here is we want to see if the given tree is complete now a complete binary tree is when at every level all of the nodes are full and so that just means that there's no missing nodes at any of the levels going down and then at the bottom most level the nodes are being Filled from left to right okay so in this case since the topmost levels are all full there's no missing nodes and then the bottommost levels the nodes are filled from left to right it's okay that there's one missing here as long as it's being Filled from left to right makes sense and so secondly if we look at this example we know that this is not a complete binary tree because well although these first two levels are full the bottom most level isn't being Filled from left to right since we're actually missing a node right here okay so I think that kind of defines most of the edge cases like I think these two examples are enough to kind of get you going so what we're going to do is provide a breadth first search solution for this and we're going to do it iteratively not recursively and this is also called like level order traversal and I think that's why I find this question fairly easy to get started and it's just because the intuition behind how you solve it can come quite naturally it may just be coming out with code that makes it a medium level question that's because you can kind of understand how if you look at this and you might say Okay I want to explore at each level and I want to say okay is this level full and does it kind of fill from left to right yes it does and then the next one yes it does and then the final one okay no it's not full but is being Filled from left to right and there's no other level below it right and so that's where you know it's easy to whiteboard the question like might be hard to come up with the code itself so why don't we go ahead and get started so this is once again the iterative solution for it and so we're gonna have a cue since we're dealing with breadth first search and we're going to immediately put the root node inside of it so while we have our Q we're going to continue iterating and we'll say okay for underscore in range and the length of our Q This is just standard templating for whenever you're writing a kind of iterative breadth first search solution so if you ever want to see like a templated um how to perform but first search iteratively this is often like the standard code you would see so this is where I'm pulling it from and so next what we're going to do is we'll say okay you know whether or not it's complete or not and there's a very simple way you can actually do this and once you see it like it's it clicks very quickly okay so what we can say is okay once you see the first kind of empty node here there should be no other nodes that come after it right so in this case since the first time when you're exploring these levels we visit this node then this node this one then this one that's how we'll be kind of looking through the node once we see okay now that I've gone to this place and there's no node here I shouldn't see any other nodes and yes that's correct when we tried to continue new iterating there was nothing else and so that's how we know it's a complete binary tree but in this case we see that okay we visit this node this one and then we see okay we found a null like we can say found null is equal to true but then since we see a node that comes after it and we already found a null pointer then we know okay this is not a complete binary tree all right so if that explanation doesn't make sense maybe we watch what I just said or I think looking at the code it can quickly make a lot more sense so why don't we go ahead and Implement that so what we'll have is a variable called found null just like we um explain or described so now we'll be initially set to false so then we can say okay our node is equal to the Q and I just realized we won't be using uh collections library and use the DQ and grab the root from it and so then we just pop left and then we have that node and so we say Okay if that node doesn't exist then we'll set our found null equal to true and so from there we want a nexif statement and so this is already saying okay this is how we handle actually setting okay we found that null and then we want to say okay what if we found null and so that means that okay since this queue is going from left to right we haven't sorted that order yet but we're going to as we're going from left to right when we still have something on our queue and it gets popped off if the previous iteration or previous thing that was popped off was null that will have been set to true and so we know in the case where okay the previous node that we were looking at was null and so since something else was on the Queue here we can return false immediately so let's just quickly return false and then finally what we're going to do is we're just going to add to our cue from left to right so we'll do let's think here Q dot append node left and same thing with the right node and so the reason why we're not even checking okay if no dot left and no dot right exists is because we want to do it at this level here when we set our found null equals true so other than that we just want to return true if we're able to iterate through our entire tree or through our entire queue all right oh we got a false here and we shouldn't have been let's check that case so here if found null oh here we want to do um an outsef here so yeah because we don't want to set it in that case let's increment these go ahead and try that accepted yeah so just what I did wrong there is okay we don't if not node is found then we set found no null equal to true but then since this case was coming right after it and we didn't have an outsif it would just immediately return false so we were always kind of returning false whenever we found a null which we don't want to do so just splitting up this okay if not node otherwise do this and then finally else we'll do this logic okay great so let's try and submit that and that's the daily problem so I think you know that helped a lot and initially I didn't understand that relation where okay we can kind of handle it generically where once you find your first null if you find a note after that or if there's another node in the queue that comes after it then it's not a complete binary tree right so that's the I think that's the real trick here the way I solved it initially was I just kind of did a typical level order traversal and then I just had these kind of if and out statements or Boolean variables these flags I was using to check okay was the kind of previous uh level full or not or okay was the previous no node null and so I just handled you know these two independent edge cases um which kind of made it really confusing to read the code I didn't realize that okay you can actually do it all generically so yeah so I hope it helped and good luck with tomorrow's algorithm have a great day thanks
Check Completeness of a Binary Tree
sort-array-by-parity-ii
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, 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`. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** true **Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. **Example 2:** **Input:** root = \[1,2,3,4,5,null,7\] **Output:** false **Explanation:** The node with value 7 isn't as far left as possible. **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `1 <= Node.val <= 1000`
null
Array,Two Pointers,Sorting
Easy
2271,2283,2327
41
welcome to the coding interview question first missing positive you're given an unsorted integer array find the smallest missing positive integer this is the problem statement the constraint to this problem is that we have to solve this problem in linear time complexity and in constant space complexity for example if you're given this array then we have to return 3 because the missing positive in this array is for that we need to return 3 the number needs to be minimum and the number greater than 0 right if we are given this array as input then we have to return to because 2 is the missing positive integer in this array if you are given this array as input then we have to return 1 because 1 is the missing positive number now how we can solve this problem in linear time complexity and in constant space complexity let's see this is our algorithm for sake of understanding let's assume we're given this array as input first let's talk about perfect position what is the perfect position for this element one in its perfect position if we see the index plus one equals to that element here we see index zero plus one is one and the element we have here one so one in it perfect position and here we have two index plus 1 equals to 2 so 2 is in its perfect position and here we see 2 and here we have 0 so 0 is not in its perfect position all right first our goal is to replace all the element in the perfect position in the array then we will traverse this array from left to right and we will return the missing positive number if we found an element is not in its perfect position here we see 0 is not in its perfect position so we will return the index plus one that is two plus one three now let's see how this algorithm actually works for first iteration i equals to zero and here we see one is not greater than the length of this array is three so one is not greater than three and one is not less than or equals to zero then else if this condition is true and here we're checking if the current element in its perfect position then let's go to the next element we are at here okay here we're gonna check this condition if 2 is greater than 3 or 2 is less than or equals to 0 this condition falls then it check again does 2 in it perfect position yes it is so let's go to the next element in this case 2 for 2 we see that we have 0 so this condition is true so let's go to the next element on the next we have no element okay so we're done now we're going to traverse this array from left to right whenever we found an element is not in it perfect position then we will return the index plot one we have here two so two plus one is three if we are given this array as input let's see how we can solve this problem okay first we're going to reflect this element is three which the perfect element we can have at this index zero so zero plus one is one so here we will have one okay then four and there is no perfect position for four right then minus one there is no perfect position for minus one then we have one during replace this element three with one we will also move this three to here okay here we see that three is not in its perfect position the perfect position of three is here so three goes here and -1 goes here now we're going to traverse this array from left to right by checking if we have found any element that is not in it perfect position we see here we have 4 here is not in its perfect position so we'll return 1 plus 1 that is 2. now let's see how this algorithm actually works for first iteration i equals 2 0 right so at 0 index we have element 3 is not greater than the length of this array is 4 so 3 is not greater than 4 and 3 is not less than or equals to 0 then we're gonna check does 3 in it perfect position no 3 is not in its perfect position so let's move three to its perfect position and this is the perfect position for three so three goes here and we're going to move minus one right over here okay now let's check again that's -1 in okay now let's check again that's -1 in okay now let's check again that's -1 in it perfect position no here we see this condition is true we'll move to the next element in that category does for it in it perfect position no so this condition here true so let's go to the next element in this case we have here the element three does three in its perfect position yes it is so let's go to the next element and that is one right at index three does one in it perfect position no so let's move one to its perfect position the perfect position of one is this okay so at index zero is the perfect position for one so let's move one right over here and let's move minus one right over here so 1 goes here and minus 1 goes here then let's check does -1 in its perfect then let's check does -1 in its perfect then let's check does -1 in its perfect position no so let's go to the next element on the right we have no element okay so we're done now let's traverse this array from left to right when we found an element that is not in its perfect position then we'll return the index plus one for that element so here we have four that not in its perfect position so will written one plus one that is two if you're given this particular array as input let's see how it works first i points to this element 7 the 7 is greater than the length of this array is 5 so 7 is a greater than 5 so let's go to the next element this is our next element again we see 8 is greater than the length of this array so let's go to the next element so 9 is greater than the length of this array let's go to the next limit 11 is greater than the length of this array then let's go to the next limit we see here 12 is greater than the length of this array then let's go to the next element on the right you have no element right so we're done here now let's traverse this array from left to right at index 0 we see 7 is not in its perfect position so we'll return 0 plus 1 that is 1 all right this is how we can solve this problem let's see how we can solve this problem using pseudocode first we're going to declare a function first missing positive that takes an array as input for sake of understanding let's add in this is our given array then we're going to check if the length of the array is 0 then we'll return 1 because if we have no element in an array then we will have the first missing positive is one then we're gonna run a loop for i equals to zero then i less than equals to length of the array and here we do not have the increment we will use increment conditionally all right then we're gonna check if the current element is greater than the length of the array or the current element is less than or equals to zero then we will move to the next element if we see the current element in its perfect position then also we will go to the next element if not then we will swap the element to its perfect position okay and this is the code to swap that when we're done with this for loop we're going to convert this array from left to right for that we have your icons to zero then for i equals to zero i less than length of the array i plus plot then we're gonna check if the current element is not in its perfect position then return the index plus one and that's what we're doing here okay if we're on the end but we don't have the perfect element then we'll return nums i minus one plus one now let's see how this pseudo code work for this array first we have the element 3 we see 3 is not greater than the length of this array and 3 is not less than or equals to 0 and 3 is not in it perfect position then we're going to solve 3 to it perfect position and the value we have at that position okay in this sketch 2 is the perfect position and this is the code to swap okay then let's stop three here minus one right here now still we have i equals to zero let's check it again this is minus one in its perfect position there is no perfect position for -1 so there is no perfect position for -1 so there is no perfect position for -1 so we're going to go to the next element that is 4 we see that for 4 we have no perfect position okay then we're going to move to the next element and that is three so three in its perfect position so let's go to the next element and there is one we see that this condition falls over here and one is not in its perfect position so let's swap one to it perfect position and the perfect position for one is this index zero so one goes here and minus one goes here and we're done with this four loop because on the right we have no element now we have here i equals to zero then we have this loop right over here using this loop we're going to traverse this array from left to right if we found any element that not in its perfect position then we'll return the index of that element plus one the index of this element four is one so one plus one is two and here we see four is not in its perfect position that's what we're returning the index plot one okay and that's what we're doing here okay so for this input this function will return two this solution will takes big of 2n time complexity since we're using two loop here okay and it's equivalent to big o of n and this solution will takes constant space complexity we could we're not using any additional space here we're just using variable okay hope this concept was clear if you have any question if you have any suggestion let us know thanks for watching this video i will see you in the next video till then take care
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
138
Hello guys I am Lalita Agarwal welcome tu jo on your on coding channel code flicks meet wahi you made par you so let no started let card problem aaj ki lead code ke problem kya bol rahi hai achha before going towards d problem na vani discussion par dose Those who have understood this problem well and are willing to try it themselves, see the question, it is literally a very edgy question, it is not something to take much tension, just what do you have to maintain yourself here? Here we have to make a completely new list of ourselves. Now what are the things that we have to keep in mind in the new list, what are the two interests here, one is the next point and at the same time there is another one. If it is a random point, then you have to assign the value of both the pointers to yourself. Now what happens in the next point, keep making your notes and keep linking them to the next rest. But here, if there is another random point, then do it carefully. You will have to understand this thing, yes, okay, now what can be the hint for this, see, there can be a simple solution for this, first of all, I have told that there can be many methods of doing this, there is root first method, there is also a little optimize method, there are more. There is no difference basically, there will be a little difference in space complexity, how it will come in detail, but in the video, those who understand further will take the question here, a small hand is required, there may be a hint as it was in the list, it is fine. Now what we can do here is that the new note is right here in the middle here, after this note, the new note which will be its representative, push on add on here and then add on its representative here. Do it here, advance its representative here, make its representative Dr. and the same will happen with this, will it happen that those who are solving like this, neither at this point of time, the question of making a mistake does not arise, why? Because its representative who comes here will be pointing to whom, he will be finding its next, if he will point to its next, then automatically its contractor will be here which is what it wanted, so this mistake of yours is not even in the story. It will be so that your new note does not accidentally point to the old note on the story. First of all, it will be less. Said yes brother, then what will be less important is that within this same note, you are maintaining a new note. So what is there here that like those who are less of random, we will do it again in another time, we are going to discuss it very comfortably in this video, space will become complex, say, okay, those who have not understood this problem. There is no need to take tension, first of all we are going to understand very comfortably that the question of food has been six, after that we will approach it and give the final bill move towards implementation. Look, understand, the question of food has been six, I have found myself here. First the head node is given, he said, it is a matter of cost, as you travel on the head note, you will get the next node, he said, okay, now whenever there is any mode of life, I will get it with the node. What are the three things that are actually being found? One is the value of the note. Said it is okay. One is at the next point which will be pointing above the next node. Said okay, it is a simple thing and this is a random point which is also a point above any middle. Can do like the random person here is pointing straight towards the tap said ok I understood said yes brother I understood like this is the 13th value note ok this is the next one It will do this and its randomness is doing it to whom, it is doing it to the previous value. Have you understood this? He said, yes sir, this is of 11 note, it is pointing out, it will point out on the next pay and the value can be anything. Yes, I have the power, now what did I have to return here, brother, look, this return and the question are not looking similar. What is the difference between these two? You returned the same question as it was, you exactly copied and pasted it, there were many things to do in it, you were told like this. Yes, but it is not exactly like that, meaning what happened to it means that you have made a copy of it exactly and got it copied and returned. He said, okay, I understood it. He said, yes brother, it is like a copy of it. So what was the opening? Another new note was made, okay, there was a next point in the new note, there was a random point in the new note, which was also its next point, which is pointing to the 13 note, okay, the 13 one. I was also next and it was random and the random one was pointing out the tap, it was ok, similar to the one above, I understood this thing, I said that if I understood, then you just have to make a copy for yourself and get it returned, then I came. Yes, you must have understood the question well, now let's see how we will approach it. Look, first of all there can be two methods to approach it. Look, first of all, if we talk about our approach, then what should be our strength. Which note is fine, he said, yes brother, this is the note, we made another note exactly similar, made seven, made the next one, made it random, OK, then we made one more similar to this one, made it point to the next, made 13, made the next one, made it random, after that Similar to Apna is 11, made next, made 10, made next, made red number, after that made one, made next, did you understand this, said yes brother, after that made tap and then in the last, what did Apna do? Got all the randoms pointed, reason why did you get the randoms pointed last, because what was the initial, you have a problem, this note was not defined, this note was not even refined, so how do you point this one? I understood it, there should be no doubt in it was the easiest method but what was the problem in it, there is no problem in it, you will submit, just what is here but what everyone did here? Space complexity is also ahead, you are not going to rock this one, then what can you do here you try to apply a simple method, what method do you try to apply that you load this one? Okay, this one is the one after this and the next one will be waiting for a new note which he has made which is 7 das maa lo call ok yes and seven das will be pointing like this now after this Which old note is in it, meaning okay, now what happened to this, basically this is what happened, all the chances of making a mistake are gone and what else will happen that we got ours listed in this and then what will we do with this? We will take out both of them separately, we will take out this saree list separately, and later we will take out these saree lists separately. As for the original one, what have you done, these two lists have come out of the same list, now if you are of the same size. If you want to talk in terms of size, do n't want to talk in terms of size, then you would be saying that if it has become similar, then yes brother, if you were not going to return, then in the sense you can say that it has become similar, but what happened here? What happened is that you did not have to create a link list exactly for this, now tell me, now we are going to follow our method in this, we are going to follow this method that first of all, we will define our new notes for each mode. Later he said, okay, then what will you do after that will you reduce yours, that whatever it is a random number, we will define everyone's random numbers, let them be defined, he said, okay, what will you do after that? Like, if you are pointing next, then its net should be pointed to this so that both the lists become separate. Question solved. Was it such an easy question, let's see it exactly. Now come here, first of all, what have you said? That if the head point of yours is pointing to the tap, then the dog is fine after returning from there, then do not slide anything else, leave them, they have no meaning, after that, what did you do with the original? The original says, ' what did you do with the original? The original says, ' what did you do with the original? The original says, ' Had note from where it is starting', 'It is Had note from where it is starting', 'It is Had note from where it is starting', 'It is absolutely correct', 'So what did you do? On absolutely correct', 'So what did you do? On absolutely correct', 'So what did you do? On top of this, you retreated on the whole, and when you retreat, what did you say? 'Come inside,' first of all, tell me, is say? 'Come inside,' first of all, tell me, is say? 'Come inside,' first of all, tell me, is this the null point? Is he pointing to the tap or is he himself loaded, is it a tap? No brother, it is not like that at all, it is okay, it is inside, it has come inside, what did you say that a temple has not been made, what will it become, a new note will be made, he said, it is okay whose The value of the original one will remain inside, meaning if its value is taken then exactly 7 is taken inside it. Said, yes brother, now the next time will be the same, it will also be found by finding the one to which the original is pointing, meaning it is pointing to 13. He must have said, yes brother, now the next one of the original has been made by him, whose tempo has he made, then whom was the tempo pointing to, 13 and seven is it pointing to the new note which has just been made for reading, have you understood at the moment? Basically, what happened to Apna is that a new note has got inside everywhere as Apna had said, when the new note has been inside, there is no problem in it, then Apna returned the original back to Apna Kya Hai Head. He pointed to it is a simple thing, he said, yes brother, it is a simple thing, there should not be any problem in it, and he says, what was the next head of the new note has been made by making a new note, isn't it? It is correct, he said, yes brother, so whom did he represent him, he got the new headset from the new note, then he took it from the office, now what to do back to the original, train him till the last and here he said that if the original Joe If its random is pointing to someone or the other, then what will we say about the next original collection of the original, that is, the random of its new note is its own point. Have you understood whose random here? The random of the original. That means it will be set at random, meaning the person whose random it was also set at random. Got it, said yes brother, I understood, there is no problem in this, so here we have set all the friend numbers here. What will you do, tell me quickly, will you reduce your list here to a simple one or will you break these two lists separately, there should be no problem in this, he said, okay, it is a simple thing, so what did you do to break it here? Pointed the headset to the original and then he said, what should I take at the time, the next of the original means its next, you said ok, then now the one which was next to the original, put it next to the original, if it is the next of the next then Means Seven went back to find 13 and the seventh one is here in his tempo. Right now and after that, if you do n't store it then yours will get separated. It shouldn't be about such a simple thing. Said, yes brother and Apna has stored it inside Already, so keep in mind that Apna has kept its link intact, otherwise it would have been linked, then Jai Mata Di, nothing could have happened after that, then what did Apna say, tell me. Now the original one, does that RK exist? If ever he enters the channel, he does not start pointing and he does not start pointing the tap and further still he exits. He said, okay, so what did he do in the original? The original which was Tampa next. He was pointing to 3. Okay, so what did you say, do n't point to three. If you are pointing to the one who is next to the original, then whom will he point to? This 7 is pointing to the new one, 13. Okay, did you understand this? Said, Yes brother, if you understood then what did you do? From here, I wrote down both the links and separated them. Ok brother, I understood, what to read in the last and returned it to the no head. I hope you understand it well. Still, if you have any doubt then please send it in the comment box only, but you can see by submitting, it is done easily, now if we talk about its space complexity, then the first thing is how much time complexity is there. If we talk about how much she is going off and on and if we talk about our space then see exactly what is happening that we are doing, then if we look at it from our perspective then we can say that you are there but ours. What is it that you are inserting new notes inside the old list and wherever you are not setting your random note along with it, then what is the reason for that, it will not be exactly off and it will not be. Did you understand this? Said yes. Brother, have you understood that there should be no doubt about this? You must have understood by watching Thank You Thanks
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
1,776
hey everybody this is larry this is me going over q4 of the recently code daily or leeco contest uh car free two so basically you're given these uh you're giving these positions and there are a couple of ways to do it and i think there are apparently there are some math mathematical ways of doing this uh with respect to convex hoe and the lower hull and stuff like that um but actually that's not how i did it um i actually you know and you could watch me solve this live during the contest afterwards so be sure to hit the like button to subscribe and draw me on discord but um did i say that already but yeah um so you can actually solve this with mono stack and that's how i did it um and the reason and the thing that i always say about mono stack and i hate actually spoiling that a little bit because for me i never think about a mono stack i think about um the questions that i asked to solve this problem and for me just visualizing this i go okay um you know there's a couple of examples but for example 3.54 right of examples but for example 3.54 right of examples but for example 3.54 right well they'll never catch each other but we know that um you know for three four it catches up to six three right um because well four is bigger than three so you know that at some point it would catch up to that and then from that alone you ask yourself okay so what is the next number to the right of this number so you know given this car what is the next car to the right of this car that has a slower speed because then you know that you're gonna hit it um so that's part one and that's not enough but that's basically the questions that you ask and it turns out that we use the stack and keeping that as an invariant of the largest number to the right that is you know to the you know in the monotonically increasing way and the variant is such that you know um if you have a four okay well this one is a bad example but let's go back to here for a second you know you push the two the speed of two on the stack you push the three on the stack um let's actually do that in a live way give me a second so you have something like this um you know that three is gonna be faster than two so that's great uh here's the one right well the one um well let's think about what this means to update right because here two means that two is the smallest number to the right of everything to the left because that's just by default there's only one um three in this case well um the only two questions right so now let's say your stack is two and three and now they're oh okay let's change the stack a little let's change this to five sorry i'm jumping a little bit um let's say we have a number three right so this is the stack let's say number three comes in right um well then the question is what's the smallest number well let's put let's think about putting this on a three for now right how where do we want to put the degree and then that means that okay later on let's say there's a four well what is the next number that is smaller than a four well it's always going to be three of course um and it'll never be five right why would it never be five because anything that's after three you know if it's the only two scenarios it's if it's bigger if you know we have a four and four is bigger than three um everything that's after three or everything that's bigger than three that's after 3 we'll have 3 as the answer right 3 can only be the answer to that question um let's say the other possibility which is the number is less than 3. if the number is 1 for example then in that case well 3 can never be the answer but five could also never be the answer right so in that case it's safe to say that when we see this three coming back to here we can remove the five um so that's the idea behind the mono stack and it turns out that the stack is monotonically increasing if you keep this probably true and this is why this is a mono stack but that's an that's a property that is emerging and not cut enough right so okay so by that it is not sufficient to solve this problem uh because if you implement this problem as i did during the contest um you'll notice that well in this case uh the three four will not hit the yeah let's say we already built this thing out well the three four will not hit the five four right because they never will catch each other right but it will still hit this car when this car combines of this car right because when this car combines with this car at a certain point well what happens is that they become one supercar with a speed of debris um and they combine at a point that is when they converge which means that um well the two well in this case let's say the speed is much higher so that there's less confusion right um well whatever this combine whenever this combines with this um well three is going to be a new speed and wherever they connect um the thing is that this car speed will never be closer to this car until it hits this car so that means that the time that this car hits this car will be the delta between six and three right so it doesn't matter when they collide this calculates of this one so in a way you could also pop this off the stack okay so that's part one so the answer is that if you do it this way um you know to get the answer for this particular input actually uh you would get you'd actually get you know and we could do the math together but you actually get the answer where this answer is actually three why is this three because the answer assumes that you know it takes three steps for this car to um catch up to this car um it takes three seconds but the answer is actually two because actually it takes two seconds for this car to match up with this car right and what does that mean and it takes me a lot a little bit of time to kind of figure out what that means but uh during the contest well the thing is that after 1.5 seconds well the thing is that after 1.5 seconds well the thing is that after 1.5 seconds this car is basically becomes this car right so at 1.5 seconds this car becomes this so at 1.5 seconds this car becomes this so at 1.5 seconds this car becomes this car so let's call them let's say you have a car a you have car b and cross c right so car at 1.5 seconds car b crashes at 1.5 seconds car b crashes at 1.5 seconds car b crashes into car c and they merge into one so that means that it will never take three seconds to get from a to b because b already became another car the speed already changes changed after 1.5 seconds 1.5 seconds 1.5 seconds so then now still as part of the mono stack or stack and this is why i don't like mono stacks because it kind of can confuses you to kind of be locked in one solution but it really is just a stack right well the question is at 1.5 seconds this well the question is at 1.5 seconds this well the question is at 1.5 seconds this can no longer be the answer right um so then now we and we know that from this card to this card takes three seconds that means that we can pop this off and then now we ask ourselves well what well sorry um then now we pop this off and then we ask ourselves okay that means that we have to you know we have to do better than three seconds right because 1.5 seconds there's a event so then we 1.5 seconds there's a event so then we 1.5 seconds there's a event so then we look at their previous card that they crash into which is their minimum which is why we pop and from here three four to nine one is actually two seconds and you can do the math and that basically gives us out the answer um is this it's basically um i don't that's why i don't like the term mono stack because uh in a way it's a mono stack but in a better way it's just a stack implementation where you're trying to keep an invariant and then variant in this case is you know the two things uh you know find you know keep asking you know for each car what is the car i'm going to collide with right so that's not that marion that's the question uh but that's the question that you need to ask yourself and then varian is this is or there are two observations um one is uh we only crash with cars that are that came earlier or that is slower sorry that is slower and then two is um two is how do you say this um as you scan from right to or as you pop things off the stack it's when um it's when uh it is at the optimal time to uh crash the car because basically you know going back to what we did here if it took three seconds to crash from this to this but this car is no longer the car at 1.5 seconds so you have the car at 1.5 seconds so you have the car at 1.5 seconds so you have to look at the car it becomes at 1.5 seconds the car it becomes at 1.5 seconds the car it becomes at 1.5 seconds because it took three seconds right so basically the invariant is just you know keep true that the top of the stack is the best answer for this current car if not we pop or we if not i mean yeah i guess if not you just keep doing it pop until this is true and that's basically what my code looks at um and i could actually you know i will just during the contest so it's a little bit awkward but you can actually optimize this a little bit by so how would i optimize this right or like in terms of writing this and then i'll explain it a little bit is i actually would do something like yeah i'll just move this if statement here because it's still it's the same if uh this is true we got select.pop and then we continue we got select.pop and then we continue we got select.pop and then we continue um so we can move this here and then we could just move this to afterwards um yeah um and know that this break would never happen but basically yeah this is my code um so the stack contains three things we have what i have to have x the speed and then the time um the time of collusion right um so basically that's basically what i did for each type of the stack we check if the speed is slower then we automatically you know if the speed is lower there's no way to um catch up to this car right so if there's no way to catch up to this car then we have to try to um unless this car crashes to an earlier call right and so therefore it can no longer be the answer for us and also it cannot be the longer uh the answer for the future cause as well as we talked about this i know just to be sure clear our cars are processed from the end from the right to left um so that we can kind of keep this invariant and then here we this is just a symbol formula of the um actually wow my variable names are terrible so this is actually d this is actually dx and this is v right or dv so this is dx dv um and this is basically the last collusion time and this is the current collusion time and this is dxtv i don't know why i chose the names but it was terrible but yeah and then here as we said if the current crash time is later than the car like how did i say this if the call if the car we're crashing into already crashed into another car before this then it can no longer ever be the answer right and the reason is because um later cars can only uh crash to it earlier so then that you're gated that way right so then we popped a stack so that um so that the while stack loop goes again so then we basically do the same thing right otherwise if it's good if this is a good answer then we obviously we put it to the answer away which we also reverse later on um and then we mark the current speed x the current uh distance the current speed and then the current time that we're going to crash and then that's pretty much it um and at the very end and this is at infinite time um because that's you know so that uh this time this thing will never be true but it also because there's no cost for it to crash into that you know so that's basically the time that it would go into and then we just enter uh append negative one and the x and the speed of the current car that we're crashing into um and that's pretty much it uh for the analysis uh let me make this slightly smaller so you could screenshot this if you like uh well with just a quote um and i'm gonna go over the complexity which is it should be straightforward to see which is that you know the space complexes are uh more easier it's linear because we have a stack and then first for um for yeah for the time complexity well each car can only be in the stack once because it either gets pushed well it will get pushed once or well maybe it doesn't have to be but yeah so each item will get pushed once and then pop once at most so that means that it's going to be constant number of operations per item and because they're all of n items uh of n items so over one oh of n total time um and that's all i have linear time linear space let me know what you think about this problem hit the like button and actually i don't know why but when i was selling this during the contest i actually explained a lot of stuff and it slowed me down so i don't know why i was doing it but uh but you could watch that next and let me know what you think uh ta-da okay so i have a hard q for so uh ta-da okay so i have a hard q for so uh ta-da okay so i have a hard q for so maybe i could catch up some points here um i have two was yeah this is not looking good for me but uh 583 of two wrong answers that was and that was like this and i got it like 20 minutes ago but i just kind of was silly about it um okay they're end cards okay so speed eyes for this one i want to see how many wrong answers people get and seems like even smart people are getting one but i also got in like 10 minutes so i have some chance of getting it maybe um okay after one soon okay what does this mean so you have one two you find out where they intersected what does the next car mean once again it could be any car right okay cars in the form i wish i got q3 faster because now i feel like i'm gonna eat it on this one because this one's a hard problem and i should have gotten it i got it really quickly it's just i had to type one and i misunderstood what they meant um i mean this is i've caught collided to the next car i feel like they have to explain this a little bit maybe not okay and then they never collide okay maybe not just i think this explanation is good i don't know why they put explanation in and like this i have to scroll all the way to the right to read it but that's fine um so it's just about dismatching this right so you have these events it's just a sorting thing and then yeah okay what does that mean so no matter when you know that when this one and this one will collide because it cannot skip ahead so it's just about timing and then or the slowest car in this free that's a that's the difference is that if this collect but we can just do the defense for that way um how can we update it though i mean this is just a heap type problem but we have to figure out how to do it in a smart way so that when they collide together because i think this one like maybe this one could catch up to this one but because they collided oh well not this case but is that true well the slowest car will always be the one to the most to the right most because so then variant is that when the slowest car you cannot if you didn't catch up then by itself it cannot catch up anyway right like just another car collided and this would never catch up okay so this is just events and this is just is it just a json like is there any way to overtake a number i mean i think i have to use the heap anyway but this is doable i just have to figure out the clean way of doing it uh which is because the key thing is you could have something i think the biggest uh issue is that you have something like i don't know the numbers but someone like this may be really fast but if this is next to each other then you know so this may get there here really fast but what am i trying to say oh no i think the other way i could have something like this now then this would always go first right you have something like this then either this hits this or yeah i don't i'm trying to find a counter example for why what i'm thinking is wrong but maybe i'm over complicating things because people got it really fast well maybe not 38 minutes maybe some weirdness here as well i don't have a counter example though but if it was that easy it just math then it shouldn't be that hard but i am going to try to maybe i have to give the wrong answer to find out this one may be cool it doesn't i don't get it so okay fine i'm just going to do it the dumb way and if i'm wrong then i'm wrong okay i don't know why i did it this way that's the space oh my god oh wait what how did this ever catch us up to this oh because after this connects to or this will never catch up until this hits this and then now this hits that so that now the question is so the n square question is this catching that right and then the answer is for all the numbers to the right what is the next number that is slower than this so that you can catch up okay so i can do that um actually that's a different problem but okay that's actually cute i like this one about and i can figure it out um which is why i like it no but okay let me think about how to do it so going backwards so this is like a mono two thing but i'm gonna do a heap for sure probably so you want to get the next so what am i asking so i want to get the so this is a four i want to get the next number that's strictly less than this and yeah then put the four two okay this is a good problem i could solve it um uh okay maybe i should just do something like this actually for what's it okay and then i have a stack as usual oh okay yeah okay otherwise we look at the next number that's smaller than this so okay well stack is greater than zero and stack of negative one um speed so let's go that is greater than or equal to uh speed then that pop otherwise and then if link will stick all right i guess i didn't need to do this but uh but then now i have to put the stack dot a pen x speed um okay fine if i have to do it anyway but i just don't do that answer okay i know i have to do the answer uh so otherwise we're pen okay delta is equal to stack of negative one of zero x minus that d speed dx is equal to our current speed minus stack of negative one by definition and then we subtract um dx over the delta or the other way okay am i done wish me luck nope everything is very negative why is that oh i don't no i pushed afterwards uh xp stack so i start the seven two oh i have to reverse this but that's fine but that's still the wrong answer it's just right yeah a lot of negative ones but okay am i just missing the math one because i think i got it right because speed is a delta speed and oh yeah this is and it's just a little bit confusing nothing okay uh that looks good maybe oh no i got a wrong answer here it's so hard to i don't know why they just don't show us the expected answer because it's just hard to read but oh when did they collide that's the problem so we have to do them after because three catches up to here at second three but hmm how do i do the math here i have to combine the numbers in a good way i'm glad that discarded because i would have got in the wrong answer so because it takes from three to six three seconds but it's two seconds because why is that two seconds it just takes one second to collide where do you collide why not at six so after one second we collide and this is at four now okay that's uh why i'm close but i have to figure out how to combine so three four five four six three okay so after one second this would catch up at uh this is nine this is seven so this collides at nine and this is at seven after one second and then after the second i mean this is this still moves at three right and this is moving at four so this is the eleven this is twelve so why does am i misunderstanding something why is this just two seconds oh because this may collide with this one because at 1.5 seconds okay one because at 1.5 seconds okay one because at 1.5 seconds okay did i yeah i got that part right so i want i did not consider it so far but okay so at 9 1 um at 1.5 seconds um at 1.5 seconds um at 1.5 seconds this actually becomes one so i have to figure out how to do that oh man that's actually harder than i thought it would be because i thought i was almost done uh because now we have to care about how when does that timing work right so when do they collide this collides at one second so that's fine but now no this collides on this with three seconds but hmm i just have to figure out how to do the math in a good way so it's not just the next one though this will collide with this one but it will collide with this one after so this is the edge case that i was thinking about or trying to think about earlier so this collides with this one and then this one that means that at 1.5 seconds how do i do the math on this dun so the critical point is at 1.5 seconds so the critical point is at 1.5 seconds so the critical point is at 1.5 seconds that we do the math is two so do we need to store the speed in which they collide or the last place where they collide because then now do it to care about this except for we'll never catch up to it so we don't have to but we have to worry about this one and this one now because from three we could collide with nine what does three connect in the line that's two because my math is terrible i have to do it so ten seven and then at two seconds is ten eleven oh no this is eleven okay so that's why okay um but then i have to do everything on this monotonic stack but that's still going to be unscrewing the worst case so i have to do something better hmm okay i mean i think that now i just have to look at the events and then process them and then reprocess them that is a mess how many people have gotten it so far and my penalties are gonna be off the roof because naively this would be n square how do i know this versus this right so i could use some kind of delta array the suffix sum to the map that way maybe a bit i think that's okay i think we could push the answer on the stack and then figure it out because if this is bigger than that then we pop as well because that means something earlier happened okay i think i could get i got it um that time you went zero um okay and then now we can catch up to everything in between but then we do this thing again that is a cool problem if this is correct but um okay um and then the next the last one is timestamp so stack price one two uh time this is the last time so that means that this event had happened so then okay that's good that means that otherwise we want to pop because all right now do the last event that means that something else has happened so that actually this pops and then also that means that this is some infinity value actually for that so then otherwise we pop so that we always collide on the last one otherwise we pop divided by zero what's tx what is dx2 how is this happening oh i have to do it just pops otherwise break and also answer okay enough to yolo let's go pick money let's go yes okay that was a hard problem not gonna lie uh hey yeah thanks for watching hit the like button to subscribe one join me on discord let me know what you think about this prom uh take care of yourself take care of others love you everything and yeah it's a good mental health and i'll see you next fall bye-bye
Car Fleet II
minimum-operations-to-reduce-x-to-zero
There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents: * `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`. * `speedi` is the initial speed of the `ith` car in meters per second. For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet. Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted. **Example 1:** **Input:** cars = \[\[1,2\],\[2,1\],\[4,3\],\[7,2\]\] **Output:** \[1.00000,-1.00000,3.00000,-1.00000\] **Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s. **Example 2:** **Input:** cars = \[\[3,4\],\[5,4\],\[6,3\],\[9,1\]\] **Output:** \[2.00000,1.00000,1.50000,-1.00000\] **Constraints:** * `1 <= cars.length <= 105` * `1 <= positioni, speedi <= 106` * `positioni < positioni+1`
Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily.
Array,Hash Table,Binary Search,Sliding Window,Prefix Sum
Medium
209,560,2183,2290
1,660
Hai gas welcome you today's video and today we are going to do the problem of lead code 1660 whose name is correct now binary tree so let's read it once the question you have a binary tree with a small defect given it is exactly one invalid note very It's right side incorrectly points to node at D from date but to D invalid notes write OK Jivan D root of D binary tree with this defect root returns D root of D binary tree after removing this invalid note and every note underneath it correctly Points, you are ok, so what we are going to do is we are going to remove this defective noun and the defective noun and is which is pointing to a note from the right which is in depth from or is in the level from, so here you can see the example. You can see that 7 is at the 4th level, so that's why it is pointing to a note at the 7th level, so we are going to remove Seven and all its children, so basically we are going to take all the Seven and its Puri. So how are we going to do this, let's take a look at it, so this is our example here, okay, so right now, first of all, by looking at this diagram, I know that we can have two cases. Firstly, how is this seven defective node, it is the left child and second how is this defective noun, it is a right side, so I write this, first how is this defective noun, it is the n right child and second how is this defective noun, it is the left child. Is mine where I and my defective noun is on the right, so if this is my minor current note, this is my current note, then my right child is pointing to someone's price child in depth from me, so this is my how one. Done and K2 of mine can be like this is this note, this is both and this is also from note two and that defective note of mine is the left child so this will be mine but example and here this is the left child and this is where this is so from this If we understand that if he is pointing to the child of the level then it is okay, then first of all my question would be that how do we know that he is pointing from one note to the note of the level, then the question is, can he? Recognized there was no depth from this point, so first of all, after looking at this question, I remember that okay, we have done level order driver sale many times and we are just checking whether our From one note to the level, the right note is pointing to the right note and what happens in our level order, we process each road one level and the example is our first level or second level, this is the third level and this is the fourth. Level so can I do that I because the one my note is pointing to me is pointing to a right side note Defective noun so I can do one less can I do my left side notes first then the right side notes I will process it and note down a scene and keep something, on the right you will process all the notes on the left and if the point on the right side of any of my child nodes comes in the ready scene mode, then I will put it directly inside. You can see here, if I had used this trick in level order, then when I go right or left, what would I process first? In the second level, for the second level, if it was my mother, then I would process one first. And then while processing the one, what should we keep in our set? Keeping the four and nine in the set because we have processed it, then after that when the one is done, then what goes out of my mind is the note with three when I check for free. Is the right point on my left already seen? If so, then this is my defective mode. Can I recognize it like this? Then I can definitely know by doing this. Either it is a left node or it is a right note too. I just have to check that the right point of my child note does not point to any note that is in the depth, then I can directly check that my note means this is our remove mode in BFS. So whatever is its right, if I have got the right of my remove note in the set or if I have got the left right of my remove note in the already set, then it means that whatever note of mine is found in the set, that note will come. The one who is pointing to the mode is itself a defective noun meaning this note here because it is already pointing to the note present in a set means it itself is a defective and if it was not like this and if it was like this then it It would have been if this intake had happened and it would have done this would have been a defective noun at this point in time, so we know that the first thing we did was we looked at how we can process the level order so that we can know that That whatever note is pointing to our note already process note should come later and the process which we are going to note is doing the 2b pointed process note first which means we are going to process its children first. And then after that we are going to process its children and see who is already set and who is not. So I hope you know the approach. If not then don't worry, we will add it once in the algorithm. If we convert it and then code it, then it will understand everything with time, then I will say like this, our algorithm or its answer key, the first process which is D notes children from right, you are left and you are from R, level order from driver and then second point. It happens that the right painter is doing the note on the right side, that is why here both times the right note has been given, whether it is the right point of the left node or the right point of the right note and the left notes, the right painter and the right notes, the right painter points. Other process child treatment self de default it so directly we are its children so similarly if I want to delete this note because this is my fault note then what will I do I will delete this note directly from here tap remove note we remove note our If this is a removed note, then what will happen to it will be freed, it will be directly deleted, for my own trick, what will I do, attack null, you are removed and if it does not happen, then this note of mine is 49, these are set, you indicate that it was displayed, so this is it. Here is our three step answer solution algorithm, you can say like this, what will we do, I hope you understand what we are doing, while processing in each level, we are going right then left first and its children. If we are inserting notes in the set, while processing level 2, I will insert these notes. In our set, I am processing level 3, so it does not have any left or right child. Already see the children notes in our set. Already point to them. Is it pointing or not? If it is not then we will add it directly for next processing but if it is pointing then it means that it is a quality note itself, so we will add the remove note of our remove node. Are you returning it directly from the fault end or are you initializing it so that the entire note and its contents are completely deleted? So this was our approach. I hope guys you got to know about Hood and Algobhi, if not then do n't worry. Everything will be known in the low court so now we will do it code so first of all what I will do is a set and on K level order you can speak to the driver so how will I do it I have taken the set wait and then after that We will go level order driver cell which is the key when will it note equal to zero we do this every time because the size we take the size here and then we go look jo chala hai mobile size - give greater till zero then After that, what we do is from here whether it happens or not, if it does, then I will check, so the first thing I will check is IF I child, then I write this IF and how are we going to process from right to left. If there are any, then I also write this: are any, then I also write this: are any, then I also write this: Start processing child from right to left, then I can have two children, one is remove mode dot right, note it equal, you are null, then this already one child of mine exists, of my remove node, I will process it and after that my left child of remove mode is also not null then I will do some processing. So first of all what we have to do is here let's check that the remove node is not right n and then what are we going to do. Let's take a look here, okay, so if my remove mode is this, if this is my remove mode, then remove note's right child's own right, if it is in the set, then if we have to touch, then how will it come that remove dot. Right dot right note it equal tu null first of all that also should not be null and then we should do our content in the set so I will reduce one and put it to the right of my remove mode so therefore I will be the child of remove mode it will be deleted otherwise what We have to do it otherwise it is not a faulty note so why do we have to add it directly and for processing then correct the note and add it and because now we have processed it then what are we going to do then I hope guys you It is understood that what we are doing is that we are processing the child of the remove mode and seeing whether the child of the remove node has a note processed in any set from the right painter, if it is appointing it or No, otherwise why are we directly adding it to the child and giving it mode as process and storing it in the set, but if it happens that it is pointing from the notes contained in a set, then He himself is a default defective and a defective noun, so what we are going to do is we will directly tap the defective child who was pointing my removal and I will say that I did not have such a defective noun. So I will delete it directly, so similarly we are going to do it here on the left also, so how will we do this if the left right exit of remove mode comes first and the left right exit of remove mode comes in our set dot content. So then it means that this is our defective noun, so put two sets on the left side of remove mode and add it to the set and after all this, what will happen, our entire process will end, level order will be returned and our route will be returned. Let's run it once and then let's see if there are any mistakes, what I have added below, OK, Null, Final, OK, Right, Left, Right, Well, here it is still there, it is taking the wrong setting. Why are you taking notes So KFC will work for us, otherwise KMT is a relief, then you will not leave, once you run, it will be accepted Okay, so now we will write it in CPC and then we will do it. Very well, I have commented this, I am going to copy it. Okay, so this is our comment, so what will we do now we will write our entire program, so what we were doing, first of all we were creating why and BF, so we will do it here. The hall will set, its name will be there and then our why will be the train and its name will be size = K size and then the innerwind inside it, take the = K size and then the innerwind inside it, take the = K size and then the innerwind inside it, take the oil size - give greater, give zero, then this will work for oil size - give greater, give zero, then this will work for oil size - give greater, give zero, then this will work for our level, so what will we do, first of all, remove our note, then tree. Note remove note = What will happen to our K note front and then from that we will do K our a removed note to us and now what we will do is start processing child from right you will do left so how are we going to do this and first of all we will see And here the left will come, then I will see if its child's right is a painter exit or not then I will see if the right of remove note exists and if it exists and in my set also it exists in remove mode. If the value of right of mode, left of right exists, first of all and in my set too, if the left right of remove mode exists, then reduce one and put it on the left of my remove note and this does not happen. If it is then process it well and how to process it well, we will write here that it is needed because it is giving value, so we run it once, then it is fine, run it once and see, we need value here. Okay, so now we will do this very well and then see what is actually happening in our code and why what is happening, so we opened our white board new page and added this code here. So this is our code from here to here and this I make small big and we are let here this small one example first small one is relief and this remove note of ours is relief and this root of ours is relief So what do we do? First of all, why did I push and we have this look and the wire look inside is the size, so what do we do? A goes to the remove node and then what do we do? Let's check whether my remove mode's write exit, then it doesn't write the write, then what we do is we insert into the set and in this we are inserting now 3, then why am I pushing remove? To the right of mode, that's why I went free now and then what we do is see if my remove node, which is one, exists to the left, so yes, left exists, camera remove node means right to the left of one. Yes, light also exists and is it right? Is this process already present in my set? Is this a note? Yes, there is a process note in my set. It is visible to me. So what do we do? We put it on the left of the remove node. So what happens next to you becomes null and then what do we do? We go out of this whole IF because ELSE has not run, this IF has run and then what do we do after that, this was our second. Okay, so this was for the first, so the next level goes on and again our size gets calculated, one and goes into remove mode, so it goes into remove mode There is nothing inside the set and Coming to D and K, the size of my K is zero. These two wires get eliminated and then what we do is we return our root which is the function in one and we can see this tree of ours right here. Which is mutated and we have removed our defective or quality note. So guys, you are getting an idea of ​​how the entire code is guys, you are getting an idea of ​​how the entire code is guys, you are getting an idea of ​​how the entire code is working. So this was a small example. Now we will take a slightly bigger example and see how it is. Ours is complete once again so why should I make it so late the first one is a little bigger okay and for now I am going to have a our second test how is it okay so it is going to be a little bigger it is going to be good test how so stay with me Stay tuned because this will give you a lot of clarity about the whole court and I have also taken half of this code, so let me reduce this code by one and bring it down to the bottom. Okay, I have brought the smaller one here, so first of all our one. When it goes out, here in the remove mode, we check whether the right of my 8 exits the right of the remove note, yes it does the right of my remove node exit, right of the right of my remove node exit, then reduce one but is that I am included in the set but it is not included in the set, so reduce one, okay, I reduce you, I insert in the set, the value to the right of remove mode, then the value to the right of remove mode 8. The value is one and then what do I do after that, why do I push the right side of the remove mode which is one, okay, then after that I see whether the left side of my 8 exits, yes it does and the camera. Then what happens after that So what happens So what happens So what happens now, it ends, those people are complete because the size is zero and then the outside size has to be calculated again, the caste is what you are, then what happens now? It goes out and what we do is we check if the right of my remove node exists yes my right of remove node exists which is four did I check the right of remove node exists so I reduce one and insert it in the set here and why I add it and then what we do from here and we go to A again like the next station and what happens in the next station is size zero be zero. This time goes to the last element of this level, which is field three, then what do we do? We check whether the right exits after noting my remove, so here the right of remove mode is not existing, so this IF does not run, then we check. Does the left of my remove node exist? Yes, the left of my remove node exists. Does it exist? Does the right of the left of my remove node exist? Yes, the right of seven also exists. Four and is it in the set? Yes, there are four in the set, so I reduce one by one, I put a tap on the left of my remove node, so there is a tap here, which means this entire power has been deleted and then what I do is I delete it completely and then After that, what do we do, let's go to process the four, brother, it also ends and here the new size is created, then we had added to the set but did not do anything, so now I have pushed and laid down, so now exercise is calculated. You are there and from here, then what happens now, only the level order driver goes away and these notes just get processed, nothing else happens, it was our processing that was catching our answer that when our three As for the process and the rest, the one which is going to run now is the Level Order Driver Cell only. If you have not seen the Level Order Tree further, then please watch the video of the Level Order Driver Cell already. There are many questions. We have seen it once. Take it, if you still want to see it, then it is okay, I am late after doing the level order driver sale complete, my tree is complete, but for now we will write the process here, okay, so what happens first, then four. A goes out, nothing special is going to happen in the next generation, then what does four do? He adds his left child here which is six and because the right of his left does not exist and the right of his left also does not exist. And it doesn't even do left or right, so it does n't do anything. Four just adds five here, adds it to the set and also pushes K, six and five here, nine, A goes here and then next. The station starts running, zero comes out, what does 99 do? Have you seen that it is okay, I do n't have any left or right child, so I will not do anything, I will leave from here, then it goes again, the size is recalculated, you and us. The brother inside looks like a channel, which goes out one and then six is ​​seen that okay, you are six is ​​seen that okay, you are six is ​​seen that okay, you are not my child, I myself will just come in remove mode and will come from here and then look at it brother, the next one would be the size. It is zero, every one goes to five and then 5 also, you have to say that it is okay, I am just a note which has no children, I will not reduce anything, if I leave from here then it becomes completely ours, complete level order driver sale and We send this ad to the entire I, which is our urine, this one where it comes here is three, here is one, here is nine, here is four, here is five and here is six and here I If it is null, then this is our complete understanding of how we were approaching this problem and how we were solving it. I hope you have found out what the problem is, its time complexity will be off N because we are running BFS level order driver. And its space complexity will be Max of N because we are also doing the notes in the set, so that's all for today. I hope you liked this video. Do you take any training with this video? So please tell me in the comments yourself, recreate all this algorithm, this entire dry iron and then go to the code and hit submit, so that's it for today, see you in the next video, cup coding and cup. driving
Correct a Binary Tree
thousand-separator
You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**. Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this invalid node **and every node underneath it** (minus the node it incorrectly points to)._ **Custom testing:** The test input is read as 3 lines: * `TreeNode root` * `int fromNode` (**not available to** `correctBinaryTree`) * `int toNode` (**not available to** `correctBinaryTree`) After the binary tree rooted at `root` is parsed, the `TreeNode` with value of `fromNode` will have its right child pointer pointing to the `TreeNode` with a value of `toNode`. Then, `root` is passed to `correctBinaryTree`. **Example 1:** **Input:** root = \[1,2,3\], fromNode = 2, toNode = 3 **Output:** \[1,null,3\] **Explanation:** The node with value 2 is invalid, so remove it. **Example 2:** **Input:** root = \[8,3,1,7,null,9,4,2,null,null,null,5,6\], fromNode = 7, toNode = 4 **Output:** \[8,3,1,null,null,9,4,null,null,5,6\] **Explanation:** The node with value 7 is invalid, so remove it and the node underneath it, node 2. **Constraints:** * The number of nodes in the tree is in the range `[3, 104]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `fromNode != toNode` * `fromNode` and `toNode` will exist in the tree and will be on the same depth. * `toNode` is to the **right** of `fromNode`. * `fromNode.right` is `null` in the initial tree from the test data.
Scan from the back of the integer and use dots to connect blocks with length 3 except the last block.
String
Easy
null
1,835
Hello friends, welcome to my channel, so today we will see the problem of equal list, you will see its demand seat, today before producing, if you subscribe to my channel, please like this video so that I can comment in question a particular, I will now Now now it has been given to our village that this duty of Sarva Samaj 1234 is done by pimps and others and in this question, first of all keep this thing in mind on the job question, so read it carefully and get all the information on it. You can extract the information. It is a big thing that even the seventh examples should be roasted very well. From the sample, you get many options, so always the West but now it is very much that you can compare the previous ones and more. Subscribe Thank You I am round element plate result What is the list of entertainment So what we have to do is that you give each element its element Subscribe and if it crosses then ours were into it So much so that we are in the room for a minute Maybe Congress needs this, here we number it first, then we have something like this in Shan Sunlight, now let's see that we can do this, in between, we note this, watch this video carefully that childhood If you think about it a little, Yogendra, it seems that even a President has been trained in antioxidants. If I put it simply, plz simple. All you need to complete is simple, if you have time then you have ordered it will have a side, so basically it can be made secondary in 460, so now we will have a solution to it, this is not a problem, this question is solved, to complete the question, you have to Now, what is the thing at this time that we have to show him that we are the complete questions to the interviewer in the interview. Also write that thing down and show it to the interviewer. If you subscribe to someone then do not forget to subscribe. Friends, see you. If you are troubled by torch and our answer free forum, then how much will your complexity go and cancel your order through Mintu or Cooperative Bank Vriksha here. But St. I have no list Remedy Francisco keep storing our space cooperative development unit electricity conference place complexity will be there but now tell the interviewer that I will give a little more benefit in this you tell him like before that here you see here, well you three things If you want to end with, then the first option in your homes is to subscribe to this thing that whatever you do and do it directly with Exorbis and C, play it with Bryan Adams and along with this, now tell this to the school or office that you are the mother's one. Please tell me, first one thing, I mean, I started playing the previous song upwards again, so that you first started taking out the entire song and if I go, then to fry the chakli, the one below which is our school of mines lobby mode is off, so there is fire in it. By the way, whenever you keep taking out the same thing, we give us a rough estimate of how much time it will take, so we do this so that if you can watch this video, it is very important because if you If there is anything, then you are also focused on it, then if you explain the method of interview, then okay, I have told him a little about it, if I can't do it, then you will tell that I club everywhere and if not, then you can explain it to him. By going to the last, you will tell me your completely police method that this is how you can get rid of lip gas. If the last can support you in calling you and doing anything for a full time, then it is up to you to know how you can revise it. The second question would be thinking that you will know something by now you know that you can answer this question a little bit, Nice West is a question, why will I try to take out my time for it, there is not enough time in the interview, not the whole day, we will see you that He also has the time increase, if he has to do the interview there for so long, then connect with him, if you are a good change, you will get me to report in such questions. Here, if you are positive about the job interview, then to complete it completely, then whatever questions you do. If you have any problem, then I have given this link in the description box below, so that you can save their oath, mark etc., can save their oath, mark etc., can save their oath, mark etc., then today's heaps are so afraid that it is coding.
Find XOR Sum of All Pairs Bitwise AND
decode-xored-permutation
The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. * For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers. Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`. Return _the **XOR sum** of the aforementioned list_. **Example 1:** **Input:** arr1 = \[1,2,3\], arr2 = \[6,5\] **Output:** 0 **Explanation:** The list = \[1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5\] = \[0,1,2,0,2,1\]. The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0. **Example 2:** **Input:** arr1 = \[12\], arr2 = \[4\] **Output:** 4 **Explanation:** The list = \[12 AND 4\] = \[4\]. The XOR sum = 4. **Constraints:** * `1 <= arr1.length, arr2.length <= 105` * `0 <= arr1[i], arr2[j] <= 109`
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
Array,Bit Manipulation
Medium
null
234
hey there welcome back to my channel before we start please don't forget to hit that subscribe button if you want to see more coding interviews questions so in this video we'll be discussing and solving the problem palindrome Link at list so let's get started the question is that they give us a single linked list where each node has a value and next pointer and the task here is to return true if it's a palindrome or false otherwise so what do we mean by a singly linked list palindrome a palindrome linked list is a sequence of nodes that read the same forward as a backward so the first and the easy way to determine if the input linked list is a palindrome is by using a stack for example let's say we have this input linked list the algorithm that we're gonna Implement is that we're gonna start by traversing the from the left to right and at each step we push the current node to the stack so since the stack follows the lethal last and first out there are structures the last element added to the stack will be the last node in the linked list after that we'll start on comparing notes from the head of the linked list and the top elements of the stack so once the stack is empty or the linked lists become null there is no more comparison so we'll return a valid point drum linked list which means true otherwise we'll return false meaning that the given palindrome is false so the problem with this solution is that we are using an extra space by using the stack data structure which takes space proportional to the input size this means a linear space complexity and also a Time complexity of all fan so the second way to solve this problem is by using recursion so the recursive function used something called the call stack when a program calls a function that function goes on top of the call stack so this is similar to the stack of books we add things one at a time then when you are ready to take something off you always take off the top item so let's say we have this input linked list so we're going to take advantage of the recursion stack of the compiler and compile the first node with the last node and the second node with the second last note and so on so at any points in time where the comparison return false the results will be false meaning the linked list is not a palindrome so otherwise if all the comparison return true we get a result true meaning it's a valid point drum linked list so we start by looping over the linked list from the start to the end so once we reach the end of the linked list we'll have two pointers the left punchers at the start of the linked list and the right pointer at the end of the linked list then we compile the value of the two punchers if both have the same value were turned through as a result for the last call in the stack and we move the left pointer to the next node so for the right pointer the recursive call will take care of it by moving it to the previous node and we will repeat the same process by comparing the two values of the two pointers so if all the recursive call return true the result will be a valid palindrome otherwise it is not a palindrome linked list so in order to solve this problem using recursion we're gonna start by initializing a dummy node that will keep track of the left pointer of the link less during their recursive call then we need to define a recursive function that is going to do all the work and return to us the result as true or false so the recursive function gonna start by calling itself with the head of the linked list and it's because we are not at the end of the linked list the recursive function will move to the next node and call itself again so the function will keep calling itself again and again until we reach the end of the linked list so once we reach the end of the linked list the function gonna stop calling itself and as a result we will have two pointers one at the left of the linked list and one at the right of the linked list so the second step is going to be the comparison between the two pointers so we're going to start by comparing the two pointers and return the result to the function call that we have done before and each time we return the result to the function call the right points are gonna move automatically to the previous node and the left sponsor gonna move to the next node so if all the comparison between the two pointers return true that means we have a valid panel drum linked list and if only one call gets a false also result the result of the main function call will be false so the time complexity for this solution is often because we are traversing the linked list from the head to the end so and present the number of notes in the linked list while the space complexity is often because we are using recursion and as I say during the explanation the recursion use a call stack and at every call is Rick it's create a new frame means another space and the stack so the question is how we can solve this problem without using extra space and memory and only using constant space memory so the third solution going to be by using the two pointers technique and the linked list has a special two-pointers method where we call it the two-pointers method where we call it the two-pointers method where we call it the slow and faster pointers so the slow pointer move ones that mean in one node and the fast pointer move two steps meaning two nodes and the idea here is that by the time the fast pointer reach the end of the linked list the slow Point you're going to be at the middle of the linked list and then we're gonna apply the reverse linked list and if you have not watch watched my previous video about the reversing Link at list make sure you watch it before we continue this video so that you can understand how we can reverse the link at list so as I say once the slow point to reached the middle we're gonna reverse the second half of the linked list then we'll start comparing from the head of the second half and the head of the first star so if both the harvests are exactly the same then the linked list will be a palindrome otherwise we'll return false so the time complexity for solution is often because we are traversing the linked list only once and the space complexity is off one since we are not using an extra space memory only using constant space meaning we are using only pointers that's it guys so let's jump at code in the solution so the first solution will be by using stack their structure so we start by initializing an empty stack to store the values of the node of the linked list then we initialize a variable called current and set his value to be the head of the linked list after they will Loop over the link it lists used in a while loop so this Loop gonna keep running until we reach the end of the linked list and at each iteration we will push the value of the current node onto the stack and then update the current variable to be the next node so once we have added all the node to the stack we're going to reset the current variable to the head of the linked list again after that we're going to Loop another time over the linked list but the difference is that at each iteration will pop from the stack the last value of the node and compare it to the value of the current node so if the both values are not the same we'll return false otherwise will turn true indicating that the link at less is a palindrome so the second solution will be by using recursion so we start by creating a dummy node and set his value to be zero and set his next pointer to the head of the link at list so that we keep track of the left pointer and the linked list then we Define a recursive whole per function that takes as argument the length list node as the input and return a Boolean value indicating whether the linked list is a palindrome or not so we start by setting the base case of the recursive function if the head is non-minion we reach at the end of the non-minion we reach at the end of the non-minion we reach at the end of the linked list where turn true means it's a pattern drop so during the recursive steps we're going to call the recursive function on the next node and the linked list and store the result in the right variable which represent the right pointer then we move the left pointer to the next node and the linked list so after that we check if the current node value is the same as the node value from the right pointer if they are not equal the linked list is not the palindrome so we return false otherwise if the linked list is a palindrome up to this point we return True by chicken that the right is true and also the current node value is the same as the node value from the right end is the same as the node value from the right puncher of the linked list finally we call the recursive helper function of the input linked list and return the result so for the third solution and the optimal solution which have a constant space complexity we start by checking if the linked list is empty features were turned through because an empty linked list is considered to be a palindrome then we start searching for the middle of the linked list with the help of the slow and fast puncher technique so I initialize a slow and fast variable and point both them to the head of the linked list so the slow point to remove one step and the fast pointer move two steps once the faster reach the end of the linked list we then reverse the second half of the linked list by iterating throughout the second half of the linked list starting from the middle node slow and we use a variable called previous R which are the pointer to keep track of the Reversed nodes then we'll assign his value to be known because the last node of the Reversed list should be in point to none then we reverse the second half of the linked list by using a while loop then we set the current variable to be the slow variable and move the slow to the next node after that we set the current node next to the previous variable so that we can reverse the direction of the pointer and finally we set the previous variable to be the current variable so that we can keep track of the Reversed node so once the loop finishes the previous variable gonna be pointing at the head of the Reversed linked list which is the second half so once we reverse the linked list we'll start comparing the first half with the second half if one of the value are not the same we return false otherwise if we reach the end of the linked list without finding any difference between them were returned true because the linked list is a palindrome that's it guys thanks for watching see you in the next video
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
1,903
hi my name is david today we're going to do number 1903 largest odd number in string so we're giving a string num and it represents a large integer so in this example the num is 52 as a string and it represents the number d2 return the largest valued odd integer as a string that is a non-empty substring string that is a non-empty substring string that is a non-empty substring so here we have a string 52 we've returned a string of five because a non-empty substrings are so we can a non-empty substrings are so we can a non-empty substrings are so we can look at the substrings of 5 and 2 and 52 and the largest odd integer that we have is 5 because 5 is the only one and it's the largest so that is what we return if there is none odd numbers in this example we just return an empty string so there's no odd digits in here and in this one this is already the largest odd number so we return the large number so the trick here is that we have to look at this as a number not as a string so we can tell if it's odd or not also if you want the largest one we can just look at so if we just look at um we just remove we look at the entire digit and not we just delete the last sub uh last index of it and look at here and then we keep going until we get to the end so the trick here is that we have to see if it's odd or not and we can only we can just do that by looking only at the last index not at the entire number and then see if that last index is odd if it is odd we return as is and then if it's not on we keep looping back until we find something that is odd and that is what we term that will give us the largest one so we can loop through this number backwards so we can look at the last index so loop and then so that's the first step and then inside of it we check if the current num is odd and then if it is we know we found what we needed because we're looking from backwards return num dot slice so we're gonna have to use the slice one from the beginning until that last index and slice doesn't include that last index so we have to add one to it so that it's i plus one and then if we don't hit this return we just return an empty string great and the way we check this is that we can mod it by two we have the parasitic string and then first to n and then mod two to see if it's has a it doesn't equal to two okay so first we loop you know so for that i equal num dot minus one i is greater than or equal to zero i minus and now we check the coin num so if num index i and then we have to parse it into it so we can use the shorthand syntax mod 2 does not equal to 0 return num dot spice zero i plus one and then if it doesn't hit this return just return the empty string great we got it so this is a pretty efficient way of solving it because at first i always say i was uh slicing off by popping off the last integer of the string each time and as if we do create a new string it's o of n squared space and then i was also trying to convert it into an integer and then uh divided by 10 to get the last one and so forth but then like large numbers was throwing me off at me problems and it was giving me a and then i tried using big n as type but this is a pretty clever way of solving it so we just loop backwards of it and then check if the last index is odd or not if it is we just return um where we at we slow high stat num to where is that if it doesn't we just return an empty string so the time complexity since we're doing a loop here it's going to be o of n where n is f of n and then the space complexity it will also be oven because we're creating a new string here that's how you solve this problem thank you so much
Largest Odd Number in String
design-most-recently-used-queue
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** num = "52 " **Output:** "5 " **Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number. **Example 2:** **Input:** num = "4206 " **Output:** " " **Explanation:** There are no odd numbers in "4206 ". **Example 3:** **Input:** num = "35427 " **Output:** "35427 " **Explanation:** "35427 " is already an odd number. **Constraints:** * `1 <= num.length <= 105` * `num` only consists of digits and does not contain any leading zeros.
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
Medium
146
328
hello guys my name is lazer and today we'll be doing a lead code problem this problem is called odd even linked list given the head of a singly linked list group all the nodes with odd indices together followed by the nodes with even indices and return the reordered list so already we need to we know that we need to keep track of the indices of every node we see the first node is considered odd and the second node is even and so on so this is pretty obvious uh first one it has in this index of one and it's obviously odd the second one is gonna have an index of two so that's gonna be even this also tells us that we want to start counting at one and not at zero because if we start counting at zero then the first node would be even but due to this sentence we know we have to start counting on one note that the relative order inside both the even and odd groups should remain as is as it was in the input so for example in this first example the correct answer is one three five two four what this sentence is telling us that is we cannot return a linked list that is one five three four two because in the beginning it was two followed by four so we cannot return linked list for the even section is four two we need to maintain the relative order and then finally we want to solve the problem with all one extra space complexity and of and time complexity so here in the first example we have 1 2 three four and five now the odds are gonna be one three and five so let's put them in the first half of our answer linked list and then the evens let's put it in the second half which is why we have one three five and then 2 4. same thing goes for example too here you can see that the first node the value of the nodes doesn't really correspond with the index position so we are going to want to have an a separate variable keeping track of that so here we have two three six and seven those are all the odds so they go in the first half and then the one five and four go in the second half so let's get right into the drawing to see what we really need to solve this question so i'm gonna write down the first example so we have one two three four and then five so the first thing we want to do is keep track of the proper heads so for example we know that the first node is the beginning of the odd so let's just call that odd start if i can write this nicely there we go and we know that next node is going to be the beginning of the even now from here we want to do some rearrange some rearranging so we really want to be changing these pointers so for example let's say we're currently looking at one we want to hold in a temporary variable the next uh the next node the one points to and then we want to change the pointer of one to point to next dot next in this case three now when we're iterating uh we're going to be moving to two since we held this temporary variable let's now move to it and let me get rid of that box so now we're at 2 and we're going to want to do something extremely similar we're going to want to change the pointer of two for of course first we're gonna have to hold uh its next node separately but i'm not gonna be drawing that box the whole time so just keep in mind that we're always storing its next node before we change it but after we store it we do want to change what it points to we want to look at next dot next in this case it's four now we move to three and we want to do something similar point it to five next start next and once we get to four we are pretty much done here and the reason we're done is because although we do have two point four to no to none we can just stop here and rearrange what 4 is supposed to point at and also what 5 is supposed to point at so since 4 is an even node i'm gonna mark all the events right here uh i'll do it's weird there we go okay right there and all the odds are doing yellow right here perfect now since 4 is an even node what we want to do is first change its pointer make it look to nothing make it point to none and then this five well before we made the change of to none we first had to get this five and let's have this five point to the beginning of even start so point to whatever even start is in this case i used to a big arrow like this that way when we were to return this list we're going to be returning odd start so we're going to have 1 points to 3 we're following this arrow right here 3 points to 5. and then five since it was the last node and that was an odd node it's going to look at the even at the first even node which is why we have to keep track at the of that even start node so now five is going to point to two then two is gonna point to four and this is the correct answer now you might be asking yourself okay well that makes perfect sense but what if we didn't fall in that scenario right oh i'm losing all my dots that's unfortunate let's say there was a six here we could change this four make it look to the six and now we stop at this five but now we know this five is odd is an odd number we know the six is already pointing to no which that's already correct since it's an even it's the last even we want that so we don't really have to change much all we really have to change is a pointer of this five and just make sure it looks at even start so instead of changing two pointers if we had finish on an even node if remember when we finish on the four we have to make sure four looked at none and then five looked at even start but if we finish on an odd node all we have to change is the pointer of that node so it's just one change instead of two now we were to return this we'll be getting one points to three points to five points to two points to four and then four points to six and of course six points to nothing and this is also the correct answer and that's all we really have to do for this problem now how though we can keep track of knowing whether the last number on is even odd by using that outside variable that i talked about in the beginning we can call it uh position or pos for position and let's just set the equal to one in the beginning and if next dot next is none we know we have to do this operation where and we have to look at what pos is so let's get right into the program and see if we can write this up all right perfect so the root is be equal to head and then even start is equal to head dot next now this right here might throw an error because if we look at the number of nodes in the linked list it is possible for the number of nodes to be zero so it's possible for us to get an empty linked list so for this to not throw us an error we can just do a simple check in the beginning if not head return none so there we go and now everything's fine now let's create that pos standing for position variable and now let's do our while loop so we can iterate through the linked list now while head and head dot next now why do we want to make sure that head dot next is valid well it's because we're going to be doing head dot next and if head was equal to none then head dot next i'm sorry if head was equal to one and then one points to none then head dot next would throw an error because none does not have an attribute uh cut next so we're just making sure we're not falling into any errors in this while loop by having that as that's the condition now we want to temporarily store the actual next node yes how we did in the drawing and now we want to do some computation so if not temp dot next now keep in mind this temp dot next is the exact same thing as head dot next so if not this then we know we're in one of these scenarios where we're on this node and there's nothing after so if that's the case we want to look at what a precision is if a position is even then let's change temp dot next it makes that equal to even start and then also make head.next equal to and then also make head.next equal to and then also make head.next equal to none now what is this saying well this is saying uh the original problem we had let me see if we can go back there we go uh head is currently right here temp is currently right here and then temp dot next is pointing at nothing so if not temp dot next and our position is even in this case it is position here before then temp dot next is equal to even dot start there we go so temp dot next is this temp is five and dot next change that point to instead of looking at nothing change that pointer and make it look to the start of even and then head dot next is equal to none because since this is head we want to remove this pointer that makes a point at five and let's just point it to none perfect else if this is not the case then we find the scenario how we had that we had when we had the six in there where head.next where head.next where head.next is equal to even start and we only have to change one thing now if we did fall inside of this condition then we know we're basically done with our while loop and we can just go ahead and break else if that condition did not run then we want to do is just continue iterating normally and by normally i mean just make it make the next pointer point to the next so that what that is saying right here is how we have right here remember we don't we want to change the point serve from instead of going to the next node to go to the next so we're doing this right there that operation and then finally we want to continue iterating normally so head is equal to temp and then let's increment our precision variable as well and then finally we can use return root so let's run this make sure it works it does let's submit it gets accepted perfect so hopefully you guys were able to uh to understand this problem now and just to make sure that it has this complexity we don't have any data structure where the size of that data structure increases depending on our input so where we did meet this all once extra space requirement and we also have the of end time complexity because we just have one while loop that's gonna be iterating over the linked list once so again hopefully this helped and if it did please leave a like and consider subscribing and thank you guys for watching
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
1,893
E agri one my name is sandeep and in this video you will show you how to solve there problem 18938 one day officer must subscribe and stands for example sentence subscribe must subscribe and stands for example sentence enter start and end that from last days do camp's one left and right 0.5 inch subscribe and right 0.5 inch subscribe and right 0.5 inch subscribe and subscribe the Channel Please subscribe this Video Subscribe button set to maximum The snake example content rangers widens 20 ki and left festival advance right so let's check if all the best android classification is not quite hindered so and does not Give one right subscribe how to right now they are giving these are very strange affairs in trouble and window contents of start and end speed for what we can do per middle value from being from the start end and they can implement all the position a different festival subscribe to subscribe our 120 days that are in you so let's fight way to good position and comment it tomorrow morning office interview snow-covered what tomorrow morning office interview snow-covered what tomorrow morning office interview snow-covered what is the national development ministry of and inverter possible the person who should take himself security three this position body one 500 FROM 1000 COVERED IT'S 21.57 SOFT 500 FROM 1000 COVERED IT'S 21.57 SOFT 500 FROM 1000 COVERED IT'S 21.57 SOFT POSSIBLY INVALID AND 5676 FROM LEFT SIDE NOT SUBSCRIBED TO 3 MINUTES Shravan Vidra From The Phone Ka Note Or Ko Doctor Intervals Let's Check Par Lattu Right Requesting You To Tree Them All The You Like To Right And Check Positive Values Have recovered that both of them are rangers possible you here two three four three 500 trains from left to right it's to subscribe button more 63 subscribe and subscribe the Channel again for land acquisition from 4th September 2010 subscribe and subscribe the Channel total Time and date a plus adds and begin from left to right so we have range of world record right - left election report complexities right - left election report complexities right - left election report complexities for pun big boss 10 minutes can do and jewelery - one who will have jewelery - one who will have jewelery - one who will have sister times and minus one witch porn lottery complexities on son2g And take a code to slow down decode minute Udayveer and now scandal next nine and a half subscribe to the channel subscribe to subscribe that here 10 minutes correct and comment why not tractor thank you for watching subscribe few lines problem definition thank you that such a witch content left and right a the start and a
Check if All the Integers in a Range Are Covered
maximum-subarray-sum-after-one-operation
You are given a 2D integer array `ranges` and two integers `left` and `right`. Each `ranges[i] = [starti, endi]` represents an **inclusive** interval between `starti` and `endi`. Return `true` _if each integer in the inclusive range_ `[left, right]` _is covered by **at least one** interval in_ `ranges`. Return `false` _otherwise_. An integer `x` is covered by an interval `ranges[i] = [starti, endi]` if `starti <= x <= endi`. **Example 1:** **Input:** ranges = \[\[1,2\],\[3,4\],\[5,6\]\], left = 2, right = 5 **Output:** true **Explanation:** Every integer between 2 and 5 is covered: - 2 is covered by the first range. - 3 and 4 are covered by the second range. - 5 is covered by the third range. **Example 2:** **Input:** ranges = \[\[1,10\],\[10,20\]\], left = 21, right = 21 **Output:** false **Explanation:** 21 is not covered by any range. **Constraints:** * `1 <= ranges.length <= 50` * `1 <= starti <= endi <= 50` * `1 <= left <= right <= 50`
Think about dynamic programming Define an array dp[nums.length][2], where dp[i][0] is the max subarray sum including nums[i] and without squaring any element. dp[i][1] is the max subarray sum including nums[i] and having only one element squared.
Array,Dynamic Programming
Medium
53
47
hello everybody this is mustafi from zakucho and today we are going to solve another backtracking problem from lead code um this problem is uh number 47. um it's pretty similar to 46 that we already solved together and really recommend you to check 46 first and then come to solve this one so this problem statement is that you have an array and you need to get all unique permutation for from this array and also this array may contain a duplicate number this is the difference between this one and the previous one 46 i mean and it doesn't have a duplicate numbers and this is really the difference so how we should start or how we should solve this one um it's a um as we solve with the previous one we like here we had different permutation and we do all the possible permutation and puts them into the result this one we need just to refine or um uh yeah to refine our solution and make sure we don't have any duplicates in our result array so that's basically it and how we should to avoid public duplicate solutions we will do some constraints that prevent our code or our solutions that enter the duplicates bosses or duplicate arrays because as you see here this is a normal permutation and if we started the normal permutation we will have a lot of duplicate solution like here one two and we also have uh one two one here and also actually it's this we should only have the solution here one two and one two one and this is uh should be our solution so let's see how we showed um both our constraint to prevent the code from getting this duplicate results so first thing i want to do is to sort the array uh the given array here so let's sort it first and we'll let you know why we will sort it so we have um sorted by yeah i think uh a sec and that's it that will um sort our array and then we need as we did the uh in the previous uh problem we need to define two arrays one for zero one for uh for the result and one for a pause and another one for the visited index indices so we cannot enter and this is that we already entered before and we need to do the recursion and do a recursive function called defense and then we need to run this recursion and then and at the end we need to return the result okay uh yeah and let's define our recursive function it will take no arguments at all and we need to define our base case first so our best case it's pretty similar as the last one is as a previous problem we need to check if the path length is equal to the given radiance and if so we need to written as to which the current post to the result array push path here and then we return to exit from this yeah i think i have a type here should be dance th http yeah and after that uh we need to uh to do the to do symbol for loop let's y equals zero and i is less than num length yeah length and i need to be incremented and yeah let's um let's do our backtracking blueprint first and then get to the constraints that we don't our code to enter this backtracking if this condition is fulfilled okay so first thing let's apply the backtracking blueprints do recurse and on no so the do or picking the element from the pass is that we need to push this element to the pass so we will push numbers of i to the current pass and we also need to mark this index to be uh visited yeah so need to mention that this uh this element is already visited or this index is already visited and in their case we need just to query the same function again and to undo it we need to pop this from the bus and we need to provide also from the visited array and that's it for the occasion yeah and for preventing the uh for preventing the um yeah for preventing the duplication or duplicated process we need to write this uh this small condition it's a it's not that small but here this condition should be if we already visited this index we should uh we shouldn't enter this loop or we should continue and ignore this um this current index so if it's included in a visited we should ignore it or that one and another one if this index is already yeah if it index larger than zero and this index of numbers equal the previous index or equal equals the previous element minus one and the previous element is already visited we should also not enter this pose and to continue and continue without it okay so we have two conditions here um yeah so if this index is already visited we should ignore it and if this index equals the previous actually if this element equals the previous element and the if previous element is already visited we should ignore it and because it's already visited and we should open it and continue to see another solution so this condition actually will help us to avoid the duplication and we only will go through cis pos here one when this is index of one and this is index of zero and this is index of two so we will go through this and after this we will go through this and the same here we will go through index number two and in index number uh one and index number zero so this all this process only we will go through it and other bosses will be avoided and we will avoid that application here so that's basically it let's run the code and see how i was gonna work hopefully we don't have any yeah i'm just we don't have any uh typos yes it should be a we have another table yeah chopinos i have a lot of yeah should be numbs every way everywhere yeah here in arms here numbs and here norms doesn't let's run the code again why we have an issue here uh if we visited i think it's wrong yeah let's type in the visited array i have a lot of times i need to fix this includes also copying clones yep hopefully this is gonna work it's the same time here and same time here yeah it's working fine let's submit it and see if it's gonna yeah it's working fine and we have um not the best uh submission and yeah that's it uh hopefully you guys you enjoyed if you have any questions let me know in the description in the comments section below that's it see you later thank you
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
1,897
hey everybody this is larry this is me going with q1 of the weekly contest 245 uh redistribute characters to make all strings equal so this was actually kind of tricky to um for a yeezy problem uh so hit the like button hit the subscribe button join me on discord let me know what you think about this forum because i thought this was kind of tricky for easy uh you have to make one observation which is that if every string in words is equal then every string has the same number of every character so with that in mind um you know that means that given n is the number of words and number of words in this list that means that everyone every character has to appear either end times or two times n times or three times n times dot so multiple of n because that's the only way you get each of them having one character or two characters and so forth um so that's basically the idea and then you just once you make that observation then you just count all the characters um yeah and that's basically what i did for each word i for each character in each word i put it into a count uh a you know basically a hash table with the number of count and then at the end i just check out each key to make sure that it is a multiple of n um so this is you know in terms of space this actually only holds at most 26 characters because it's lowercase so it's of one maybe or a or if alpha if you want to go you know for the number of alphabets uh characters in alphabet uh here this is linear time in the in this number of characters because for every character we do a lookup table um and here it is all over also of alpha in that it has as much as 26 in the loop so the total time it's going to be of n one for each character of every word combined and in terms of space it's going to be o one of alpha where alpha is the number of alphabets which in this case is 26. um that's what i have with this one you can watch me solve it live during the contest next um let's see okay go hmm emily hmm hey uh yeah thanks for watching hit the like button hit the subscribe button if you like it join the uh join the discord uh to talk about this on other problems so i usually go over uh me and my channel my discord channel talk about problems after the contest like right afterwards so come hang out and share ideas and love and learning and all that stuff i'll see you later um have a great week hope you had a good contest and stay cool bye
Redistribute Characters to Make All Strings Equal
maximize-palindrome-length-from-subsequences
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. **Example 1:** **Input:** words = \[ "abc ", "aabc ", "bc "\] **Output:** true **Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ". All the strings are now equal to "abc ", so return `true`. **Example 2:** **Input:** words = \[ "ab ", "a "\] **Output:** false **Explanation:** It is impossible to make all the strings equal using the operation. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
String,Dynamic Programming
Hard
516
333
Hello friends my name is tar and today I'm going to discuss the question largest binary surch tree in a binary tree what is binary search tree is a binary tree with additional constraint that everything on the left sub tree is less than or equal to root and everything on the right sub tree is greater than root and this is recursively true for every node so here we are looking for the largest binary search tree in this binary tree so for example here this is a binary search tree and it size is three while this here is not a binary search tree so we have to find the largest binary search tree in this tree this can be done in two ways one is uh going from top to bottom so in that approach what we do is we find is the tree with this guy a root a binary tree or not so in another video I've already discussed that algorithm how to find a BST with a given for given binary tree so for 25 20 is less than 25 but is on but it is on the right side of 25 so this tree with this 25 as a root is not a binary Source tree so then we fan out on left side and right side and try to find the largest Binet sry so for 18 19 is uh greater than 18 but it is on the left side so this sub tree is also not a binary search tree so similarly we keep going left and right the problem with this approach is it takes o of n² time to find the largest binary search tree we are going to use a post order traversal to find the largest Min searry in O and time so what post AIT traversal is we visit everything on the left side we visit everything on the right side and then we'll use that information to find the largest bstd so let's find the largest bstd for this B let's do a post order reversal on this stream so we start from 25 we go to 18 we go to 19 and then we reach 15 remember post order traval is left right and then visit so at 15 returns uh those four values to 19 with true 1 15 so what this means is that sub tree with 15 as its root is a binary search tree which is why it's returning true the one is the size of that binary search tree 15 is the minimum value in this sub tree and 15 is also the maximum value on the sub tree so 19 gets a true from its right side so what 19 is going to verify is with 19 included is it still a binary resarch tree so for that to happen the minimum on the right side which is 15 should be greater than the value at the root which is 19 is not is uh is greater than 15 so 15 is not greater than 19 so n with 19 included this is not a binary search tree so 19 returns false the size of the binary search tree it found in here so that's one uh and it doesn't matter what it returns for men or Max because your binary Searcher is it's not a binary Searcher anymore so it doesn't matter what you return for Max or men or Max so 18 goes to 20 goes to 18 so what this 18 returns to 20 is uh true 1 18 Again with 18 as a root of a binary searry it is a binary search Tre the size of that binary search Tre is one minimum is 18 and maximum is 18 and this piece of information is return to 20 what 25 returns is true 1 25 so 20 gets true from both its left and right so it means that both its left and right sub trees are binary search Tre only thing now 20 needs to verify is that including only thing 20 needs to verify is that including 20 is it still continue to be a binary sey so for that the minimum of the right side should be greater than 20 so the minimum of the right side is 25 so that's greater than 20 so that's good and the maximum on the left sub threee which is 18 should be less than or equal to 20 which is also again true so this three here continue to be a binary surar tree so what 20 is going to return to 18 is true saying that this sub tree is a binary sub tree the size is size of the left side plus size of the right side plus one so that's three and then the minimum of the entire binary SE three the minimum of entire binary search three is the minimum of the left side so that's 18 and then the maximum of the entire binary Tre maximum of the binary entire binary Tre is a Max of the right side so that's 25 so this 18 gets a false from here and true from here so it means that with a sub tree with 18 as its root cannot be a binary search tree because one side is not a binary search tree so what 18 will do is just return the Max of the size from either left or right so that's three so what 18 returns to 25 is false saying that sub3 with 18 as its root is not a binary Sur Tre but it has found a binary Sur Tre of size three so it returns three and then minimum and maximum doesn't matter so then 25 goes to 50 goes to 35 goes to 20 and 20 goes to 25 so what this 25 again returns is true 1 25 to 20 so what 20 checks is the so what 20 gets is true from its right side so only thing it checks is the uh minim it's is the minimum on the right side which is 25 greater than 20 it is so it means that including 20 this is still a binary search tree so what it returns to 35 is true size is 1 + 1 so that's true 35 is true size is 1 + 1 so that's true 35 is true size is 1 + 1 so that's true two and then the minimum of the left minimum of this sub tree which is 20 and then the max of this sub tree Max of this sub tree is the max of the right side so that's 25 so this piece this four piece of information is returned by 20 to 35 and then 40 returns to 35 is true 1 40 it's a binary search tree size is 1 minimum is 40 and maximum is 40 so 35 gets true from left true from right so it knows that it's left and right sub three at binary sear three all needs to verify is including 35 does it still continue to be a binor Terry so for that to happen the max of the left side which is 25 should be less than equal to 35 which is true and the Min on the right side which is 40 should be greater than 35 which is also true so with 35 it continues to be a binary sear tree so what 35 returns to 50 is true yes this sub tree is binary sear tree the maximum size is the size of left 2 + 1 3 plus this one so four and then the + 1 3 plus this one so four and then the + 1 3 plus this one so four and then the minimum of this sub tree is um is the minimum of the left side which is 20 and maximum of this sub Tre is maximum of the right side which is 40 so 35 returns these four piece of information to 50 then 50 goes to 60 goes to 55 so 55 returns true 1 55 and then 70 returns true 1 70 and then 60 verifies similarly verifies that it's left and right sub tree are binary Source tree and 60 is greater than the max of left and 60 is less than the Min of right so this is continues to be a Min Cy so 60 returns true size is 1+ 1+ Min Cy so 60 returns true size is 1+ 1+ Min Cy so 60 returns true size is 1+ 1+ 1 so that's three uh minimum of the entire sub which is 55 and Max of the entire sub which is 70 so 55 gets this from the 50 gets this from the left side and this from the right side so what 50 does is it knows that its left sub tree is binary search Tre Its Right sub Tre is binary search Tre and then 50 is greater than the max of the left side and 50 is less than the Min of the right side so it is also a binary search tree in with including 50 so what 50 returns to 25 is true and then 3 + 4 7 + 1 true and then 3 + 4 7 + 1 true and then 3 + 4 7 + 1 8 and then the Min of the left side which is 20 and the max of the entire sube which is 70 so this piece of information is return to 25 so 25 gets a false from this side true from this side so what it knows is that with this sub tree with a tree with 25 as a root cannot be a binary search tree because 1/2 is not a binary search tree because 1/2 is not a binary search tree because 1/2 is not a b search tree so what all it does is Returns the max of whatever it got from left or right so that is eight so eight is returned to the calling function so eight is the size of a maximum largest binary search Tre in this binary tree and that is this one 1 2 3 4 5 6 7 and 8 again the runtime complexity for this algorithm is O of n all we did is a post order traversal going from bottom to up and keep propagating this information up to the till the root and then root just return the maximum size sub tree the link to the code is in the description section of the video again I ask my viewers to help me improve my G GitHub repository by contributing to it the link to the repository is link to the repository is link to the repository is Mission piece interview Wiki and also you could uh subscribe to my YouTube channel user Toro 2525 channel user Toro 2525 channel user Toro 2525 thanks for watching this video
Largest BST Subtree
largest-bst-subtree
Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes. A **Binary Search Tree (BST)** is a tree in which all the nodes follow the below-mentioned properties: * The left subtree values are less than the value of their parent (root) node's value. * The right subtree values are greater than the value of their parent (root) node's value. **Note:** A subtree must include all of its descendants. **Example 1:** **Input:** root = \[10,5,15,1,8,null,7\] **Output:** 3 **Explanation:** The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3. **Example 2:** **Input:** root = \[4,2,7,2,3,5,null,2,null,null,null,null,null,1\] **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` **Follow up:** Can you figure out ways to solve it with `O(n)` time complexity?
You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.
Dynamic Programming,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
142
one so today we are looking at lead code number 142 this is a sequel to linked list cycle it's the second one link list cycle number two and this is uh somewhat similar to a regular linked list cycle except this one we want to find out where it is starting okay so let's take a look at the prompt here given a linked list return the node where the cycle begins if there is no cycle then we return null so we can see here that we have three two zero minus four and we want to return this two node here because that is where the cycle is beginning so if we have three two minus one position one so we're going to bring it will be the index of where the cycle begins here we have one and two the position is going to be zero and then here we have one there's no cycle so we return nothing okay so how do we approach this we know how to get a regular cycle we want to use two pointers let's jump over here to the conceptual if we have a regular linked list let's say we have a link list of one two three four five six and then we have a cycle here at four what we can do is we can use two pointers so we can have a fast pointer and a slow pointer and every time the fast pointer increments it'll increment by two and the slow pointer will increment by one so we can see here so if we increment fast by two fast will be here slow will be here fast we'll go to six and then it'll go back to four and then slow will come over here to four now normally that is that in here it worked out that the cycle that fast and slow both landed where the cycle begins but normally we can't really um predict that it could land somewhere else inside of the cycle but not where it begins so how we want to do this is once we know where the cycle is meeting okay let me actually use a different example here because i think it will make more sense let's say we have node 1 2 3 4 5 6 we can do seven eight and then we're coming here to four okay let's say we have something that looks like that and then let's just go and look at this fast and slow pointer method here we have fast and here we have slow fast is going to move 2 slow is going to move 1. fast is going to move 2. slow is going to move one you can see right here they did not meet where the cycle starts okay but we'll keep going uh fast is going to move two it'll jump here slow will be here fast will again move two and then slow will jump here and you can see that this is where they actually meet so it's not at the beginning of the cycle we want to return this node right here the index of that node right there so how do we do that well what we can do at this point and let me just clear this out um again and we'll just remember that the fast and slow met at node six okay so we can remember that's where the fast and slow point are both aligned to let us know there is a cycle so now how do we get this node 4 how do we know when to get that well if we start another pointer here okay we'll just call this pointer and we don't need fast anymore we're just looking at slow we have pointers start from the start of the list and then we keep on incrementing both of these slow pointer and the fast or the pointer by one so pointer will go here and slow will go here and pointer will come here and slow will come here and you can see they meet at the beginning of the cycle so that's just a characteristics characteristic of using two pointers is that when you are looking for the start of the cycle you want to use two pointers and first determine whether there is a cycle so use the fast and slow method and then you want to iterate again from the start of the list with another pointer and keep on incrementing both of those pointers wherever slow and fast landed and they met over here for in this example we want to then run another while loop with a pointer starting at the beginning of the list and that slow pointer incrementing one and that other the pointer at the beginning of the list also incrementing one and when they meet when they intersect it will be at the beginning of the cycle it's just a property of two pointers it's just how they work and uh and that's how you get that and now of course we want the index we want three not four we don't want the value we want three and so all we have to do is just when we do the while loop we can just have a counter or we can have an index variable set it to 0 and then just count 0 1 2 3 this is going to be where they both meet all right so that's how we solve linked list cycle two let's go ahead and code this up okay so we jump over here and so first thing we want to do is we want to get a fast and slow pointer so let fast equal head and let slow equal head and then what we want to do is we also want a pointer equal head because we'll use that one during our second while loop and then we want an index variable and we'll just go ahead and set that to zero okay these two variables we're going to use in the second while loop and these two variables we'll use in the first we'll also use the slow the position of the slow in the second while loop as well so now we again we're just using that classic pattern so we'll just do while fast and fast dot next is true and if you're wondering why we're using fast and fast dot next uh you can check out uh the video on link list one where i go into detail why we want to do that but the reason is quickly is that we want to make sure because here we're going to set fast is going to equal fast dot next and if there is no fast dot next then when we run this dot next on that node it's going to throw an error because there's it's a null there it's going to you can't um you can't invoke a method on a null value so that's why we're using fast and fast dot next and then we're going to just increment slow and this will be slow dot next okay and now we just want to check if fast equals slow then we just break okay because if they do meet then slow is in the right position and we can just break out of this while loop the only reason we're doing this is we're just trying to figure out where fast and slow are going to intersect if uh if there is a cycle now we just do one more conditional outside of this we just check if fast does not equal slow then we return false or we return null i think that's what they want us to return if there is not a cycle yeah we return null and the reason we're doing that is that if we make it to this conditional right here and fast does not equal slow then that means that this input there was no cycle there however if we make it to this condition and we break out of the loop we just want to check that fast and slow if there is a cycle that it's in the right position and it's because there's a cycle that's why we broke out of the loop okay and so now we're going to do another while loop and uh we can just i mean this can just be true because that we know there is a cycle so it is going to meet so there's no need to break out of this loop the condition will be met inside the loop and here we're just going to increment our pointer okay and our slow okay and um actually we don't want to do true here we just want us to do while pointer does not equal slow okay and then we just increment that and then we also increment our index idx plus all right so after we do that we just want to return our idx okay let's go and run that you have return a value that is not a list node type oh i think they want us to return the node not the position yeah there we go okay oh and then we just want to um have an edge case here let's see if fast is not equal slow we want to we just want to have an um one edge case here is if head dot next is null i want to return null and if head is null as well we want to return null there we go okay so there are a few edge cases you want to keep track of um if there's no head and if there's no head dot next then we return null because there can't be a cycle we don't need this idx here because that was my mistake i thought they wanted and they wanted us to return the idx but they don't they just wanted us to return the actual node and so if there's no head we return all if there's a head dot if there's no head dot next return and all and then we go ahead and we find where they're intersecting and we just do one more check that if there isn't actually a cycle if fast will equal slow if it breaks out of this while loop and so if it does not equal slow then there's no cycle in the input and we return null and then we're just incrementing pointer and pointer.next and we're seeing where and pointer.next and we're seeing where and pointer.next and we're seeing where they meet and wherever they meet that is where the cycle begins like we went over uh over here you can see this right here is where the cycle began and that's just a property of linked lists and using two pointers again you want to be familiar with this you want to just have this memorized using two pointers how to find the length of the cycle would be the space between fast and slow so you would just you know have slow here and fast and then increment one of these all the way around until it loops back and that would give you the size of the cycle to get the start of the cycle you want to use two pointers figure out where they intersect and then have a third pointer that runs and wherever they meet will be the beginning of the cycle and again to just detect a cycle we want to use fast and slow pointers and figure out if they meet then there is a cycle okay let's just quickly go over time and space complexity so time complexity this is going to be linear because we're only going we're going over the list twice so the time is going to be o of 2n and we can just approximate that to o of n okay and then space what is space we're not creating any new space we're just holding variables or holding data in pointers and so there's no space so our space is going to be constant space okay so space will be of one all right so that is leak code number 142 linked list cycle 2 hope you enjoyed it's a good one to know definitely comes up and there's a lot of principles a lot of patterns in here that you're going to see over and over so definitely want to be familiar with this and i hope you enjoyed it and i'll see you in the next one
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
818
There are definitely 108 cloves. How are you guys? If you start from Siri, then this is the series Heart Serious Questions, Tight Hard Series in the sense of loot. We will pick the top card questions, so each hard question will represent a topic, like whatever we have. Main topics which you should know in Interview Factory are Dynamic Programming is Graph is Giridih is Sliding Window and many more side topics which we will cover in this thing so now where will this series give you any benefit if you are preparing for interview. Definitely you should know what are the top interview questions. I have already made many videos on the English team on the link. If you have not seen it then now you can check it out. You will find it in this channel and we have also made videos on the team. Videos have already been made, a lot of requests were coming, what about other data structures, make videos on them too, so I thought, friend, this is an easy medium problem, if you prepare for the interview, then I think I know you, okay, so we will do ours. I have given the main focus and heart problems, this will also help you to know how to approach hard questions, okay and you may also get to learn a lot of new concepts, okay, so now let's start without any delay and a And the most important thing is that I will give you hard questions, after that I will give you sign in. Okay, assignment for example, I have given you two questions to do and one question for you to do at home. Now I want you to answer two questions. Do whatever I will give you questions on the side, if you can do those questions then definitely watch the video and you will learn the concept and if you are successful then everything is fine. If you are facing some problem then you can watch the video once again. Whatever I tell you. I will give a question on the side, it will be related, the first question is fine, it is not like that at all and it is related, it will be related, this will also help you practice and I am planning that after covering this body in the kitchen, I will hold a mock interview for anything in it. Basically, whatever you see, we will cover all the interviews in this, it is okay in this so that you get the feeling, what other questions do you ask, so I am thinking that right now the main focus will be ours. It will come on Hot Scenes, okay, so this is one thing I want from you, Yadav, that you subscribe the channel, it is okay, you are liking it is very good, but subscribe, friend, what are you doing, let's start the songs which are our questions. That's fine and I will give you all the questions as per the description, then we will approach you. First of all, you have to click on the link above that question and read the question carefully. What is the question called a question? Want to understand the question completely end to end, still if you come across any question and think that there is no time then you can watch the video that I will understand or watch the question. Progress of main approach. You read the question, understood it and then design the solution. Try, try, at this time, which algorithm can we apply in this, if you even think about losing weight, then you are in the right direction, now after that you have watched the video and you have seen that I am doing it here. And you people are wondering whether he is somewhere in the world, if so, then it is very good, there may be someone else in your section, if not, start the process question, then that is also a very good thing and you must definitely mentor him if you are someone. Do the question in a new form because it can be very popular to do a question because it depends on the doer, I am friends, it is okay now the whole example cost is very less and if I want, I can write the end cube solution just for example, if I want, I can write this Log in because the cost is very low, so it is not that there will be only one approach, multiple approaches can be used and whatever approach you do not have, if you think of any approach other than this, then comment and tell what you think. Okay, now let's start, what is the question basically saying? Your work is fine and first of all, pay attention to the main point of this question, let me tell you that, we will write it on the side here, okay, I have written this in the comment. For this, I have made it here which is the main point, I will also discuss it with you and set the question for its sacrifice, what are the questions for us and what do we have to do, in which direction is it okay to think? Subscribe by starting our car. The given position is zero and its speed is plus one in a tumble, that is, your car is in the starting position, it is at zero and its speed is that app Laxman, okay and the main point here is that in flight number nine, so we have The number line is infinite, meaning it is not a particular end to end, you can tell that it starts here, ends here, the flight number is a line, so first of all, if I teach you, it is an infinite number, okay, so here we have Infinite number nine, these are the main points, I turn on the mode there, after that whatever will be our starting point, which will be our starting point, that is zero less now it is 201, this is what I have written here, this is our position for speed. The car will start at its starting position, its speed will be at zero. Okay, now let's talk about this government. * Negative position: It is government. * Negative position: It is government. * Negative position: It is not that your car will move in the front only, it can also move backward, it is in this situation. Consider the question as if you are sitting in a car and give us instructions by asking whether your automatic car is okay. Now there are two ways of giving instructions. Either the car can go forward or it can come back as you see in a normal car. So you can select one, you can take the car in the reverse direction, so this is the point, you can go into a negative position, what you want to say is that your car can also go in the reverse direction. Okay, so we have 224 here. If I try to write six pieces here, we have 234. Either I will do a back or I will reverse you. Now everything here is condition Singh has done nothing. If your The car which is there gets instructions i.e. your car has to be gets instructions i.e. your car has to be gets instructions i.e. your car has to be celebrated, then what will happen in that case, our position which is the new position, will it go to the position plus six speed or not, where people pay attention to this, our current which is known. Our current A, I will call him the coordinator, this is a car, a tribute, can handle car accidents in the sense, work truth will contain position and spirit soul to any extent and position and spirit soul to any extent of position, we will tell what kind of position is what is it, if it is okay after beating that, then this thing Pay attention to what our current position and current speed can be and what can be our next possible position and not possible speed. Okay, keep this thing like this that we have two options, either I will update or we will reverse. I will do so that we can have some conditions for each option. If you look at the question carefully, when you get the instruction share patience for A, that is, our position, she will go, add whatever is the current speed, okay, this will be next. Multiply the speed which was before by 2 and we get next. Is it absolutely correct or not? If I look for option A, if I hear option A, You are my next position, right? Which is my next position? I should write an inactive post on this, Pooja. This is the current position, I am plus job, current speed is ok and this is my net speed, Jio is net speed, she will go, I take this is my friend speed is ok, plus multiply bittu is 2G net speed, she will go, do speed multiply bittu, so this is The option is your player for one. Now let's talk about what is the option for reverse. So our option for reverse is that secure speed is positive and speed post - we cut other wise pieces in the morning. post - we cut other wise pieces in the morning. post - we cut other wise pieces in the morning. What do we want to say right now that your position There is no change in this position, if you have given the command to reverse, what does it mean that you have just received the command, you have not yet started moving back, your father has just given you the command, so if you have received the command, then in that case The car will decide that my speed will be negative or it will be plus. Now what I am trying to say is that if your speed is positive then it will become negative and if it is negative then it will be plus. What does this mean to us? Let's look at that thing. Think carefully, now you were going in the reverse direction and then I told her that brother reverse, well I ordered her to reverse, now reverse became reverse forward, she was already going backward and you told her to go reverse again. If the bank worker goes reverse forward then if the car is going in your negative direction then this will be its speed, it will become plus and if it is going in your positive direction then it will go negative in drinking juice, then it is similar that if Let me tell you this carefully, if the speed is positive then if our friend's speed is greater than ours then that is our net speed. Now we can write it like this. For negative, if ours is negative then my net speed will become and If it is positive then our net speed will go - midnight so we have some go - midnight so we have some go - midnight so we have some condition that the net speed is 'a' so condition that the net speed is 'a' so condition that the net speed is 'a' so I make it a little bit bigger here so that you understand okay then next video and next position something. There will be no next position, we can see here that my next position will be the same as my current position. So we have the net speed and the next position has also come in the size of both, that is, we have two choices and Look here from the condition we have for both 24, so now what should be the question for us to ask? Your question is that I have given you the complete example of the target. Okay, I told you that you have to go to target three. Okay, so what should you do? Here is the show test instruction that I have to give you, meaning I want to say here, if you are given a target then you have to tell the length, small sequence obstacles, okay, now small instructions that if I talk about here for example, if I told you tiger also okay. Now let's understand why this happened. For example, our current starting position was 800. I will write down which is our starting position. The current position is 208 and that is our current speed. That was Chyawanprash. Now I told you that if you want this question, then what will be your next position, this is my zero if message and this is based on titration and here if I am on the first impression side then I will talk about the current position. So now pay attention to the position I had earlier, press the current seam, you get my instructions, now if you go to the app, the next position will be the current position, press the current position, at this speed, our current position was zero and do this on this earth and that is, even now. So the current that has become has also become the corrector, what will be our current speed now, what has become of the previous speed, multiply it, that is, the speed that we have now, is correct, now let's talk about what we have till now for the next question. Got instructions again, now the current position is one, she will go to one plus two, this is a clean lobby, our current speed is, she will go to two years before, but we have researched the target here, so that means if we do not read the minimum instructions, then two questions. We had to tell you the target life and tell you the minimum number of restrictions that we can give so that he can do research on the target. If your car is fine then this is another question. I think you must have understood the portion well. If you Could not understand that again, now remind the video and watch it once again, now the main issue here is that ok, we have understood the question but in which direction should we think about it so that we can talk about the solution. If you do, then give some thought in this direction, then the thing to be noted here is that I have options to explore, okay, we have infinite number nine, so now whenever you have options, you think in terms of records. In fiber, in terms of worry, in terms of bus, now here these two things, now I want both of them because even in between, whatever you have, in a way, you are providing options to him, for example of binary, okay. Where people are fine, you know that I have the option in the right hands, I can go to the left, I can go to the night, so you support both of them in some portion, using why is that face method, you can also call the options from the middle. If I understand them as a resection, then it is okay to have an over head liberalization which can benefit us too, that if the face can be imposed here, then pay attention that if the benefits can be imposed, then why use the name. Can I store it, can I use rezoning, can I use dynamic programming there, then these are two things, if this is a question, if I can use it, then I will check first, can I decide, and if I use base, then Man, how much time complexity will come, then I will send that ok sell time complexity, I will put this face in the house ok and then what will I do if it is because of me and after that I will try to mash it, I will see if there is any overlapping sub. There is a problem and after that I try to mash it and then see if I am able to reduce the time complexity after mashing it. In both these situations, if the answer is yes then that means both the solutions are valid. So let's talk about the problem that I told you after Brad Sagar that Kabir, what is the relation between weight and weight, then let's talk about something here, what is the main problem here, take that infinite number, now understand this thing carefully or I assume that my targets were the same, then it is okay, then the instructions I am giving are the habit that we have also got the habit of infection, what are we doing, the instruction, sister, I have told the car to come, now the car is going behind us, the target. Now I too may have a sequence in which I etc. do all this again and again, I am here now, the instruction is late, why will I give it at this moment, when will I give the thought-provoking conversation in the instruction, if I know now. That when will I give the thought-provoking conversation in the instruction, if I know now. That when will I give the thought-provoking conversation in the instruction, if I know now. That I have never reached the target, now the car has not reached the target, it means that I have two options, either I go flat or go in reverse, there is also an option of reverse here, if I talk about reversal again and again. In this case, we have a loss. In this case, the loss is that if you do reverse again and again. Okay, for example, I would like to say to you, give this thing carefully, I did a little bit of that here, you did the reverse. Okay, after doing the reverse. You saw that my speed has increased - minute correct. Now what have you done? You have selected one, the increased - minute correct. Now what have you done? You have selected one, the increased - minute correct. Now what have you done? You have selected one, the vehicle is in reverse direction, now you have accepted that the traction wind is going reverse but your target is ahead on the positive side and you are going on the negative side. So you are not able to reach the star but still your command is late, then there is something missing here, there is a point meeting, when will we be able to know that if we do not go reverse or now beyond this, I cannot go forward, I am here. But after some tuning, it came to mean that I need some condition here which tells me that brother, if it is in this range then it is an infection, if it is not in this range then it is a question. 2 Understanding this thing now like A. Knowing this, example if You will see here you went into reverse and after that I did a cold accelerate and this again and again as per the instruction you will see if the car is doing the reverse direction medicine now and is not able to reach there then I have the option I can give any proof, if I give any command, this is also a field option, but we have these options, because in this way you will have infinite number of sequences, okay, so we do not want that, we need something here. But we need a step that removes our invalid sequence. Invalid sequence means that if my position is still too far away from the target, now it is too far away. How will we tell that it is too far away? Then this is the cream step. First of all, what I want to tell you here is that understand the question, what do you want to say in this question and what do we have to do in it, we can travel anywhere on these flight number lines but it is important to hear that we have to move in the federation that if I forward If I am going then I will go completely forward till the end, it is okay if I go by my voice then I will go absolutely reverse but I have to keep in mind the target that if I am going backwards exactly behind the target, it means the target is here and I will reach exactly here. So what does it mean that I will not be able to receive even the target? I have to go near the target and not go away from the target. Pay attention to this. I have to go near the target and not go away from the target. So try this now. I have an option, I know today's news Begusarai news request, it is a little easy to do it with bank weight, you can do it, I am thinking, I have tried it with friend benefit, okay in face, we will ignore both the options and give it there. But how can the pruning step be implemented, so what do I do here, let us understand a little bit about what we will do in the code, okay, I will leave it so that you can understand what we are doing in this, so now the function I have is its And the target that I have is Italian okay so first of all what I do is I create some of my variables for example target okay and here I write this is targets request target so this is what I do first you start Taken and we need that and minimum number of sequence right minimum number function so here we get a to minimum number of sequence torch light so of this defect Vikram 12 minimum number of instructions light so this method will be our co and it will give me lakh that I have porn with minimum numbers, okay, and we will sell some, we will talk about it, now just one cup, I would like to tell you that the tech we are preparing like this scandal skeleton which we have to use, okay now let's talk about that. Now I told you that the car will have its position and its speed. Okay, so now for this you can also take a pair of intent which will represent that what is my current position now, is that back, whatever that is a valid thing. To get the instant pair, I should make it a little generic. I take a class here, which tells me whether my properties of the card are correct, the properties of the car, you say, or the battery of the car, yes, you say, then I give the tricks here. I say, okay, working tricks, so we have two things in this, one is private, one is public, so I will come here sir, you will also see this thing, how am I writing the code, okay so that you can also have a little idea. When we have to write production level, how is it written? I am also not fit in this thing. Okay, slowly but will do something. Hmm, okay, even then you type like this. Virus should go away. Either this is my position or Then my speed is fine, both in our interior. If you look at this question carefully, here there is target and telescope and there is no tension here that it can be in decibels, so it is important to clarify these things from the interview. Here I am Inter Minister tell me it is int but when you are in interview and you have any such question then reply that friend will the position be interior only, target will always be interior if it is in decimal then how much book speed difference should I know valid. It will be right to whom I will sew, it is said that if you have used the orphan root of number - then you will know number - then you will know number - then you will know what you should do. Okay, even if you are not on that side, let's try this question. Okay, I will enable it by clicking here. Which will be the task Tricks Okay, so this task will be from street food, that will be ours, here we will pass this tree is one, so we will pass the position is acid and if we pass the statement from, then what will be here, which position request opposition and this Speed request to speed tight, so I have made this oath, now after that let's talk that I have made both private here, so how can we set it, how can we make it great, so we will do it here. But we will set the position is fine and similarly this set of mine is speed and similarly this gate of mine is position and gets passed by doing this you can make to you know public properties exercise meeting to private you have a little bit of correction of all four here I am directly my If I am not able to change the pimples, I am changing them through some method only. After this lead after reaching tight, what do I do to you, do a set of these positions, I know it is not required for the lift question but it is a good idea if You mean, if you are able to write it in a well-quoted manner you are able to write it in a well-quoted manner you are able to write it in a well-quoted manner and you have practice in this thing, then it is very good, why should you write it, you should write it in a bigger way, you have practice in a way, if you are okay then it will be there in this too, which is our position. Okay, position will be there and this is our speed, because of this, speed is night. Similarly, our gate position will be this, our gate and sum net speed, so both are points. Don't okay, now both are inches, so what can we do here. Can return the position Okay and here what we can do in get speed Now we can remove the speed Okay this became my car attitudes of clans in which my position is speed Okay if I have something else Let's make patience, I can add. Okay, now here this thing is a big subject taker, you say and there are two things and we can use printed feet, but in the palace interview, some interviewer is thinking and he gives you a flop in which Apart from the position speed, there is another variable, okay, what will happen in it, then you should understand the foot option 20. If you make him player of the year, then in a way, I think that man is from him, you create a separate class for him, body, but nothing changes. If you can add that force and add here, then it is okay. Leaving aside the cases, when the time comes, you can make your image. There is distance, you can add distance and okay, so these things, that is why I refer you to create a separate class. Now let's talk. Let's get the minimum number of restrictions, this will make our ghagra minimum number officer, we know that we are here with the gas, let us try it and we will see the tuning step, so which is our two, which I have to tell you, the apron step is the most main thing, okay I will tell you how to print it, now we have the target, okay, and we have the gate, minimum number of stations, okay, first of all, I love you and minimum, I write here that in my last, now starting. In the minimum number of which is my instructions minimum number of instructions okay and that is zero okay I click here return minimum number of functions okay so this is youth I have to return in the last and let us why do I make That I need to use the face Westphal true so that's why I'm making it again because this thing will definitely be that factor because I need position there I need speed there okay so what should I do you here care reason tricks sorry then we In this program Singh, here the rate reports will come and after that what name should we give to the why, still I wonder why we used to write it as benefits, okay now it is good to read, there is a ribbon, okay so what do we do here. What is our starting position till now? What is our starting position? First of all, Jhamru, I told you here because the comment is that the one who started is zero one, that is, the position thing is that speed is our one. Okay, this is our starting coordinator, absolutely okay now. The thing to be noted is this, try to visualize it in your mind, phone, I have both the options, I can do AB, I can do more, it is also possible that I have written such a sequence, I know of two such sequences. If you write something like this and one is a different sequence, then by coming to a particular coordinate, those two sequences match yours and erase them, then this particular point is visited in one sequence also, it must have been visited in the whole other sequence, so can I will not visit it again and again because once I have tweeted a little, it has to be visited again and again. I think you are understanding this. So now what will we do here, along with checking the Kwid, we will also visit this page again and again. Ways I can take the set inside Lord of the Rings Okay Anushtup Spring there are more ways you can take you I feel like I am here Anushtup set I feel more like okay I will make a request sting to you or basically One is that it is set, it is fine and it will check whether it is set as widgetized or not. You can tell him that my particular position has been widgetized or not, it is correct, so I have got the work tributes, is there anything wrong, is there any tribute? It's right, it's okay, the work is done Tributes Frank, we are not at home, I want to understand why we are showing late, no problem, we will see later, okay, let's talk now, the first point that we will put in the festival, we will put it, I am still a bachelor. Tricks, okay, so first of all, our current position will be 200 right and my friend speed will be there, okay, I will check with us, why not benefit, why the simple method that we come up with, okay, that is notification.mp. come up with, okay, that is notification.mp. come up with, okay, that is notification.mp. Okay, now. We put the thing here, we forgot, now the meaning of that thing was that okay, do enough to do this because I want the position and speed here, a particular position and a particular speed, this is above, position and speed. I want to tell you about the position and speed that we will make a pair together, this is what we want to do or want to make, okay what will it be, will she tell you basically, is it specific whether the video has been done before or not, now to do this thing. There are two ways, so I make a string, that is one way, what do I do? Well, first put the thing you want in it, I will take a front and then a node map, so put them here, I will interpolate here and say, brother, this is Visit map is my 11th method but I am thinking that instead of doing this, I should do spring only, it will be a little easier and if it doesn't work then we can do something else, so here we make the key first. Okay, let's take a string of accounts that we will visit in our visited set. Okay, so here we do two spring that think of someone that we want to create a unique key that our festival and we want to create a unique key so that In our car activities, let us tell whether a particular task has been visited or not, so I think you are understanding, so to set it, we can put zero plus if we want, we can put anything, okay two friends here. But I am going to put plus pills so friends and here we do one which will be Ishwar Mahato which is our one current position right now is zero love current coordinator mintu ok now what will we do here we will do inside my visit set If we need this particular bill, then we have made the particular next here, now let's talk about its need, we have already made it, we have visited it, okay, so what should I do now, so I will see what is the size of my current, okay why? I appeal size request to face tune an adult you don't size ok now this letter to make a student and oil size - - what we are doing you and oil size - - what we are doing you and oil size - - what we are doing you want to see how many number option at my current level ok if so It doesn't happen if Puri is here, I did n't get the target here, I didn't get the target here, that I need 119 traction, now I write here that the minimum number of instruction which is ours, give it one plus, it has been 212 for decades, that we need 119 traction. Will have to pay now because I could not file it properly here. Okay, now let's talk, we wrote the get minimum number function, there we are using benefits, after that use size - - okay, now I after that use size - - okay, now I after that use size - - okay, now I click here car. I take activate kar tricks will be useful front because this front and here I did benefit why is it okay this benefit will be an adult you that dot print good okay and here what I did which is my festive from here I took out the element that is correct Now what will we do after this, now I have the work attributes in the front, okay, now that is the attitude with the help of which we can calculate the next position and net speed. Okay, so I have written here that my current position is also in the front part get. Position is ok, that is my friend speed, I am applying, that is different, don't kids, so here we have got the position, got the speed, ok now it's time to exploit but it's time to explore and two options one is active. And dramatist reverse light, so we will export both of them, so in this case, one will play an important role, then we will export that and that, okay, now when we do explorer, we will have to pay attention to one thing, now our next position is here, I will take Takes the next position that you are okay, now we are doing that to one, so our next question is what you just saw and will be the current position plus friends Petite Pooja, what will be my net speed, that too my current speed, multiply by. Okay, here we have to check whether this is the exposure and the net speed, whether this is the visit, so I will take the string which is similar to this, we use the key itself and sign it, toot prank or good. Okay, here I will say next position and here I will say next okay, here we will check that my current key, if it is not visited, okay, if it is not visited, here current key means some time. Let me commit suicide so that you can cook it well, so I hope it is visible to you now, so I will check you that which is my widget set or not current key write, what does it mean if that video is already done, if I want that if that I am not a visitor, that's why I also want this matter from being. What do we do? I make a key here for Angry Birds too. Okay, if we copy the mantras, then what will happen in the case of day? Now, what is the next position and my net speed? It is ok, now my current position is equal to this position, speed is net speed, if she is negative at home, then call here, if she was positive, then she is fine, then she wants this position, keep trying, I will try here, it is absolutely correct, I am in my It is okay with you that if that visit is not yet present in this set, do the particular according to visit, okay then the first step will not be that if there is no operation, the joint visit set is two tin shirts, one, set his age similarly here. Okay, now let's talk about one thing that we are not worried about here is that at any standing time, at any standard time, if I find out that the car that we are in has reached the target. There I can return the minimum number of instructions on till now the minimum number of restrictions told that how many infections have you given till now, then if my car has reached the target then I know that whatever I have described till now Had given, with the help of that instruction, if America target is reached, then I can return the number function sitting, then it is not similar, roughcoin can be stopped, calculate the level here, it is fine in every area, if you want to visualize it face, then I Text each option here and this is what we have six routes fruit custard note I took one option from here I took one option I took two options a binary tree take time to this Now if I am coming to one option this is I took one turmeric that is this Schezwan this number 223 is on my third level i.e. on my third number 223 is on my third level i.e. on my third number 223 is on my third level i.e. on my third instruction I came to know that if you ask for a retiree in the car then it was destruction means he should stand at the third number, this is what I want so now this is absolutely correct, it is broken here, okay Now let's talk about the main thing which I wrote here about the pruning step. Okay, now let's talk about the install step. This step will tell us that there is a flight number line, so which side should we face till then. Okay, now let's talk about me. The option is excel data, ok, I will check it. Now this is the point which can be used at many places. This is a trick which you can use at many places. Now let's see what we are checking here that My target is - next position that if My target is - next position that if My target is - next position that if that lesson target is that this is a very good condition means it can be used in many places, I will tell you similarly in this case also, this is my position, it is also right here, what are you saying now. This is the position, I have put fruit here because the position I have can be negative as well as positive, I want to know how close it is to the target, whether it will be equal or not, it has not opened because I have I had calculated earlier, okay, now I am talking about the next position, so the exposure that will come to us will either be behind the target or in front of the target, so I have to calculate that if I do not go that far from the target, that means which The distance is, it should be around the target, what I want to say here is that I observed the distance between the target and the next position, I paid attention to it, I showed how much is the difference between the target and the next position. Right, that distance has to be kept to a minimum, so what I have done here, the target is the next position, here I am trying to complete the medical, okay then I want the distance in order to Ray around the gate so here I say Ganesh alag investment this is simple on rickshaw okay now what do we do here and because I know if this condition is satisfied then that validate is okay now what do I do here this statement Which is the Visits and Voting set, that basically it should come inside it, because for example, if we have reached a point and you have not yet deleted it because it is not there, we cannot mute it like this, we can visit it only then. Where the free target is there, why did it happen to me but I did not add this problem, okay, what will we do with it, what do I do in this topic, the condition is here, I end up on us, okay, with this, our overall The code is there, it is a little centrifuge, okay, I am telling us that if it has not been tweeted yet, it is okay, we can visit it, so let's try to visit it and if that is my next position. If the next position, that is my next position. If the toe is near the gate then there is a file to visit him. If he is far away from the target then he will not be able to mash it. So me you me what will I do? B.Ed So me you me what will I do? B.Ed So me you me what will I do? B.Ed Auspicious and here we will do something now Auspicious and here we will do something now Auspicious and here we will do something now work tributes Okay, so here we will pass the next position, next speed okay, so this is done similarly, we will try to do the same thing here that one okay now look here the minimum number of restrictions if we are able to get the gate then definitely. In return gift, if I am able to reach the target in America and here, then we can prevent, but for example, I have explored all my valid positions, so we have to find out by trimming step, as if there are lines at any position. I am doing this, I have a shop but could not reach there, so what will I do here - I will do 110 what will I do here - I will do 110 what will I do here - I will do 110 correct, so similar to you, because if I have to pay any note and it is present in the particular level, then I return the level. I did not get the note, this too in the particular level, I have traveled the whole trick, if you understand it carefully, hard work ministry, if you take it as a subject from here, then friend, this is two positions on one note, so I will go to this friend, I will go to each one. The thing is there are two possibilities depending on each note or here dengue 281 go to you growing does not mean that if I use it in my mind then what will become of my Next9 and if I use the instructions then what will become of my Next9 Well, I think this is our code, it should be sufficient, let's try it once to see if there is anything wrong, it is showing the idea, okay, but if we have to test the cases, a minute, okay, then this is our input. That's three loot, that's broken, ok, now I have given you a class, we can add it to this, now I submit this question to the interviewer, after that, subscribe, if you can subscribe, then it's ok brother, it's accepted, ok. And let's not pay much attention to it that I told you earlier that now if we follow any approach, there can be different approaches, it is okay to ask one question, so now what are we doing here, I am trying to I can tell other people Curzon Wylie but I will not tell, I want you to ask yourself a question and try how we will be able to do it at once. So whatever is in your favor, what I told you is the setting of the video. I will send it to you, those who are on your side, how can you do this question with the American, try to finalize it by making in your mind that there is such a problem, overlap it, you will overlap because I have told you earlier that this is made by tuning. Two things whether it has been visited before or not then if that sequence is pure sequence then there is a sequence and this point is found in particular both the sequences means the point is coming in between both the sequences, at this point in the sequence this If the sequence point is different then it is a particular point, it is visited or else in both, increase its result, start it in advance, then I can definitely use it in this or I can put media group programming now. Player, now let's talk about what I will give you in the next question juice. I am going to tell you whose flop it is, but you will not find the list from which to open, I told you that brother, the instruction is fine, you have printed it, okay that point, but also print the infection, which infection it was, now let me pay attention to this thing. How can we use this, there are two questions on the side, first of all you have to ask how we will do this from UK and the second part will be that if I put a meter in Recgen that I do not want a balance, I want that minimum. The numbers need the spring of porn that the protection fell asleep in my last for which Yasmin I want the movie, she brought me the setting but now what do I do here, so you also see this class now, this is the code, not the model, okay, I have every one The system is set up and here I can easily add the parameters, okay, hate that will tell me how many observations have been made so far, so I add here, instructions friend, okay, so far. If there is no shame then let's leave it like this, let's add far so far. If there is no shame then let's leave it like this, let's add one more character and let's add 180 crores here in which I will pass that my desire is spring, instruction spring will come in instruction spring and this will be this instruction spring question. Do you understand, you are a question. That now we have to print the instruction spring also, so I do it quickly, so this is done, our country instruction, why not request to instruction, I write yours here, this will be anti, it will be okay because here we have passed any success print. No, okay, so we have this, now we need it for the set, I am the third, okay, let's make it takes a little time, no problem, the instructions were copied from the website, the instructions were to win, here we take the string, the instructions were spring. Instruction distorted subscribe position is done now we need instruction screen we have to gate set the instruction screen this is my method and here I returned the instruction okay so here I have made a matter will add one okay now I have three tax meters in cars. Position speed and infection friend. Let us print the instruction straight. Okay, now what will I do here. I will not return now that there are springs here. Okay, it will be fun to ask questions. We have this pin, so if my If I send the length of the meeting then it will definitely be the minimum number of instructions, then I don't have it, you will get both the work done, the length will also be done and it will be printed and if I don't get it, I will return it daily. Now what do we do here? There is and is because to make it velvet to us I think I will have to create some class of my own from which we will be able to express the meeting. Basically we will have to create a separate file, so this list will also tell you within 2 minutes of playing, we have created a class, what did we do in it. Here is a solution which is elastic of digits, we modify it a bit, now inside the intent, we are returning the spring here which is the minimum number of instructions we want from, okay and after that what I did here is the input file and output file. We have added the target from here and created the solution code and from here we call this function. Okay, now the thing I was telling you was that now we have one more thing in the car accident and that is already there. Tank So if I tell you right now that if we are standing at the starting point okay then if we circularize the reason tricks then it will take its own default value its entry lion so if we are standing at the starting point our car then we have now If there is no infection, then definitely, now we write 2018 here, so we do not have any infection, if we want MP3, then I like you, now one which will be my string, that too from the instructions which I have in the current instruction, I will put it in the front. Don't instruction spring is ok so from here we cut instructions from remove now what do we do here if I have current position inspector target then I will return your unit to distraction simple ok now this does not give me minimum number of instructions From here I can get rid of this also does not require this here, okay, now which instruction can I return directly here, it is absolutely correct, now here I tried the same pimples by step which I used to check yours now What will be our next instruction, for example, now it is a coincidence, I am using you, if this is my current instruction, then what should I do in it, please tell me is this one okay or what can we do which is mine? Which instruction will it be? Now see, there are two cases in this, either this one is the case, this is the case, how do we need the time of both of these, so what can I do, I can explain it in an instant, I can make this trick, spring current option string, okay now. What will happen here is my current instructions from the current session which is mine, what will I add to it. Okay, so here I will send what is mine and the current attribute will go to the current option rate. Similarly, in this case too, it will be okay. If the incident is there then there will be more here and I can give the current options here, so now once I compile it and see if there is anything abroad, then if you have to go here only once, then my spring is these eight, okay. Let's check for those who do it in the right way and give it color. If the court has run it again then understand that if TK has been run then understand that you have not come in a simple class in which there was position, there was speed and one The flop question was asked that you will return me the minimum number of pension. Tell me, the question was that you should return me only the infection sting that I have the success pin. Now the question arises that friend, multiple instructing can happen. Definitely, multiple instructing can happen. Which can also be a lesbian, we can't say anything, can send a message to the multi construction setting that I am also of the same gender, if I am not of this ambulance then I ask you this question, does this question have validity if I am asking you if the question would be whether we can have multiple answers for a particular target, then you have to comment to me. If it is possible, then how will we handle this question? Now the important thing here is that I will tell you directly. Let me guide you a little bit, now here this screen is gate minimum number officer option, what to do here is directly return, if you look here and where we have target front door, here we return chakli and comment section is here. But multiple district is not quitting immediately, what could we do here, if this is possible then what can I also do, I could have taken the vector, this Priyanka can do something here, I could not do anything, after that again I could explore the possibility of, so you have to tell me that once I get the minimum and ping, is it possible that I have another such spring, one seat each, I want to give you if you fruit note But if you are standing then if you are going to the next love you and then after that to the next level and then going to the next level then what you have is that there will be one word on each level, one character add is ready, okay So if you are standing at a particular level and there you thought that you have got a swing, a target Kunwar, then will you try to go to the next level, then it is okay to think about this. I think you understand the question, this question was very simple, if I talk about space complexity and time complexity here then look at Falguni step here, the most disgusting step tells us that if you talk about simple BSF here So you will know that if you assume that you have advantages, then it is okay, then if you have advantages and agree, then it is okay for you to decide on these plates, but here how can you sign up, how many numbers of vesties did I have, how many vesties were there in this. What can happen, I think that it can be like this, it can happen that first you are here, then you go in reverse, then you are on the target again, then here also you have covered the same distance. Have traveled and traveled there that much, so if we take the spinners of this year, then after that what is the time complexity, then it is up to you to comment, okay then okay guys, if you liked the video then like it. Like it, I will provide you the solution in the penis, you can go directly and see the solution, it is okay and try again because if you understand then it is more difficult to do, no, it is a complete hard category problem and if I tell you in which company. When asked, this question was asked in Google. That question is fine because it was asked in Google and it is not about phone interview. It is about one side interview and if you had gone to one side also then you would have known about fibroid. If you are around 30 then in the fourth round it was asked that I am fine in which hard level question if you perform well then how did you like the question you have to tell in the comment that next question tell me by commenting which one to do after Tagore we are here But cover the interview specific questions in the list so that it does not happen that you gave me the question at 11:00 in the office and if I gave me the question at 11:00 in the office and if I gave me the question at 11:00 in the office and if I try to do that, then this series is not for that thing, I too can In the future, I will create a separate group for computer programming, but right now this interview is serious, so if you want me to do something new, please comment and make a video on it, then you comment. 91 of the mountain question list. The topic of this time is right, it is not that religious programming of any category states man fight, so I hope you understand, like, share and subscribe, see you in the next video by the that
Race Car
similar-rgb-color
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += speed` * `speed *= 2` * When you get an instruction `'R'`, your car does the following: * If your speed is positive then `speed = -1` * otherwise `speed = 1`Your position stays the same. For example, after commands `"AAR "`, your car goes to positions `0 --> 1 --> 3 --> 3`, and your speed goes to `1 --> 2 --> 4 --> -1`. Given a target position `target`, return _the length of the shortest sequence of instructions to get there_. **Example 1:** **Input:** target = 3 **Output:** 2 **Explanation:** The shortest instruction sequence is "AA ". Your position goes from 0 --> 1 --> 3. **Example 2:** **Input:** target = 6 **Output:** 5 **Explanation:** The shortest instruction sequence is "AAARA ". Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6. **Constraints:** * `1 <= target <= 104`
null
Math,String,Enumeration
Easy
null
1,897
Hello everyone welcome to my channel Kodri with Mike, so today I am going to do video number 16 of my lead code easy, okay the question is easy but we will create it in three ways, the logic will be the same but the way to implement them will be told in three different ways okay I will show you the code of both c+p and java okay I will show you the code of both c+p and java okay I will show you the code of both c+p and java today. Lee number is 187 easy marked. The question says that you have been given an array of strings. Words are ok in one operation. Pick two distinct indices I and J where words are I is a non MT. String and move any character from word sy to any position in words j kya kehna chah raha woh abhi dikhata hoon example se return true if you can make every string in words equal meaning ultimate m pata hai kya hai words wala jo hey hai na yeh jo You have to tell whether you can equalize all the words in the input, okay, so let's see here, like what is it saying, like this is ABC, this is B, okay, so one. Pay attention to the thing, this is a B, right? What did you do? He came to this person and said, give me an A and give it to him. If you give it here, then what will he do? He will pick up an A and give it to him. Okay, so now. Look, pay attention, all three words have become equal, that is, it is possible to make equal, the answer is true, okay, this is clear, okay, what did we do by removing this from here and giving it to this one, okay, now look here A is B, this is A. Yes, this is A, but it needs a B, that's why it is A, it will also be able to become A, but there is no B, we don't have extra, look here, there is only one B, if there was another B, then it would have been given to it, because Look here, if you notice how many people are there, how many candidates are there, one two candidates, so if you look at character A, look at one character, it should be two, right because there are two people, so both of them should get one A, so this is One is found here and one That brother, all the frequencies should be equal and not even equal, that is, it should be equal to n = and not even equal, that is, it should be equal to n = and not even equal, that is, it should be equal to n = 2, right, that means they should be divided equally among all n, like this can also happen, for example, let us assume that here A is B, Y is A. OK, so here you pay attention to what is the frequency of Look at the frequency, it is only one, no, whatever is four, it can be divided between two people, no, given two A's to this one, okay, but B is only one, it cannot be divided among two people, no, that means as many as The number of candidates is the same number of candidates. If everyone's words have to be equal then you have to make the distributor equal in all. Look at one character like here A B C A B S and A B and B S. This was the same. Well, look at the frequency of A, how much is it, one, two, three, how much is the frequency of B, one is here, the frequency of B is also three, let's see the frequency of c, one is here. The frequency is also three and how many candidates are there. There are three candidates. Okay, let's see if a can be divided among these three candidates. If the frequency of a is three, then we will do 3/3. We will frequency of a is three, then we will do 3/3. We will frequency of a is three, then we will do 3/3. We will give one a to everyone. Okay. Ok, gave one a to everyone, ok after that let's see b also, can also give one b to all three, aa a is done, c see, can also give one c to all three, so a b s a is done. That is, if all the three words can be equal, then ultimately you do not have to do anything, you just have to see that the frequency of the number of characters can be divided equally among all the candidates or not, meaning if there are n candidates then there are n candidates. And let's assume that my character is any character, it should be divided equally among these n people, it means that whatever frequency is the module of the care, if I take it from n then it should come to zero. What does it mean that equally? A, we have divided it among the people, okay, A, we have distributed it among the people, okay, so it is quite simple, so what we have to do is to store the frequency of all the words, then I am coming to my approach one, that is, they are right on number one. So now it has become very simple, you can code, but you must wait a little, I have told you three approaches, so see all the three methods of coding, the first method is very simple, you store one order, wait and see. What is this care, character and what is this int, what is frequency, look at the frequency of hut and just check that whatever is the frequency of each character, that module must be equal to zero, find any one such character. The model which is not A means it cannot be distributed to everyone, so we will return false in that case. Okay, all the E's should be equal to zero. If any one is found, frequency percentile A is not equal to two. Sorry, not equal to 0, then we will return false. At that time, it is ok. If all the frequency modules are zero, then true. If any one frequency module is not equal to zero, then we will return false. Its code will also be very simple, ok. Later we come to the second approach, those number two approaches are not different, the way of writing the code is different, look here, we have used a dirty map, brother, we have given a clear cut in the question that if there are only lower case English letter alphabets, then there is no map or int. Take 26 and initialize it with zero. Okay, and how will you store the frequency of the character of each word? Whatever character it is, how did you store the frequency of the array? Do you remember? That is, the a which gets mapped to zero index, the b which gets mapped to one index, the c which gets mapped to two index and so on. Okay, so the z which gets mapped to the 25th index, so Look, we have taken the size of 26 so that the 255th index is available. If we make it Oh C my A+ Plus, then the make it Oh C my A+ Plus, then the make it Oh C my A+ Plus, then the frequency will be updated. Okay, then it is the same check, isn't it? Will go into this count, will go into this count and any other. A frequency has been found to be the same thing. This check is the same. Only we have taken a different method of storing the frequency. This time we had taken a map and this time we have taken an are off integer in which it is stored. It is clear till now, what is the third method, I will show you that in the code, that is the simple way, which is not a simple one, I will use STL with LDA and don't worry about Java also, I will show you the code, okay It will be exactly the same, but this is the method of checking, you went to the for loop, checked all the frequencies, then you will hit the for loop, here also you will do the same, you will hit the for loop, but I am saying that a You can use simple STL but that is fine for your knowledge. This is only for your knowledge. In the interview I don't think you will need these things. It is fine only for knowledge purpose. We will create the same through ATA and Lada. Even in Java, I will show you through a library, okay, this part how to count is easy, okay, how can you check all the frequencies, so these are the three approaches, it is quite simple, let's look at all the codes one by one. Seeing the complete code, you will learn a lot. Okay, so let's start its code. Look, pay attention to what I said. First of all, let's find out the size of the word. The word data size was the first thing that why are you taking N map because I need to know the frequency of each character. Want is ok, MP for string and word will go to every single word, ok and will go to every single character of that word, Care and Seech is ok, extracted one word from this word and will go to every single character of that word and MP of C Made plus, stored the frequency of each character, after that we have to run a for loop, just simply int, sorry, auto and it in MP and check the frequency of all, what will be the int frequency, is it in seconds or not, the frequency is in seconds only. What will be the character in odd first? Okay, so we just have to check that if frequency module n is not equal to 0, that means we will make this character equal to all n people. Which character is my K C = Odd first? If you are not able to divide then it is n people. Which character is my K C = Odd first? If you are not able to divide then it is n people. Which character is my K C = Odd first? If you are not able to divide then it is impossible for all the words to be equal. Give return false right here. If this does not come anywhere then we will make it true in the last one. Let's see after submitting. Please wait for your third approach. Okay and it will be equal to words dot size. In the third approach, I will teach you how to write in Lada. We will also use STL there. It is good for your information. It is good for your knowledge, that is why I am telling you. Okay, this should also be submitted. Now what am I saying, after removing the map, I am saying simply take an int, right, count name is 26, treat it with a zero of size, okay and in the count, you will have to change C mine A instead of C here. Because the size is 26 and you need an index corresponding to the character, put a for loop, okay, you will get the auto and frequency directly, and if this model A is not equal to 0, then you will return false. Okay, let's say, this will pass enough. It is a simple approach, we just replaced the map, it is accepted, this is also fine, now look, pay attention, now I am doing the same code, see here, this is a for loop, isn't it a check for loop, this is the one that the frequency is divisible by. Is it n or not, I will remove it and I want to teach you how I will use it, okay, so look, pay attention, it is very simple, a lada is STL, it is all underscore off, what does it do, it checks that whatever. Whatever container I have, is it ok from the beginning till the end? Any particular thing that you want to find, is it all of them or not, is it ok in this count, meaning are all the elements of this count equal to what you want? Okay, so what do you want, I just write here A Lada, now in Lada, I define what I want all the elements to be, Lada auto Lada I is equal to sorry, so now look, remember all the elements of the count. If it is an integer, then let's receive it here by the name int frequency. Okay, now what we have to check here is that this frequency is frequency model a e equal to zero, so do you know what this all off function will do? This will check that all the elements of the count should be true, return is equal to i should be equal to zero, this is the function of all off isn't it and here from Lada, I have defined here what I am expecting if Let us assume that in the question, all the elements are equal to three, then you can do it like this, the return frequency is equal to three, it is checked, what else is there, you can do anything, you just have to ensure that all of it is equal to three. What does it do? This is what you wanted to know. What does all off do? It checks whether all the elements of the count are equal to something or not which is what you want. So here I have checked its behavior that the module n should be zero. All the elements are fine, now pay attention to one thing here, what are we missing? This n is defined outside and this is what is happening inside the Lada, so if the elements outside are not visible to you inside. If you want to access then you have to put m here, this is a very minute detail which if you ever do coding in extreme c+ program or at do coding in extreme c+ program or at do coding in extreme c+ program or at industry level then these things will be very useful to you, okay and you should also know this thing for your knowledge purpose. So I am just telling you here, okay, so let's see by running, we should be able to pass all the cases. Yes, don't forget to give semicalculus here, after that see one more thing and yes, wait for Java, I will also show you in Java also. This has become accepted, neither can you do it like this also, you will see what many people do, they do not write Lada separately here, they write it all here, the definition of very complex starts from here, is n't it? From here till the bracket, I hit copy till here and hit replace in Lada, that's it, the story is not over, now after seeing the code in others, you must be thinking, brother, what a great job you have done, that nothing has been done, this is the simple thing that I just wrote to you. This one was shown by writing, you can see how simple it was, I just copied and pasted it, here we have never been afraid of seeing other codes, you will break it, otherwise you will be able to understand what has been written, okay, this way I am just letting you understand. Otherwise, every tough code will seem easy to you, okay, this was just for your information, I am repeating it to you, so in this way we solved it in three ways, okay, now let's come to Java, so I will also code for Java. If I show you, then in Java, I will show you the map one, first int is equal to two words dot length, okay, now let's take a map, brother, what was there in the map, character, comma, integer, character, what is the meaning of which character, integer, meaning, frequency. What is its ok and let's name it New Hash Map What name have we given Sorry name we have given the count from here Ok new is the map created now let's start for string word in words will go to all the words And we will go to all its characters, whatever word it is, we are going to go to all its characters, so the word is in two characters array, right in Java, it has to be done like this to traverse the characters, it is okay, you are seeing the word in two characters. I have converted all the characters, I will get them one by one, okay, now I am putting the count, sorry put, sorry count in my map, see what I am putting, if it is already ready, then there will be + and in its frequency. Do it ok then for that the + and in its frequency. Do it ok then for that the + and in its frequency. Do it ok then for that the count dot get and default is ok. If it is already ok then if it is not there then put it. If it is there then just add plus to its frequency. It is ok till now it is clear for what to do now. All we have to do is count the int value in count dot values, okay count, go to all the values ​​of the map, I am checking all the values, I am go to all the values ​​of the map, I am checking all the values, I am go to all the values ​​of the map, I am checking all the values, I am checking the frequency, value model A is not equal to 0, then what to return is to return false. At last return true if you did not return false anywhere then it is ok, what happened with count dot values ​​that if you have values ​​in the map happened with count dot values ​​that if you have values ​​in the map happened with count dot values ​​that if you have values ​​in the map and this is the value then you will get all the values, let's see by submitting. Should be passed in Java also I want to show that the Lada C+ that I had that the Lada C+ that I had that the Lada C+ that I had used, is there anything similar in Java also? So let me show it to you. It is okay in Java, first of all I will show you once with the count. Count is equal. To new int 26, this size is taken, now you just have to put it in the count, here is the count of s - a + p. Okay, here is the count of s - a + p. Okay, here is the count of s - a + p. Okay, look at the same, c + p, we have done it in a single line with the corresponding lda, so can we do it here also. Can see how to return array dot stream function will be used for count is ok dot all match is there right as it was in c+ p there right as it was in c+ p there right as it was in c+ p here is all match ok c whatever comes my c module n must be It should be equal to 0, that's the end of the story, okay, so this thing is for your information, otherwise you could have created it in a very simple way with map and applied simple for loop, I have given these extra things just to give you information, okay I will submit it and show you. If you have any doubts, raise it in the comment section. Try to help me out. See you in the next video. Thank you.
Redistribute Characters to Make All Strings Equal
maximize-palindrome-length-from-subsequences
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. **Example 1:** **Input:** words = \[ "abc ", "aabc ", "bc "\] **Output:** true **Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ". All the strings are now equal to "abc ", so return `true`. **Example 2:** **Input:** words = \[ "ab ", "a "\] **Output:** false **Explanation:** It is impossible to make all the strings equal using the operation. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
String,Dynamic Programming
Hard
516
417
hey everyone in this video let's go to question 417 Pacific Atlantic water flow only code this is part of our blind 75 list of questions so let's begin in this question you are given our M by n rectangular Island that borders both the Pacific and Atlantic Ocean Pacific Ocean is basically touching the Island's left and top edges whereas the Atlantic Ocean touches Islands right and bottom edges here the island is partition into grid of square cells and basically the M by n integer array we are given the integer Matrix we're given represents the height of each of the cell basically you can think of it like this let's suppose we have something like this let's suppose this right here is the Pacific Ocean which is planting so let's suppose this is the Atlantic Ocean in red and then the heights is given like in the middle so Heights is basically you can think about like the height of the specific cell right so maybe this is like a mountain or like some region but it's like it has different heights at different locations right so this is what you can think of it now what is the question say so the question says that the island receives a lot of rain and the rain water can flow to the neighboring cells directly north south east and west of the neighboring cells height if the height is less than or equal to the current sales height what does this mean this basically means that suppose that maybe like over here suppose that like this cell gets water right the cell gets water with this cell gets water then it can go down here right because this is all like lower you can also like go all the way here it can go here it cannot go to like a higher place so you can't go like all the way up here but basically the water can go all the way down here and maybe you can touch the Pacific Ocean we can go all the way down here and touch the Atlantic Ocean and here again it touches the Atlantic Ocean Etc so let's read it again the island receives a lot of rain and the rain water can flow to the neighboring cells directly north south east and west of the neighboring cell's height if it is less than or equal to the current cells height and water can flow from any cell adjacent to an ocean into the ocean Okay so what does that also mean it basically means that like if it is over here if the water lick arrives here it can basically like arrive at the ocean so what do we want to do in this question well in this question we want to return the coordinates for any of the cells in which the rainwater can go to both the Atlantic and Pacific Oceans what does that mean so if you were to go back let me erase a lot of this so let's say we start off at this cell over here and maybe I'll just zoom in a little so let's say we start off at this over here if we go down this path we can reach the Atlantic Ocean maybe if we go down this path we can reach the Pacific Ocean there are different paths like this in which we can reach both the Atlantic Ocean and the Pacific Ocean but we want to return all of these cells in which they have this property now one thing you might already notice is that these Corners over here are like this corner here and like this corner down here and then this corner down here they were like okay I guess it's just these two actually they will obviously be part of this list because they are touching both the Atlantic Ocean and the Pacific Ocean so both of them so those two would definitely be as part of our list that we've returned but there will also be like many other cells over here that could potentially be our answer okay so what does this mean right like if you think about this one if you think about this Matrix that we have here think of this as like a matrix of heights right so if you think about this five here what it's saying is like from five where can we go well we can go from four and then Atlantic right here from five we can also go like maybe like four and two to the Pacific but basically you can understand that from this five cell we can reach both the Atlantic Ocean and we can read the Pacific Ocean right so that's like one thing you can notice similarly like from the seven here from the seven we can reach the Pacific Ocean here if you go down we can also just reach the Atlantic Ocean so there are certain cells that can reach both the Pacific and Atlantic oceans and we want to return these cells okay so how might we go about doing this well one way that I think and anytime like you see like this type of graph problem or like Matrix or anything like this like you might as well think of like DFS or BFS right like those are just like given so one thing that I can think about is what if I was to maybe like start off like maybe I can start off at like this one cell here and I can see all of the cells that I can visit right and if any of them visit both the Atlantic Ocean and the Pacific Ocean then maybe I can add this cell to my list of results I could do that but what do I notice here well I notice that there's going to be a lot of cells like that right because if this is an M by n Matrix so one two three four five this is like 25 cells so do I really need to go through those 25 cells I mean that is one way I could do it right like maybe I start off at this five and I see all the positions that I can reach and maybe it can reach the Atlantic Ocean and maybe you can reach the Pacific Ocean but do I really need to go through all 25 cells right is there an easier way if you think about this the easier way is actually why don't we just look at these cells over here these Edge cells over here so what I mean by that yes if I go over here and maybe let me zoom out and I'll paste it okay why don't we just look at these Edge cells over here these Ed cells I mean all of this for the Pacific Ocean and all of this for the Atlantic Ocean why don't we do a DFS call from here and see what are the cells that we can reach if we start from any of these positions so what might that look like well in the case for I is equal to this one so let's say we start off here right so what are all the cells we can visit well it looks like we can go down and remember this time we're just thinking in Reverse right here you would think about like going down or remaining on the same height but if we're trying to see all the cells we can visit from this one then it makes more sense selecting in the opposite directions like I want to go up right I want to go up so that's how we can think about it so from this cell we can reach this one because we're going up we can reach this one we can also reach this one right what about here well if we go down here then can we read the two no we can't because it's lower so we want to actually just go higher so we can't actually do anything from after we read the three here we're stuck what about from 2 here can we place can we go anywhere yeah we can actually reach this two and then we can reach this four we can reach this five we can read the seven Etc but basically what you see that I'm doing is that from all of these indices here I'm finding out all of the nodes that I can visit and if I know all of the nodes that I can visit on the Pacific side then maybe I can do the same thing from the Atlantic side so maybe from the Atlantic side let me see let's say I consider this 4 over here or from the 4 over here I can visit this four but I can't really go elsewhere right so that doesn't really help me from this one over here from this one I can see that I can visit the three here I can visit the four I could also visit the five now notice what this means it's five it can be visited by the Pacific like edges it can also be visited by the Atlantic edges if you think about what's happening here if a cell can be visited by both the Pacific I just add Atlantic edges that means that it's one of the answers to our question that means there's like a point like this that I can reach the Atlantic Ocean and it can reach the Pacific Ocean right so that's another point that we can think about what about the seven over here like how might we arrive at the seven well maybe if we start off at the Pacific we can definitely reach it because this one goes up and we arrive at the seven but let's see like how can the Atlantic arrive at it so Atlantic maybe it starts over here and then we can see if we go up we arrive at the seven so notice that now seven is being visited by both of them so that's something we can basically check in this right so that's how we're gonna go ahead and approach this problem we can do a DFS call from the boundaries of the Pacific Ocean and the boundaries of the Atlantic Ocean we can see the common cells that they visit and those will be our answer so let's take a look at how we can write this in code and the way I like to always do is types of questions so I'll just call this grid and the way I always like to do these types of questions so first of all we should check if okay so it looks like Eminem have to be greater than zero so we don't have to check for like any cases where we might be um like an empty grid but we can nonetheless the final rows and the final columns right with the final rows and we Define a columns now what okay so now I need to do my DFS call right but where do I need to do it from well I need to do it from a total four places first place it's going to be this first specific row here then it's going to be this first specific column the next place will be from this last Atlantic row and then this last Atlantic column so how can we do this so first let's see specific Pacific row let's see okay so pacific row we need to do it from specific column I need to do it from Atlantic row I need to do it from Atlantic column I need to do okay so for pacific row what do I need to do well I need to basically go through the first row so this will be I in range 0 and then we'll go through actually The Columns and then I'm going to do my DFS call right I don't know what I'm going to pass in yet but I'm going to do my DFS call but what do I need what is my row and call going to be or my row and column will basically be the row will be zero the column will be I right row will be zero the column will be I this position here the row is zero the column is 0 1 2. okay let's talk about specific columns so for specific column we want to go down this path so how do we do that well in this case we can actually go to the rows for I in range 0 to rows and then again myself.helper again myself.helper again myself.helper and my index will be well it's going to be the row which is I and the column which is zero okay cool now what about this one this last one for the Atlantic Ocean this last or maybe we can start off with this last row here last row how's this going to work well in the last row again we're going through the columns but what do we do what would uh what would the I and J be what would the row and column be well the row would be basically the last rows right so it would be rows minus one that would be the x coordinate and for the column it would just be I okay and finally we have this is the last column so how do we do this so in this case again we have four Iron Range zero We're looping through the rows because we already know our column so my self dot helper here what would it be well it would be the rule would be varying so the row would be I and the column would be essentially the last column so it would be cos minus one okay and so after we've done our DFS call here basically we can aggregate all of the cells that we visited in both of the like all four of these and both of the oceans actually and then we can arrive at our answer so let's take a look at how we might be able to do this okay so what do we need in our DFS call right so we have help helper we have grid we need row we need call what else do we need okay maybe it's important to also keep track of what we need to keep track of like the last cell we visited right because for example if we let me maybe remove all of this so if we are maybe starting off let's say we're starting off at this one over here right how do I know whether I'm allowed to visit this too or not well it depends on the height of this right and the height of the previous one basically my the current element the height must be greater than or equal to the height of the last one so I need to know like what my last value is so I'll say something like a last develop what else do I need to need well what else do I need to know well I don't know just yet but maybe let me start coding and then we can see if we need to know anything else okay so what are some of the other things we always do in these types of questions well we want to make sure we don't go out of bounds right so in order for us to make sure we don't go out of bounds we have our general formula that we like to use the first thing we do is we Define the rows and columns again and this could be passed in but like to keep our signature pretty like common pretty small so what can we do here we can check if rho is less than zero a row is greater than rows column is less than zero or column is greater than cause if this is the case then we want to basically not do anything we want to recurse back we basically just return from here okay what about another case well now I know I'm in the grid right but I can check if Grid at row and call if this is less than the last vowel well then I cannot like visit this right because I cannot go from like one to two this is not allowed so in this case what we would have to do is return okay so that's our second case that we have to return all right what else do we have well now I know that I can visit a specific cell right now I know I can visit a specific cell so why don't I just basically like cache this that I visited the cell why don't I store it somewhere that I visited to sell so maybe I can have like a scene array right a scene set and then what I can do is I can do scene or ADD and I want to add row and Co right but before I do scene.adder on call it's before I do scene.adder on call it's before I do scene.adder on call it's possible that like because it's the DFS we might visit the same cell again right and so we don't actually want to do that so we can actually check this we can check if row call in scene if that's the case then what well then we will just return right we don't want to do anything here now if I have all of this then the only thing I really need to do after this is recurse in all four of the other directions over curse left so let me just maybe fill this out what will it be grid roll call what would the last valve be or the last one will be the current vowel right great row and call and the scene will remain the same and we have to do this for all four directions so let's say we want to do left first and left the column decreases by one we want to go right the column increases by one if we want to go up the column decreases the row decreases by one if we want to go down the row increases by one okay perfect so this is our DFS call so what it will allow me to do is that from this one index here from this any location here or basically if you say all of the cells that I can visit I'll add them to my scene array or my scene set and then I will try to visit in all four of these directions so now what we need to do is figure out what to pass here right what do we pass inside of this okay so we actually know first of all we know grid we know rho here is zero column here is I what should the last value be well the last value if you think about it when we're just starting off then we want to make sure this is not false right now in order for this to be false this last value we need to actually make this the smallest value possible because then this will actually be greater than that so we will not run into this issue so I can just do float minus infinity right minus infinity and then now what do I need to pass in for scene we're seeing what do I need to pass it well I might just pass in a set here but if you think about it this set should be common to basically the Pacific Ocean right so I can do something like pset which means specific set and then I can also do a set which means it'll not take set so here I will just pass in ESET which will be the Pacific set specific set and then here I'll just fill these in so grid I zero float at minus infinity and this again will be a preset now fill this in but here I will pass in the Atlantic set I load minus infinity Atlantic set and same thing here I will pass in Grid I cos minus one load minus infinity and then the Atlantic set okay so what have we done so far so let's backtrack and see what we've done so far now we're doing a DFS call from this location and this location in our DFS call we are basically populating all of the cells that we can visit in the pset and in the a set what now what do I need to do well now I can basically just take the common ground right I can just take the cells that are in both pset and in a set now we can basically just do an intersection so this is kind of just um core python thing but basically all you need to do is I can do answer or res is equal to what would it be equal to well what I need to do is I need to add in I can do pset enter section Etc of aset and so what would this return to me this will actually return to me a set right it will actually return to me instead of something like um I don't know maybe like one and two three and four ex something like this right now we can actually return this as the answer our answer first of all has to be a list and it has to be like a list inside it can't be like a tuple like we have here so maybe I can call this like temp and then for my result what I can do is I can do four item in temp I'll do res dot append list version because it's going to be a tuple right I can do list of item and we just return so let's see if we can run this or if we run to any errors because it's quite a bit big like thing we have to do so okay so one thing is grow overrid and grow and call all right so I realized two errors that we made so first of all this one was hard to catch but basically the infinity here should be a negative Infinity the second thing here is that this is wrong actually row should be greater or equal to rows that's the case same thing for columns if that's the case then it's out of bounds we missed that as well now if we go ahead and run this let me go ahead and press submit I've arrive it at the answer perfect so this time complexity of this basically we're going through the entire array so it'll be o of M times n and also we are storing that basically in terms of space in terms of the set as well so at the worst case system okay perfect thank you for watching
Pacific Atlantic Water Flow
pacific-atlantic-water-flow
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`. The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_. **Example 1:** **Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\] **Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\] **Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below: \[0,4\]: \[0,4\] -> Pacific Ocean \[0,4\] -> Atlantic Ocean \[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,3\] -> \[1,4\] -> Atlantic Ocean \[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,4\] -> Atlantic Ocean \[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean \[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean \[3,0\]: \[3,0\] -> Pacific Ocean \[3,0\] -> \[4,0\] -> Atlantic Ocean \[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean \[3,1\] -> \[4,1\] -> Atlantic Ocean \[4,0\]: \[4,0\] -> Pacific Ocean \[4,0\] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. **Example 2:** **Input:** heights = \[\[1\]\] **Output:** \[\[0,0\]\] **Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans. **Constraints:** * `m == heights.length` * `n == heights[r].length` * `1 <= m, n <= 200` * `0 <= heights[r][c] <= 105`
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
3
hello everyone my name is kri Nandan and today we are going to solve the lead code problem longest substring without repeating correctors okay so let's read the problem statement so here it says given a string s find the length of the longest subring without repeating characters okay here uh if you hover over the subing it also gives the definition of the subing N a substring is a continuous nonempty sequence of characters within a string so the subing should be continuous what does it means like you can see example three here it has clearly said that the output of this example is three and I am assuming that this is the three character that is the output here so it says the answer is w k yeah this is the three character the Len of three so length is three that we already know notice that the answer must be subst okay so the ansers that we return should be a substring here PW ke is a subsequence not a substring okay so you can also try to make a substring and let's say if you take first character here p and you take three character from here right so this will be this will have a length of four and all the four character will be different but this is a sub sequence not subing and if you hover over it again it says uh continuous so continuous means if you take W right you need to take K just after that if there is a w again here then you cannot skip it simp in this case like since we have taken P so if we want to take a subring then we have to take this w we cannot skip this one so that's why this is a uh not a subam this is a subsequence if we consider this string all right I hope uh now you understand the problem now let's try to solve the problem so let's try to solve this very naive way okay so let's take a variable called result okay if I can type and the length is by default let's say it's a zero and let's run a loop so let's calculate the length first so we can say length S A String okay and here we can say for I in range length and then here we can also uh take a variable let's say temp and this is going to store the uh length of temporary substring okay and also let's take a variable called Serv W and by default this is going to be empty variable all right so let's run another loop for J in range and this will go till the end but this will start from I okay and this will go till the last length all right so here we are storing the subing uh let's make it a set actually and how let's say this is the cas because we need to just return the length so we don't need to return the string and set is fast if you are doing the search so what we can say uh we can check if we have seen this character that we are running on okay so we can say if s do I in cash or let's make the variable as just seen if we have seen this character then let's put a pass and let's write the else condition first if we have not seen this then what we are going to do we are just going to uh add the character into this uh scene set so we can say scene do add okay and we can add the character here uh J this should be J also and we don't need uh temp actually let's remove this okay and if we have seen this then what we are going to do uh we are going to actually break this so we are going to exit this Loop okay so we have not still uh since we have seen this so we are piing skipping the loop and here what we can do we can say if length of scene is greater than the result okay if it's greater than the result then we can say result will be the length of scene and I think that's it we don't need to do anything else and we can just re return the result okay so if we try to run this you can see all the test cases are passing right if I talk about that uh time complexity and the space complexity of this problem so let's put the time complexity and this is going to be the O of we are running one Loop and inside that we are running another loop so this is going to be the N square and space complexity since we are not using any uh extra space here we are using uh the space so let's say this is going to uh have the o n extra space because it may happen that the string uh the entire string doesn't have any repeating character so you will store every character into this one okay so that's uh that is fine but this is the very naive way you can see that I'm complexity is very uh not good so let's try to optimize this and let's try to solve it with another logic and so that we can reduce this time complexity okay so I have taken the uh first example from the problem statement and uh let's try to find out the solution okay the result that is expected from the sying is three okay so let's actually visualize how many subing we have who has the length three so we have first we have second one we have third one and we have fourth one so these are the four subing which is having the length three without any repeating character okay so from the problem I can see that we need at least two index to calculate the length Okay and uh to do this uh we need the two Index right so we can use the two pointer approach so here also I'm just going to use the two pointer approach and so for the two pointer I will need pointer 1 P1 and I will need pointer 2 P2 and when I start this Loop right my both pointer will be here at index Z so let me actually write the 0 here and uh from here from the start I will start calculating the result because may it may be the case that a every character is a so I need to return the one there so if I calculate the result so the result will be P2 - P1 + 1 because whenever you are be P2 - P1 + 1 because whenever you are be P2 - P1 + 1 because whenever you are using the index to calculate the length right so when you take the start index and the end index so you need to do the plus one because in case of this Z if you calculate right now 0 minus 0 and if you do don't do the plus one then you will not get the one as a result because your both the indexes are at the same position so we have calculated the result as one and if I talk about the subing then this is a but here we don't we need the subing without repeating the character right without any character being repeated so in that case we need to store the character that we have visited so let's create a c and we can store a here and we can put the character as a key and index as a value now let's move to the B and we will check if we have seen the B previously so we have not seen so we will update the B here in the cas and we will calculate the result so at B it will be 1 - 0 + 1 and this so at B it will be 1 - 0 + 1 and this so at B it will be 1 - 0 + 1 and this will be 2 and my subing is going to be AB this one all right in the next iteration uh our P2 will move to the C here index 2 and we will check if we have seen the C previously so we have not seen so we will update the c Index here in the C and we will calculate 2 minus 0 + 1 and this will give us minus 0 + 1 and this will give us minus 0 + 1 and this will give us three and now our subing is ABC so this is a valid subing once we move to the next pointer uh three I mean we move the P22 index 3 we will have this subing this entire subing okay uh a let me write it correctly a okay so this our subing is going to be this one okay now this is an invalid substring and we will if you check this last character right at index a we have seen this character previously so whenever we find a character that we have previously seen in that case uh this string becomes this sub string because becomes invalid and uh to make it valid we need to move the P1 and next position of P1 we can say uh let me actually put it here so we can say next P1 will be previous position of P1 and we can get the previous position of P1 by checking Cas of since we have found this one right so we can put the character here + one so this is here you character here + one so this is here you character here + one so this is here you can see the index for 0 so 0 + 1 is 1 so can see the index for 0 so 0 + 1 is 1 so can see the index for 0 so 0 + 1 is 1 so the next position of P1 is going to be here at index one and now uh we can calculate the results so to calculate the result we can say 3 - 1 + 1 this will give us can say 3 - 1 + 1 this will give us can say 3 - 1 + 1 this will give us three and subing will be b c a and since we have recalculated the uh we have again seen the uh position of a right uh I mean we have again seen the this character a so we need to update the index of this a so index of this a was Zero previously so we will put three here okay we will repeat the same again so let's try to go to the next character that is B and this will be four so our subing is going to be in this case this one and B this is an inval sub and B we have already seen here in the cas so what we will do whenever we find repeating character we calculate the next position of P1 and if I try to calculate the next position of P1 so the previous position of B was one and then one so this will be two so next position of P1 is going to here okay now we can calculate the result so result will be 4 - 2 + 1 and result so result will be 4 - 2 + 1 and result so result will be 4 - 2 + 1 and this is going to be 3 and Subs that is giving this result is cab and once we have calculated the result we need to update the index of B so index of B was 1 now it will become four so we have a index as a four and uh next let's move to the next character C here and in case of C uh it was for so yeah it this index will be five so C we have already seen here in the cas so whenever we find in the as we calculate the next position of the P1 so this will be position previous position of C + 1 so this will be three position of C + 1 so this will be three position of C + 1 so this will be three so we will move the P1 to here 3 and since we have moved now we need to calculate the length so this will be 5 - calculate the length so this will be 5 - calculate the length so this will be 5 - 3 + 1 and this will give us three and 3 + 1 and this will give us three and 3 + 1 and this will give us three and the output will be a b c so this is the subing and we need to update the current index of the C so current index of the C is five let's move this to uh next position that is six and if we check we have already seen the B so what we will do we will calculate the next position of P1 and how can we calculate the we can get the previous position of B that is 4 + 1 so previous position of B that is 4 + 1 so previous position of B that is 4 + 1 so this is five so next position of P1 here you can see it's not moving One Step it's actually taking the previous position of the B so this will move here so P1 will go to the five and now we will calculate the substring a value substring that will be 6 - 5 + substring that will be 6 - 5 + substring that will be 6 - 5 + 1 so this will give us 2 and these two will be uh these two subing will be C and B now we will move one step ahead P2 will go to the 7 and again we can uh okay so I forgot to update the position of the B so position of the B here will be six now we if I move to the B right I will check if I seen b previously so I have seen the B previously so I will create the next position of the B of the P1 so it will be 6 + 1 that is 7 so this P1 so it will be 6 + 1 that is 7 so this P1 so it will be 6 + 1 that is 7 so this will move to here only and now if I calculate the sub string this will be 7 - 7 + 1 and string this will be 7 - 7 + 1 and string this will be 7 - 7 + 1 and this will be uh 1 and the sub string is going to be B all right so these are the subing and if I take maximum of every result right so the output will be three okay so this is how we can calculate the uh result let's try to handle uh one more substring where I think there will be a problem so let's say the string is going to be uh let me use different color let's say the string is a b a okay and output will be two for this case and if we try to find our substring this is a valid substring so there are two substring that is valid and we can put the cash here and we have a P1 and we have a P2 so P1 is here P2 is here if I calculate the result will be 0 - 0 + 1 this will the result will be 0 - 0 + 1 this will the result will be 0 - 0 + 1 this will be 1 and our subing will be a and our c will store a z and if I move the P2 to the next position so this is 0 1 2 3 so this is 1 so we have not seen the B so we will put the B into the cas and now this will be 1 - 0 + 1 and that will 1 - 0 + 1 and that will 1 - 0 + 1 and that will be two and our sting will be AB okay again I will move to the B and this P2 will go to B so P2 will be here at index 2 now I have already seen the B so what I need to do I need to calculate the previous position I mean I need to calculate the next position of the P1 okay so P1 next so we can say this will be Pro previous position of the B and that was 1 + 1 so this will be the B and that was 1 + 1 so this will be the B and that was 1 + 1 so this will be two so this will uh this will move to here okay and we can calculate the result so result will be 2 - 2 + result will be 2 - 2 + result will be 2 - 2 + 1 okay so this will be 1 and the sub string will be B okay and we will update the current position of the B and that is going to be 012 so this is going to be two now if I go to the a right what will happen have we seen the a previously yes we have seen the a previously so what we are going to do we are going to calculate the previous position of a next position of the P1 okay so the next position if I check for P1 then this is going to be previous position of a that is zero and plus 1 so this is going to be 1 so here the next position of P1 will be calculated at this one but this is not a valid position so whenever we create a next position of the P1 right we need to make sure that this is not less than the what we what the P1 previously had so in that case we will ignore so this is less than this one right previously it was at two so P1 was at two uh and P1 next is 1 so P1 was 2 and P1 next is at 1 so P1 is greater than P1 next so we will not move the P1 anywhere okay so in that case P1 will be here only and P2 will move to this one a so P2 is at a so we will calculate the length so this will be 3 - 1 + length so this will be 3 - 1 + length so this will be 3 - 1 + 1 uh no so it's here so 3 - 2 1 uh no so it's here so 3 - 2 1 uh no so it's here so 3 - 2 + 1 and this will be 2 and our subing + 1 and this will be 2 and our subing + 1 and this will be 2 and our subing will be B A of length two okay and we will update the length of a that is 3 so this is one base condition where you have such string so you need to make sure that whenever you get the position of the P1 right that should not be lesser than what we previously had so this should always be greater than what we previously had okay so I think this makesense s so let's try to actually write the code for it and uh let's try to run if we can uh find the expected output in lead code so let's remove the previously written code and we need the result apart from that we need two pointers so let's say left and this is zero and we also need the right pointer this is also zero and we need the C where we are going to store the characters okay so uh let's run a loop so we can say for C in s or we can let's say enumerate s and here we can get the right pointer so we can remove this okay and we have these things now we need to check if we have already seen this character so we can say if C in Cas that means if we have already seen and there was one more uh condition that we need to make sure that the next pointer of the left is not less than the current so we can check that by getting the current uh position of the character and making sure that this is greater than or equal to the current left okay so this is fine now we have considered the other case also and uh now let's if these two cases satisfies we can set the position of the left pointer so for that we can say cash current position of the character and we can do the plus one okay and once all this done we can calculate the result by saying the max of previously what we had and uh then we can do the right minus left and + 1 okay can do the right minus left and + 1 okay can do the right minus left and + 1 okay and now we need to also update the index of the character that we are seeing right now so for that we can say case of C this will be the current index that is right okay once all this done we can just return the result I think this will be the final solution okay let's set uh see the time complexity so you can see we are running a loop uh only one Loop so this is not going to be the N Square this is going to be the n and space complexity so we are using the cas right and uh if the let's say in case of ABC BB in this case obviously we will have only three character in the cas and it will keep updating the indexes but maybe there is a string given like a b c d e f g h i j k there is no repeating character so in that case we will store everything in the cas so in worst case we can say the space complexity is going to be the O Okay and let's run the code and see if it works okay uh all the test cases are passed so let's try to submit this okay so this works perfectly fine uh so thank you so much for watching this video uh if you're new to the Channel please click on the Subscribe button and uh thank you so much for watching and I will see you in the next one
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
330
hello everybody and welcome today we're going to discuss the solution to the problem patching array it's a hard table problem although does not require any knowledge of data structures or algorithms it just requires you to understand the logic and a couple of observations will help us get there first let's discuss about the input output given a list nums which is a list of integers and you're given another integer n now the goal is to design a function that returns an enter at the end this end represents the number of patches now you have to somehow modify or look at the nums list in such a way that you can generate this ranging of events from 1 to n okay this is a bit confusing so let's actually look at a sample let's take a look at this sample here where we have 1 comma 3 as the list of nums and n as the target now initially what is the sort of number of generated numbers in this case it's three numbers generated one three and then a combination of both of them obviously this does not cover the entire range from 1 to n we need 2 5 and 6 all of them together here also so one of the possible patches is going to be adding two this means that the nums are a is now going to look like 1 2 3 which can now generate 1 2 3 4 5 6. feel free to write it down on your own and enumerate all the possible combinations of these sums they're going to give you the range 1 to 6 which is what we wanted basically one patch was able to get us to the right answer and so we'll return 1 as the answer for this case now let's look at a couple of more examples and we'll forget about the patches part for now and understand the core observation behind this problem we have the nums list again and one two three given this time now we want to discuss what the range of these nums is basically from start to the end what is the contiguous range of element it covers basically 1 to 6 is just a mathematical notation meaning that we have element 1 2 3 4 5 and 6. simple and so one two three will have the range from one to six one two three four well again at this point of time you can pause the video try and enumerate everything on your own and you'll find that the range is from one to ten more simply you can also look at one two three since that covers everything from one to six adding four to that list just increases this upper limit by four so you can see four added to six gives you ten in another case like one two three seven you can observe the same thing happening the range just go goes and increases by this amount so original list was one two three as soon as we added seven at the end the range now increased from 6 to 6 plus 7 which is 13. now the question we want to ask is it always the case in this case right here 1 2 3 8 is the answer 1 to 14 am i covering every single integer from one all the veptil 14 both inclusive if you note right now what's happening is we have one two three 5 6 given by these three numbers here but there is no integer 7 here there is no possible combination of all of these which can make you the integer 7. so this is actually incorrect what's happening here well we've sort of split it out into these two cases here the case where you can directly add this new element and just increase the range by that element or maybe you can't increase the range by that element and in that case you'll need to patch this list on your own like in this case we added the patch of two this is the entire solution to the problem in fact we'll look at one and two three again and their upper limit is six and we'll keep that in mind now we ask the question is the current element which we want to include maybe it's four maybe it's seven is the current element less than equals to upper plus 1 is this current element inside of the range is this current element upper plus 1 is by the way 7 right now is this element less than equals to 7 and so all of these cases between like four five six seven are going to get included here and so we'll do this computation we'll just simply extend the list we'll simply extend the range upper now becomes upper plus the element basically 13 is what 13 is the old range 6 plus the new element 7 and so we have done this upper plus equals to element and once you've figured out once we have added the seven element just go on to the next element and look at the same logic pretty easy what if that is not the case in this case right here what if it was one two three eight as we discussed we needed to patch in this case before it we can't go forward if that were the case see what's actually happening is we want this to have like a continuous sort of range you could write it 1 2 6 inclusive and then 8 to 14 inclusive but the 7 in the middle is going to eat you up so we'll actually go ahead and patch this up include the 7 right now at the cost of 1 and the upper goes up by upper plus 1. wait what okay so as soon as we include this element 7 uh what happens to the answer upper was 6 initially we checked this the current element is 8. now 8 is not less than equals to 7 which means that we're going to go in this path element is currently the 8 and the upper plus 1 is 7 and so we want to patch this up we want to insert the element 7. now we insert it at a cost of 1 and now since we added this element 7 which is going to be upper plus 1 we can now retry this logic and we can again go on and continue on the same if statement and that is pretty much the solution okay maybe the code will help you understand it better but it's mostly like a pretty complicated problem you need to write it on your own and uh only then you'll fully understand what's going on anyways we'll actually code this up and maybe that helps so we'll have i equals to zero i basically uh going over all the nums so what's the big condition here the entire goal of this problem is to reach a state where we are one comma n so this n is sort of the upper limit goal when upper limit when upper is going to be less than n we have to do some computation when we haven't reached n yet when the upper limit of our all of the combination sum has not yet reached the n out there we want to do some computation if we have reached there however we can just return uh the cost of whatever it took to get there okay now we'll write the if condition if element uh what is the element less than equals to upper plus one so we'll write element less than equals to upper plus one uh element by the way is what element is the current number we're pointing at and uh just for a quick sanity check we'll also ensure that i is always less than the length of nums otherwise it will go out of bounds okay we'll do some computation in this case the green case else will do some other computation in the red case okay so what's the computation here upper plus equals to element so we'll do upper plus equals to element which is nums of i and i plus equals to one we'll move on to the next element now else what do we do well obviously in this case we need to patch this up so cost goes up by one at the same time upper gets increased by the whatever element we have patched the element we are going to patch is upper plus one and so this follows the entire condition we're going to retry and try out the if statement again and only if it succeeds we are going to go to the next element so on and so forth we can go over this entire thing and we are done with the code now uh feel free to again take a break look at this logic right here and understand what's going on we'll also discuss quickly the space time complexities so it looks like it's going to be order of n but is that always the case we aren't increasing upper by one each time are we're either increasing upper by this guy numbers of i or we're going to increase it by itself this actually hints at what we have seen like this is just going to go to the twice its value so it looks like maybe we are looking at something on the order of log n and this statement looks like uh we may have to or we actually have to go over all the elements so this is order of m okay what's the total complexity then well we either go to this if or this else so the total complexity in terms of time is going to be m plus log n m representing the length of the list nums okay this is the time complexity what about the space complexity well we haven't used anything other than these three variables here and that is it three variables as the space complexity or a constant space complexity anyways this is it for the solution of patching array i know it's a hard problem and it's a mathematically sort of dense problem requiring you to look at a lot of cases understand where it breaks down and finally figure out this beautiful looking if condition anyway this is it for the solution and uh if you like this video be sure to give it a thumbs up if you don't like it give it a double thumbs down really let me know if you have any comments feedback suggestion i'm always there in the comment section below and as always thanks for watching
Patching Array
patching-array
Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array. Return _the minimum number of patches required_. **Example 1:** **Input:** nums = \[1,3\], n = 6 **Output:** 1 Explanation: Combinations of nums are \[1\], \[3\], \[1,3\], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: \[1\], \[2\], \[3\], \[1,3\], \[2,3\], \[1,2,3\]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range \[1, 6\]. So we only need 1 patch. **Example 2:** **Input:** nums = \[1,5,10\], n = 20 **Output:** 2 Explanation: The two patches can be \[2, 4\]. **Example 3:** **Input:** nums = \[1,2,2\], n = 5 **Output:** 0 **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `nums` is sorted in **ascending order**. * `1 <= n <= 231 - 1`
null
Array,Greedy
Hard
1930
224
in this video when you look at an equal problem called basic calculator so given a string s representing a vowel expression uh implement a basic calculator to evaluate it and return the result of evaluation you are not allowed to return any or use any built-in functions that evaluates any built-in functions that evaluates any built-in functions that evaluates the string as a mathematical expression such as eval so you can see here we have an example of one plus one right it's basically inside a strain and you can see here we could have space here there could be no space in between a symbol or an operator so and at the end we want to return an integer value which is basically the result right the result of the evaluation right so you can see here we're returning an integer two um so and you can also see here we have another example right where we have like spaces and then we have two minus one right which is one plus two is three so therefore at the end we're returning three right and there could also be like brackets um in our strain as well so if we have a bracket what we have to do is we have to do what's inside our bracket first right so let's say we have an example like this then first what's going to happen is that we're going to get the sum inside the inner bracket in this case 4 plus 5 plus 2 which is going to be 11 right and then what's going to happen then is we're going to get this the results right of this bracket so in this case what's going to happen is we're just going to get 1 plus 11 right which is the sum of this right here and then which is 12 and then 12 minus 3 which is basically 9 right so once we have that we're going to complete what's inside the bracket so in this case 6 plus 8 which is 14 right and then 14 plus 9 in this case is basically uh 23 right so therefore at the end we're returning 23. so and then there could also be like i said there could be negative value as well so in this case it's basically 45 minus 40 sorry 48 minus 48 in this case zero right so number can have multiple digits that starts with plus right a positive value or a negative value constraints is that you can see here for each for the string right the length of the string will be at least one character and the string will contains these symbols uh we could have mt strip we can have empty spaces right we can also have digits right valid expressions all the strings are valid expressions and uh every number and run a running calculator will fit in the 32-bit integer so in this case how can 32-bit integer so in this case how can 32-bit integer so in this case how can we be able to solve this problem so to solve this problem we know that we have to complete what were in this case get the result of evaluation for the inner brackets right before we can be able to complete the outer brackets or what's in the outer brackets so in this case you can see here we first complete the inner bracket which is 11 and then what we're going to do then is we're going to complete the outer bracket in this case the current bracket right and then which is nine and then once we complete the current bracket we also have to complete the other brackets right we have to complete the what's inside the bracket first right and then in this case six plus eight which is going to be 14 and then once we get the sum of this which is basically 23 right so in this case what we have to do is we actually have to do something like a stack we're using it like a stack data structure or dfs right basically we're trying to do is we're trying to complete what's in the brackets first right so what we're going to do is that we're going to iterate the string character by character once we visit a bracket we know that we have to complete what's inside first before we continue so we can do is that we can do a dfs and this dfx function basically trying to complete or get the result return an integer value of the um of the sum right of the result of the total value for what's inside the brackets so once we uh complete what's inside of brackets we're going to backtrack to the um to the outer brackets right to what's outside of brackets and then we can because now we get the sum for or in this case the total value for what's inside a bracket we can be able to use that value to continue to um get the total value for what's outside of the bracket right now we know how we can be able to like solve this how can we be able to like get the sum right let's say we have four plus five plus two how do we get this sum so in this case to get the sum um what we have to do is we have to first of all iterate through the list right or in this case a string and then if in this case we're going to have a variable right so in this case we're going to have our sum initially equal to zero once we visited a curtain the first character in this case the first character is a digit right well there could also be another situation where we could have 45 you could have a 4 500 right there could be a long list of numbers so what we have to do is we have to iterate through right while the current digit while current character is a digit we're going to basically append it to a string and then while the current is not a digit we're going to basically um convert the current string into an integer now number right so what's going to happen is that once we convert this through to an integer number which is four we add it on to the sum right and then what we're going to do is we're going to move on to the next character in this case is the operator so we have news that we have to use a another variable like maybe like an operator right um to keep track of the current operator because once we visit the next element what we can do is that we can use the nest we can use the current operator to change that right so in this case right now it's a plus so we can have a plus one if it's a minus that symbol we can have a minus one right or a negative one value so what we're gonna do is that we're gonna move on to the next character so we have a five okay so what we're gonna do is that we're going to get sum right so sum is equal to sum plus the current num right which is 5 times the operator in this case it's basically four plus five right which is basically nine so in this case we'll just have nine here right now let's say we have a negative one here or negative two here or minus two here so once we get here we have negative two right so sorry we have a negative one so we make the operator negative value so that once we get to the actual value right in this case what we're gonna do is we're going to um just like i mentioned before we're gonna get sum right which is 9 is equal to sum plus the current num right which is negative 2 right uh sorry just 2 and then times the operator which will convert it into a negative value so we have a negative two value right so the sum is nine plus negative two which is basically um in this sorry yeah in this case sorry nine plus negative two is basically seven right so in this case the sum is seven right so basically you can see that this is basically how we're going to get the sum right for within our current brackets so now we know how we can be able to um solve this problem let's take a look at the code so the code is pretty simple i basically use dfs to solve it you can use a stack basically first we convert it into a character array and then we're going to have a index that's starting from the first element right starting from the first we're starting from zero and then first inside our dfs right we're going to traverse this the string and then in this case we're going to have our sum in this case zero operator is one right basically is positive value right so initially we're basically gonna have a positive value um and then what we're gonna do is that while we're while the sum was in the current brackets right while we're going to basically going through our current brackets right so it could be something that was out of bracket right um for example like a value like this like one plus one in this case there's no brackets at all that we just continue right so there's fourth there's a couple things we have to check right one is if it's a closing parenthesis then we just have to break if it's an open parenthesis then we just have to increase the index by one right and then what we're going to do is that we're going to um basically do our dfs we're going to have operator times dfs function remember just like i mentioned it will return us what's the total value of what's inside of brackets right so we're going to use that times the operator plus the current sum just like i mentioned right we'll update our current sum now why we move index by one because the current position right like i mentioned the current position is a bracket right if it's an open bracket then we don't want to visit that again we want to make sure we index plus we're moving on to the next character which is we're going to start from here and then we're going to move forward right we want to get all the value we want to get the sum we want to get the total value for what's inside our bracket right so in this case what we're going to do is that we're going to do our dfs right and then let's say we have a negative value right so in this case array index is a negative symbol then we just have to make the operator into a negative value right negative one and then same thing if it's a positive value we just have to make it positive one and let's say if the current digit right the current character is a digit so we're gonna do so we're gonna form the number right just like i mentioned we're gonna use a string builder while you know while the index is less than a rate that length and then character dot digits the current so current character is a digit what we're going to do is we're going to basically append this character onto the stream builder and then let's say somehow that this current character is not a digit what we have to do is we have to go back right go back one by one um because now is basically where this is the current index is pointing to a digit right in the array so now we have to do is we just have to convert it into a number so all we have to do then is we're basically just going to convert a string into an integer times the operator right this will basically give us the um the number right the actual value and then we're just gonna um basically update the sum okay and then as you can see that for each and every single iteration we're gonna increase the index by one and let's say there's a situation where in this case we have a space if we have a space then we just have to continue right if there's any other characters then we're just going to continue right but of course like the question says the string is a valid expression right so what we're going to do is that we're going to continue to do that until we have our index where we basically uh either we have a closing parenthesis then we just have to break we just have to return the current sum right this is basically um all the values where the total sum for current uh within the current brackets or if the index is beyond the array.life if the index is beyond the array.life if the index is beyond the array.life right if there's no brackets at all right for example like one plus one no brackets at all we basically iterate and traverse the entire string then we just have to return the sum right so in this case there could be two just like i mentioned there are two situations that will break the loop one is we can have a closing parenthesis or the other one is we can uh go uh the current index go out about right and notice that the current index is based or the index is actually a global variable right so once we're going our dfs the index is still moving right and then once we come back to our dfs back to the uh the parent stack we want to make sure we are using our operator right either is a negative value right i could also have a negative value in front of it right like i could have a negative value in front of it too right so if it's a negative value then we just want to make sure the operator times the result of our dfs right and then update our sum right so you can see that this is basically how we're going to solve the problem time complexity in this case is big over n and then the space complexity in this case is also going to be big o of n right so you can use a like an actual stack data structure or you can also do a dfs but either way the space complexity will be it will be big oven
Basic Calculator
basic-calculator
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_. **Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "1 + 1 " **Output:** 2 **Example 2:** **Input:** s = " 2-1 + 2 " **Output:** 3 **Example 3:** **Input:** s = "(1+(4+5+2)-3)+(6+8) " **Output:** 23 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`. * `s` represents a valid expression. * `'+'` is **not** used as a unary operation (i.e., `"+1 "` and `"+(2 + 3) "` is invalid). * `'-'` could be used as a unary operation (i.e., `"-1 "` and `"-(2 + 3) "` is valid). * There will be no two consecutive operators in the input. * Every number and running calculation will fit in a signed 32-bit integer.
null
Math,String,Stack,Recursion
Hard
150,227,241,282,785,2147,2328
404
hey what's up guys is Nick white I do a lot of tech encoding stuff on Twitch in youtube if you're interested in anything about me just check the description I have everything they're doing all the Leko problems all 1,000 that are up Leko problems all 1,000 that are up Leko problems all 1,000 that are up right now so I've about 50 on a playlist on my youtube channel so if you want to check those I explain each and every individual problem and we're getting into even harder problems here so right now we're doing some of left leaves okay this one's easy there this one's called some of left leaves find the sum of all left leaves in a given binary tree well what is a leaf so a leave in a binary tree is a what is a child that has no left or it's a node that has no left or right child node so we see that a left leave is going to be a left node it's a left node the left and it's gonna have no children nodes right so 9 and 15 are the only two left nodes with no children nodes here so how are we gonna do this well we can do it early or we can do like a DFS recursive solution we'll do the DFS recursive solution first so first of all if we're dismal than the sum of all the left leaves this is nine and fifteen so it'll be 24 in this case the sum is gonna be zero if the roots no because we have no tree to traverse and there's obviously no left leaves otherwise we can declare our initial sum so some of left needs will be set to zero and then what we're going to want to do is if I'll explain this in a second no table left is not equal to null then we'll do then we will increment our counter or some sorry some of the leaves will plus equal so what why are we doing this well if the no doubt left is not equal to null so we start with our root at 3 so if left is not equal to null then we see 9 then we have a left node that's one of the conditions we need now we need to check if that node has no children so we do if no doubt left our left equals null and it is and no doubt left out right is equal to not so no down left up right is nothing to so if it's child with no children then we can add it to our sum because that's the whole point that's what we need in our song otherwise they're still gonna be left notes that have children so in this else case we have a left node that has children we're still gonna want to recurse on those children because later along the lines we can keep traversing down these children nodes and eventually maybe find another left so all we have to do to recursively add the to the ongoing some a recursive call of some of left leaves on root dot left ok actually yeah we've been using root this whole time so I actually only put the word note so just make sure you don't do what I'm doing make sure you don't stink sorry for being loud I'm in the library so just keep that in mind now what about the right notes well if we find a right node that has children then we're gonna want to keep traversing on that if we find a right node with no children you don't want to keep traversing cuz that's the end of the road for that one so let's just account for that keep no doubt right is not equal to null so if we see a right node and then our condition this time is a little bit different if no doubt rights left is not equal null because we want children now or no dot right is not equal to null then we'll keep traversing because if it asked children if it has children we can keep going and we might find more left node so we just add this to our ongoing some as well some of left leaves plus equals some of left I keep dude I even said that I shouldn't use node and I've kept using no sorry and then we just return our sum so some of what flew sorry this is a little bit of a sketchy I have a lot of talking around me distraction so it's kind of a sketchy ending error not a statement 0 in sum of leaves equals 0 return 0 sorry if the root is only return 0 would be the sum of the left weeks what is this fine 22 semicolon this is a really bad tutorial sorry ok there we go that's a success hopefully you guys understand why we to do that now it's to the iterative solution we're still gonna return zeros are some if and we'll keep our initial songs set up here we're still gonna return zero as our sum if the word is null because we have no tree to recurse on then we have our initial sum and then what we need is a stack of tree notes like every iterative tree solution because basically what happens is in recursion you use stack space when you're calling doing recursive calls but in an iterative solution we need an actual physical stack so we have a stack of tree nodes equals new stack will add our roof to the stack immediately so stacked our add root and then just like all these other problems Wow the stack is not empty will pop a note off this is one I was using node equals stack out that's how I got confused last time and then all we have to do is these same things so if no got left is not equal to no just like we're doing the recursive call if node I left then we add that to our song otherwise we wanted to keep traversing so instead of a recursive call this time we're just gonna do stack dot add node out laughter keep traversing if it has children and then the same thing for the right note is last time so if no doubt right is not equal to null if no dot right left is not equal to null or no doubt right dot right it's not equal so if the right note has children we're gonna just keep traversing on stack got add node of Rights adding to the stack helps us traverse because we're popping a note off each time and traversing on all the children and then after the whole loop we've at incremented our son with all the left node values and then all we have to do is return left weeds there we go that's the answer hopefully it works first try does we didn't have any syntax errors this time that was the iterative solution hopefully guys understood how that works we basically just Traverse on all nodes that have children we keep traversing we traverse the whole tree in any left node that we see with no children we add it to an ongoing song it's pretty straightforward for some of left leaves look at the solution practice and please check out my other one sorry for the shaky explanation a lot going on around me and sorry for the noise there's a ton of people down all these other videos so please go check those out thank you guys for watching please let me know in the comments what I can do better see you guys
Sum of Left Leaves
sum-of-left-leaves
Given the `root` of a binary tree, return _the sum of all left leaves._ A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 24 **Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively. **Example 2:** **Input:** root = \[1\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
383
hey hello there so I'm going to talk about today's recording challenge question it's called ransom note so the question is as follows we have a betrayal rear ends and no string and another string containing all the letters from the magazines and we want to write a function to determine whether we can construct the ransom note using the letters we have in the magazine so it's at front fluence question and I guess this is just the letter C in the magazine can be used only once in the ransom note that's because when we cut the letter from the magazine it's gone so we then we pasted that letter onto the piece of paper to form the message I guess to avoid the handwritten you know being recognized by the police so it makes sense in this kind of settings so the solution is quite simple we're gonna convert the string Magelang string into a hashmap BD with the keys being the characters and the value being the number of times that we can use it the maximum number times we can use it which is equivalent to the number of times that the letter appeared in the magazines and then we're going to do once one pass through the ransom note and for every letter we're gonna check whether we can use one we have enough letters in the magazine to cover that if we find a violation along the iteration through the node we can return false early otherwise we will when we finish the processing the ransom note we can return true in the end so that's much the solution it's a pretty elementary algorithm question testing the usage of hash marks so the time complexity is the length of the ransom note plus the length of the magazine string so that's those two together and first place is C the number of unique characters in the marketing so that's the timeless space pretty simple we're gonna create a hash map which is supported to integer the frequency count for the characters in the marketing string let's call it a character frequency and we're just going to for all the characters we're just going to increment it's a frequency count in this hash map and then we go through the note just once so here the logic is that of course we want to decrement that the frequency count because we use that letter at least the ones or for forming the ransom note so we want to have to decrement this but we want to test the whether we have enough before we do the documentation so if either we don't have that character that's or if we have it but we just don't have enough which means that they we have zero then we just return for us if we successfully forming the ransom note by you know character by character we get a piece of character from the magazine and use that to form the ransom note if we can successfully done that return true yeah so this is the code it's a pretty simple let's see the test cases this is false this is true again okay yeah okay it's kind of slow today the website yeah so that's that question pretty simple
Ransom Note
ransom-note
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_. Each letter in `magazine` can only be used once in `ransomNote`. **Example 1:** **Input:** ransomNote = "a", magazine = "b" **Output:** false **Example 2:** **Input:** ransomNote = "aa", magazine = "ab" **Output:** false **Example 3:** **Input:** ransomNote = "aa", magazine = "aab" **Output:** true **Constraints:** * `1 <= ransomNote.length, magazine.length <= 105` * `ransomNote` and `magazine` consist of lowercase English letters.
null
Hash Table,String,Counting
Easy
691
501
hey everybody this is Larry this is day one of the October November Lial day challenge I'm here on top of Mount OS Shak T I'm there's no way I'm getting it right but I'm in uh in the mount asso area and basically just looking at these beautiful views and I finally climbed this hike uh and climb this Mountain hiking it and that's all I have uh let me know what you think and yeah hit the like button and subscribe and join me on Discord and you could actually see me solve the problem now hey uh yeah uh so let's get started uh I'm in a private Airbnb that's also a BNB so I'm ready uh and also this is day one so let's get started on day one uh welcome everybody I hope you like the intro um yeah hope you like the intro I forget which intro I have these days I'm kind of all over the place um but let's get started find mode in a binary search tree uh but yeah I'm in a pivate B&amp;B and tree uh but yeah I'm in a pivate B&amp;B and tree uh but yeah I'm in a pivate B&amp;B and it's kind of very nice and yeah this elderly couple just kind of feeding me everything it's been really nice here in uh in Mount asso area in Japan all right uh if you want more about that follow me on Instagram I'm going to just finish this problem hopefully find mod in a binary search tree H I'm trying to think whether there's a shorter weate that's not linear eh I mean impit stack is kind of silly like if it doesn't count then I don't know I mean okay that's just like a programming implementation trick at that point it's not a actual Fury thing um because I was going to say like you can't do better than linear space or at least or h space um I mean I guess the so the obvious thing to do is just to do a linear time frame with respect to look at everything um can we take advantage of the fact that it's binary search tree I guess you can do some like really incremental things with respect to you know like uh if the biggest element on the side is you know the same as the element the right or something like this is the same then you know you can skip ahead a little bit but at the end of the day and I guess you can do some like pruning if you really want to like if you know that the mode is already like you know like if your current mode is four items and you know that there's only three items in the sub tree um someone like that but trying to think how else would you take advantage of the search tree I know this is a easy and maybe I'm overthinking it a little bit um these are things that I would consider in terms of extra space can I do that with on the stack I mean yes I mean the answer is yes but you just it's just like an implementation thing I believe cuz all you do is just return the element and the count and something like this and then kind of propagate it all the way around um all you really if you do I guess that's the one thing about binary search tree that I guess I didn't that is not um a regular search tree is if you do an in order traversal then you have all the numbers in order so then the mode would come out in that way so okay fine maybe that is a thing that's what they mean and I guess I'll implement it that way um now but so that is a thing that is different than a regular binary tree but I was just yeah I don't know that's a little bit weird I mean maybe uh yeah I don't know if there's anything more than that so uh yeah I think that should be okay so let's get started then um yeah so I mean and you could even do this on the stack but I'm lazy so I'm just going to write it on outside so best is equal to none count is or best count is equal so best is the element and wait what is the why is output in way oh you have to return all of them okay that's a little bit awkward okay fine so then uh okay right I mean it's fine and then now because you're doing in order then you can do them one at a time so I guess that's what they may be asking for um for me it I mean I don't know I mean it is what it is I guess so count isal zero uh node is equal to none maybe right then now you do in order of a node uh so we do in order R and then we return best right and then if no is none we return we want to do in order of left or no. left no. right and basically here so left and then we do the current node because this is in order right then now if oh this is terrible huh I think I made that same mistake last time or like yeah current node is equal to uh current node. value is equal to node. Value then current count increment by one right and then if current count is greater than best count best is equal to um uh was is it no do Cent no. value do return the notes or the values okay yeah well I guess doesn't make sense to return the note I think this I think you could I was going to say you could probably save um a non loo you just clear and then add but at that point is the same right so yeah um yeah I think that's still true even as you go down okay and then else if current count is equal to best count best. Curr value and I think that should be oh no um I mean this is mostly good but then notur is equal to one and node or current node is equal to node. Value um I guess current node is a no oh because it can be none because my Sentinel is lazy um I think I just do the way that I wrote it because I do the check separately um hope this is right I kind of made some unnecessary Sentinel value so we'll see uh oh yeah there you go yeah oh I am dumb oh this is not related to that well I mean this is related to the dumbness but um I just kind of forgot about that part okay fine wow I am very silly today getting uh um that's C yep uh not going to lie this is very great Lighting on my face but uh I am still Wasing a little bit because I'm getting very um I'm getting excited because I'm going out for a hike right afterwards so definitely watching a little bit and last time I got a wrong answer too don't this I don't know what the but this it's been like four years is it four years wow time really FES when you're having fun isn't it uh you can probably look up that video and I might be much younger but in any case yeah um this is what I have today I mean I had a silly mistake uh that's very silly actually and I was just focus on the one point and I'm rushing a little bit to be honest but yeah this is linear time still linear space or h space due to the stack um actually it's linear space in general because best can be linear right so I don't know uh so yeah linear time linear space and yeah that's all I have for this one let me know what you think and yeah stay good stay healthy to your mental health I'll see youall later and take care bye
Find Mode in Binary Search Tree
find-mode-in-binary-search-tree
Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. If the tree has more than one mode, return them in **any order**. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. * The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,null,2,2\] **Output:** \[2\] **Example 2:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` **Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
98
454
hey guys thanks for joining in today's video we're going to take a look at problem 454 and leak code for some two so first we'll go over the problem description then we'll discuss how we can implement a solution to the problem we'll call out any edge cases we have to account for we'll discuss what kinds of data structures and algorithms we can use to make the solution as efficient as possible and finally we'll actually go ahead and implement the code and submit the answer so i'm going to be coding this in java if you want to follow along in a different language that's fine too the concepts will carry over from language to language so let's go ahead and jump into the problem reads given four integer arrays nums one through nums four all of length n return the number of tuples i j k l such that zero is less than equal to those terms which is less than n and nums one i plus numbers two j et cetera equals zero so basically we have to find combinations where we pick one item from each array sum them up and they equal zero so for the examples they give us the first one is of size two so each array has two elements and they give us an output of two indicating that there's two ways that we can select one item from each array such that the sum is equal to zero so in the first one plus negative two plus negative one plus two and a similar example for the second one in example two they give us a kind of trivial input each array has one element of zero and the output is one meaning that there's exactly one way we can combine those elements so this is actually one of the base cases we have to account for the sort of trivial case of just zeros so in terms of implementing a solution the first thing that comes to mind might be to just do a four level nested iteration where we say for each element in the first array for each element in the second and then the third etc each of them nested within the last we could just get this some check if it's zero and if it is add to some counter increment value now that solution would work but it would be very inefficient it would be a time complexity of o of n to the fourth power so we can definitely do better than that so the question is what can we do to avoid some of that redundancy to help answer that question let's look at a whiteboard diagram which we can use to explore some of the facts of the situation so what we have here is a simplified version of the problem so instead of four arrays we only have three so on the left we can see the declaration of each array each one has two items on the right we can see a tree which expands upon the choices we can make so for example if we pick zero from num ones and then one from nums two and then negative one from nums three we would take this sort of zigzag approach here so in other words we have paths corresponding to all the possible sums we can take now notice that everything except for the first level has duplicated node so for example we have a three here we also have a three next to that to the right and the second level we have a one and another corresponding one then in the bottom row we have four of each node so we have four negative ones and four negative twos so that indicates we might be able to do some type of caching to cache previous execution so that we don't have to explore redundant paths so what i've done here is in the second level next to this three notice we have a two comma one tuple there what i've done is i've taken partial sums at that level so we have three plus negative one is equal to two three plus negative two is equal to one so i've added three with each of its child nodes now notice that the three on the other side has the same exact value two and one and similarly for one we have zero negative one and then zero negative one again for the other one so this indicates that we can do some caching of that sort so in this example we could potentially traverse the left side of the tree first get those caches in place those maps then on the right side we come to negative one the purple node and then we go to three we can see that three already has values two and one and then we see okay one and negative one that makes zero we just found another pair so instead of having to explore that entire subtree which would be even larger if we had four arrays here we can just compare against our map directly so in our actual code implementation we can take an approach similar to that so let's go over to the code and get started with that so in this problem we have four arrays instead of just three so we'll have to account for that extra array so we can take the same approach and if we strictly follow that approach we would have two map caches one for each inner level then we could compare against the first array numbers one directly but we can do a little bit better than that instead of needing two maps we can still use just one map and we can do the same type of quadratic iteration for nums one and nums two as we did for nums three and nums 4. so let's go ahead and do the first part of creating the map first i'm going to make a separate method for that let's return a map of an integer to an integer the reason we're using a map and not a set is because we need to see how many occurrences of each number we get because we don't want just distinct values we want actual counts otherwise we would just get a boolean indicating that we can do zero instead of the number of distinct tuples that would give us here so let's make a method create sub sum map and it'll take two integer arrays i'll call it nums a and nums b just for simplicity thing we'll do is initialize the map i'll use a hash map for this then we'll do a quadratic iteration and what i mean by quadratic iteration is just loop inside of a loop so we'll have int number a from nums a then into nums b in numbers b sum is equal to num a plus num b we'll put that in our sums map and we're going to put the key as the sum itself the value will be either zero or sorry the value will be either one if this is the first time we have it or the previous value plus one otherwise so we'll use get or default so we can provide default of zero if it doesn't yet exist in the map that way we don't have to do some if else sort of thing this is a little bit more uh streamlined then we can just return the sums map so that's the first step done which we discussed in the tree or doing that caching layer then what we need to do is actually do a quadratic iteration over numbers one and numbers two similarly but it'll be a little bit different there so first let's go ahead and initialize our map here now we're putting those three nums four in there but it would be similar if we did numbers one and numbers two and then did the other part with numbers three and numbers four and that also tells us that fortunately the order in which we put them in won't matter so if it works for this one is numbers one this one's numbers two etc it should also work with the inputs flipped or swapped in different orders so for each of them in numbers one we want to perform a sum and then check if the map has that and get the count from it if it does so initialize count to zero also call it num a here and then b count plus equal to partial sums dot get or default we'll do that again and we need the negative sum here because it'll be the sum plus this thing is equal to zero so we need to make sure we put the negative so i'll just say negative num b minus num a or zero so if it doesn't exist then it will not add anything to count then lastly we can return the count so this will handle situations where there are no sub sums at all because the count will just remain zero throughout and it'll also handle different orderings just by the fact that we're still iterating over each thing in the same sense so let's go ahead and submit this answer is the correct answer okay so i've run this a few times the first time i just had a typo once i fixed that we were able to actually get an accepted answer i ran a few more times just because of the variability of the runtimes and memories when we run the same code more than once just so we could get a healthy balance and we have a working answer that seems decently performant so i think we can accept the implementation that we have here so that covers the content for this video if you made it to the end please leave a like and subscribe that really helps out the channel and also be sure to check out our website where we have tons of where we have tons of where we have tons of different programming articles related to data structures and algorithms web development and other different types of topics and frameworks we also have an online store with mugs laptop sleeves and other products centered around programming memes and programming humor definitely worth taking a look thanks for watching
4Sum II
4sum-ii
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that: * `0 <= i, j, k, l < n` * `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0` **Example 1:** **Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\] **Output:** 2 **Explanation:** The two tuples are: 1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0 **Example 2:** **Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\] **Output:** 1 **Constraints:** * `n == nums1.length` * `n == nums2.length` * `n == nums3.length` * `n == nums4.length` * `1 <= n <= 200` * `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
null
Array,Hash Table
Medium
18
1,793
hey everyone today we are going to solve theal equation maximum square of good subarray okay so first of all we have two constraints the first constraint is like we have to calculate max score with this formula so take a minimum number from index I to index J and then multiply index J minus index I + one and multiply index J minus index I + one and multiply index J minus index I + one and the second uh second constraint is so index I is less than or equal K and the K is less than or equal to J so let's focus on um this second constraint so problem is it's hard to manage three indices at the same time so um we should change our idea so simply we know that K index number right because we are given the k equal something so I think it's a good idea to start from K index then itat through all numbers so in that case in index I is like less than or equal to K so move towards index zero on the other hand um index J is greater than or equal to K so move towards the last index so let's say k equal index 2 here so I start also I and J also start from here and I um I move towards index zero this way and the J move towards the last Index this way so um point is we don't have to care about this second condition because if we move like this I is definitely like less than K right and J is definitely greater than K right so we already meet this condition so we don't have to care about uh this second yeah so that is the first point okay the next point is how we can move uh index I and index J so description said return the maximum possible score of good sub array so I think we have three cases so case one is not reach end of array at both sides so in this case if I number is greater than or equal J in that case move I with minus one so why minus one because we start from K so K is now index two so I move toward index zero so that's why if we want to move left we need sub we need to subtract minus one from index I right so that's why move I with minus one so um on the other hand um if um J number is greater than an i number in that case move j um with like a plus one because uh J move towards the last index in this case four right so that's why we need to add plus one to J so easy right and uh case two is um reach index zero first so let's say index I already reach zero so in that case simply I move j um with plus one because uh there's a possibility that we can find like a maximum score um and then K three is U reach the last index first so J reach the last index and the I is let's say um here so in that case so simply I move I with minus one right very simple in each iteration we calculate the minimum number and maximum score so candidates of minimum number should be current minimum number or I number index I number or index J number and I take a minimum number from these three and the candidates of maximum number should be current Max number versus the result of this formula yeah very easy okay so let's see how it works with a simple example 1 4 37 and K2 and first of all initialize I and J with K so igk is now index two and initialize minimum number maximum number with K number so in this case three right three and first of all um so compare IUS one and J + one so four compare IUS one and J + one so four compare IUS one and J + one so four versus 7 and uh we have to return the max score so take a larger number and in this case seven so that's why move j to next so and then um every time as I told you I'll calculate a minimum number and the max score so current minimum number is three and uh as I told you um we have three candidates for minimum number and current number and the index I number in this case three and the index J number and seven in this case minimum number is three right so minimum number is still three and uh after that calculate the max score Max uh we have two candidates um current Max score versus I delete the formula and but minimum number in this case three multiply and J minus I + one so J is now multiply and J minus I + one so J is now multiply and J minus I + one so J is now index three minus index 2 plus one that means two right so 3 mtip two is six so now Max squore is three versus six so three is greater than three right so that's why Max square is now six and then let's move I or J pointer but uh already J already reached the uh end of array right so in this case um we move I point that to next so here and then let's calculate two numbers so minimum number so current minimum is three and I number is four and the J number is seven so minimum number is three and calculate the maximum score and the minimum number is still three and J index is three and I index is now one plus one so three multiply three right so in this case nine so 9 versus six so 9 is greater than six so update Marx score is nine and then let's move I or J but uh J already reached the end of array so move I point to next and then calculate the minimum number 3 versus 1 + 7 not plus 3 minimum number 3 versus 1 + 7 not plus 3 minimum number 3 versus 1 + 7 not plus 3 versus 1 versus 7 and one is a minimum right so that's why now minimum number is one and let's calculate the max Square so minimum number is one multiply and J is three I is z plus one so in the case four m by one so that is four right four versus 9 so N9 is a greater than four so max score is nine and then now I and J reach uh end of array right so we finish iteration so all we have to do is just return nine in this case yeah so that is a basic idea to solve this question so without being said let's get into the call okay so let's write the call first of all mini m equal Max score equal nus K and the index IAL Jal K and calculate the length of input array n equal length of nums and then let's iterate through from K Point while I is greater than zero or J is less than nus one in the case if I is greater than zero and J is less than nus 1 so in that case um so let's compare two numbers so if nams I - one is greater than or equal nams I - one is greater than or equal nams I - one is greater than or equal num J + one in that case I take a larger num J + one in that case I take a larger num J + one in that case I take a larger number so I minus = 1 else J plus equal number so I minus = 1 else J plus equal number so I minus = 1 else J plus equal 1 and then else if I equal zero and uh J is less than n minus one so this case is where uh um I pointer is already reach index zero so in the case um just uh move J pointer plus equal 1 so else if J = N minus one and I is greater than if J = N minus one and I is greater than if J = N minus one and I is greater than zero so this case is a j pointer already reached the last index so in that case IUS equal one so after that update minimum and the maximum score so minimum should be mean so we have three candidates right so current minimum versus numus I versus numus J very simple and then calate the max squore equal Max squore versus minimum multiply index J minus I + multiply index J minus I + multiply index J minus I + 1 yeah that's it after that the max score yeah let me submit it yeah looks good and the time complexity of this solution should be order of n because we itat all numbers from K point right and the space complexity is o1 we don't use a uh extra data structure just a simple variable 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
Maximum Score of a Good Subarray
minimum-moves-to-make-array-complementary
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Array,Hash Table,Prefix Sum
Medium
null
347
all right guys welcome back to another video on the derv codes channel i apologize for the last video and the annoying static that was going on anyways we're going to be solving lead code number three four seven another question on the neat code 150 list this question is top k frequent elements and essentially given an array nums and an integer k return the k most frequent elements and it seems we can return it in any order okay so let's take a look at example number one now we can see that we have three ones so you map one to three we have two twos map two to two and then three two one okay and now it wants the two most frequent elements okay let's take a look at our mapping so the two most frequent elements are both one and two so we can return one and two in any order so either of these would work great now another thing worth noting is that the length of the array is from 1 to 10 to the power 5 and k is in the range one to the number of unique elements in the array all right guys so for the first solution we will be using a hash map and this algorithm actually takes o n log n time so for the follow-up which states that so for the follow-up which states that so for the follow-up which states that we should find a solution that takes o of n time this solution will actually not work nevertheless let's see how this can be done with a hash map hashmap alright so the first step would be to create a hashmap which we can denote as frequency alright so for now we just have an emptyhash map and we want to iterate through the array so we have a for loop that first points the first element in the list one okay one does not exist in the dictionary let's add it to the dictionary with count one okay then move the pointer over one already exists in the dictionary so let's just update its frequency one exists once again so it has frequency three two has frequency two and three has frequency 1. all right so this is what our hash map looks like so after we have created the hashmap from here it's actually pretty simple because all we have to do is we have to sort the pair the key value pair of each of the values in the dictionary by their value and then what we'll get is a list which looks a little something like this so what we'll get in the end is a sorted list like so three one which corresponds to this element in the map 2 and then 1 3 which corresponds to this element and then in the map we'd like to keep an output array we'll call it res and res should be initialized of course as an empty array and then what we'd like to do is we'd like to keep a while loop which essentially points at the very last index in the list and it adds each of the elements in the array according to their frequency so in the first case we have one and what we can do is we can just pop it after we have added it to the results array so what we would have now is one and then the next element would be 2 and then the next element would be 3 given that k is equal to 3 in this case if k were equal to 2 we would just not i had the last element in the array this is what we would have in the end and that's essentially it for the hashmap solution all right guys now for the hashmap coding solution so the first thing that we're going to do is just create our empty results array and then we're going to create our frequency map all right and then what we would like to do of course is iterate through the nums array so for num in nums what we'd like to do is we'd like to check first if nom is in frequency as a key and we like to check if it's not in because in this case we just want to say frequency at index num is equal to zero and then we'd like to increase frequency at index num plus equals one all right and that'll take care of gathering the frequency for us and then what we would like to do is we would like to create a new sorted array by frequencies containing the elements from num so essentially what we do is we say sorted by frequency is equal to sorted and then we'll grab the dictionaries value so frequency dot items and then we'd like to sort it by so our key will be equal to a lambda expression so lambda x at index 1 and then we would not like to reverse the array so this is all that we would have alrighty now what we'd like to do is simply populate the result array which we can do just by creating a comprehension or in this case i'll just create a for i in range and then we just want to go up to k because we want the k most frequent elements so for i in range k we'll say result dot append and to the results we'd like to append sorted by frequency at index i and since this is a tuple we would like to use the first element in this tuple so the tuple is essentially a key value tuple so first element is the key the second element is the value alrighty so then we'd reference index one and then we have gotten the k most frequent elements so what we'll do is return oops price and then you can run this code sorry made a quick mistake it's index zero because that's the key run code and of course the solution is not that efficient but we will fix that in the next coding solution all right guys so for the next solution we're going to be doing something called bucket sort now the time complexity of this algorithm is of n and the space will be o of n as well okay so the way that bucket sort works is essentially we create an array with these little buckets which correspond to the frequency so the index of a bucket corresponds to its frequency so each of these sub lists are considered buckets and now within these buckets we want to add each of the numbers that correspond to a specific frequency now let's walk through an example of this okay so consider the first example so what we do is we look at the number of elements in the array because we want to figure out what is the maximum frequency that we can have and of course it is the number of elements in the array okay so the first thing that we'll do is we'll create an array with n plus one buckets just because there's not going to be any elements frequency zero so that first one is going to be an empty bucket so in this case we have one two three four five six so we'll have to have seven buckets all right so that's what the array will look like and essentially what we'll do is we'll keep a frequency map like we did in the last solution so we can call it frequency right and this map will just map the frequency of each of the elements in the list or the element to the frequency of it in the list so in this case using the same algorithm as in the last solution we'll just say one maps to frequency three two maps to frequency two three maps to frequency one and this is the frequency dictionary okay now what we'd like to do is we'd like to iterate through the frequency dictionary adding each of the elements into the index of their key so essentially what we do is at index three we'd append one at index one we append three and then from here what we'll do is we want to start building our output array well to do that what we can do is we can iterate through the array from the back so essentially what we'll do is we'll first look at this one see if there are any elements so create an array called result we'll see if there are any elements in this because this would be the most frequent no there's no elements okay are there any elements in this array no and then until we get to this array once we find an element what we'll do is we'll add it to the array so then in this case it would be one all right then the next thing that we'll do is we'll take a look at this array so there is another element that we can add great and then let's just say we're looking for frequency 2 as given in the example this would just be a result now what if we had another element here and we were looking for frequency 2 well what we could do is we could pop from this array or we could take a list slice for the exact amount of elements that we need so in this case it the result list would look something more like this although this would also be valid now once we've built a result array we can just return and this actually has time complexity of o of n because all we're doing is we're first building this empty bucket list which takes o n time because we're exactly filling the outer array with n plus one buckets and then the next thing that we're doing is we're iterating through the nums array and we're accumulating each element's frequency in the nums array which is again about n steps and then from there what we want to do is we want to iterate through the map which will be at most n steps and then from there we want to iterate through this frequency array that we have built of buckets containing elements with a given frequency and this takes n steps to iterate and what we'll notice is that you might ask okay well what if a container just contains n elements well what is important to note is that we're popping or we're removing at most k elements and k is always less than or equal to n so we can say this is at most n steps so this building our result array will be two n steps which is of course o of two n so in total the algorithm is o of n time now for space what did we use we used a mapping so let's just say every element had frequency one that's of and space okay and then we also built this buckets array well that's also o of n space that's taken and then the results array of n at most and that's it for the solution all right guys and for the second coding solution using the bucket sword we will begin of course first by initializing our result array so result is an empty array and then the next thing that we'll do is we'll actually create our buckets so buckets list will be equal to a list and we'll use a comprehension in this case each time adding a new bucket so four for underscore in range and then since we want n plus one buckets what we'll write is for an in range length of nums plus one so that'll create n plus one buckets where n is the size of nums alrighty and now we'd like to actually figure out what the frequencies of each of the elements are so that we can populate the bucket list okay so the first thing that we'll do is we'll create a frequency dictionary empty at first and then we will iterate through the nums list as we did in the previous question so for num in nums what we'll do is first we'll check if num is in so we'll check if it's not in frequencies because in this case we actually need to initialize it so frequencies at index num is equal to zero and then we can just increment the frequency so frequency at index num plus equals one alrighty and then from here what we'd like to do is we would like to iterate through each of the frequencies in the frequencies mapping and we would like to append them the elements associated with specific frequencies to that corresponding index in the bucket list so what we'll do is we'll go for elements in frequencies what we'll do is access so we'll say buckets list at index frequencies frequency of an element so at a certain frequency we will append the element great alright so now what we have is we have that list of buckets fully populated and then from here what we'd like to do is we would like to iterate backwards through that list each time updating our result list okay for i in range and we want to go backwards here so from the last bucket so length of nums over here we want to go down to the zeroth bucket but it's negative one since it's not inclusive and then we like to decrease by one each time great and then from here what we'd like to do is we would just like to append buckets underscore lists now we would like it to be the ith index and specifically we would like to append from index 0 to k and then each time what we're going to do is we're going to remove the number of elements that we have added so here what we'll do is we will add this to results plus equals and then from here we'll say that k is equal to we would like the previous value of k minus the length of buckets list at index i now of course in the last iteration we might not use all of the elements in bucket list at index i which is totally fine because what we'll have here is that k will become negative so when k becomes negative what we can do here is say if k is less than or equal to zero what we would like to do is just break or in this case we can simply return the resulting array and then we would be done and that's essentially all that there is to it since we're guaranteed a solution we essentially know that this loop is always going to reach this point where k is less than or equal to zero so we can submit this now and then we get the correct solution and this one is in of and time and that is all thank you guys so much for watching and another video is coming your way very soon
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
1,197
hey guys how's everything going today let's take a look at number one 197 minimum light moves this is one of my videos that I'm going to use to prepare for my fifth Facebook interview in June so hope it helps myself or and I hope it helps you so we're given an infinite chessboard with the coordinates from infinity to infinity we have a night at zero for each night when there has there may might be eight boosts right yeah and we need to return a minimum number of smooth for a night to get to the square XY the answer is guaranteed exist and the constraint would be yeah it's not that big well first let's analyze some basic the basic idea is just to go to - basic the basic idea is just to go to - basic the basic idea is just to go to - just like tang the canvas while step-by-step right the first one step-by-step right the first one step-by-step right the first one is zero so let's mark the cell with the stem innamal steps okay from here we have eight moves which will be one step here something like this right okay now let's analyze next steps is to so the two was started to put 1 step 1 right so it would be like 2 and ok here is 2 0 and it's smaller than 2 so we skip and 2 so the picture just came to us that we could just do this over and over again until we match the coordinates but right but here's a one problem that if we want to get to the point like get the point I stop top all right if we do this like expansion forever what it's what just grew like this so there's a lot of unnecessary calculation right like if you want to expand the area to here it's madness because our night is at the top right so we need to improve this idea how well it turns to us that's the board is a completely symmetric so if we're given some there for it for each the coordinates in a board there is corresponding for board which means for an eye to go to either of this either four of them the steps are to be the same right so if we can are given these three coordinates we can just go to this one only one that remind reminds us we could just try to remove the via this part and this part that these three diagonal area with that would that work let's just try to do some more something more if we just ignored these points here will you still suffice okay for 200k for one let's try to want to complete the one condition one so here is to oh okay this is for the top right diagonal and now for two here be three right and three here and then 1 2 here 3 &amp; 2 3 so here 2 here 3 &amp; 2 3 so here 2 here 3 &amp; 2 3 so here there's a problem here right yeah we could do move three from here three get four from three but actually you see there is one here so actually we'll be good all right yeah going back to our going back to the original full expansion here 1 2 this is the first one and this one will be 2 something like this so here for 2 here it can get to what he can get to this diagonal is - of course - here - - this diagonal is - of course - here - - this diagonal is - of course - here - - to get down and now here you can get a - to get down and now here you can get a - to get down and now here you can get a - this cannot get directly from top right net and diagonal right and 2 3 this could be accessed from 2 here so the problem is the core is here but what if here because you can see that the length the coordinates will be bigger or equal to 2 right so it cannot be generated from this part or this part this could be generated by 3 and now for the points here why if there is a point to the left side could get the commits to the cell here there must be a corresponding coordinates to this part and generate to that so we can forget about it right yeah the core problem is this - we can't yeah the core problem is this - we can't yeah the core problem is this - we can't generate it because either if you analyze the first one you see that the origin I hear actually the row and the column actually it is a these are these four cells that could not be generated with one step so actually if we do it with one more time and we can cover that right that means for the first two step we need to get all the all connects and then from that we could just keep the only positive integers and there's a yeah and there's another problem is that there are a lot of duplications right like these three could be generate from these two and these three Christian also these two so there's a we need to keep a keep track of what it is or in access or not if you know already access to we're gonna ignore that so if this 3 is already handled the next time when we meet again we need to skip so the idea it becomes clear is that first we use a flag is a flag using map so keep track of the visited or not right okay we use visit it to create a new map and then we do iteration on each step I mean by I mean it just uh how should I interpret this which means keep of the cells which could be led to PI and step or for this we use a queue yeah so Wow there is which it should be initialized with 0 and so when you do this forever Marshall what do we do here is that first we need to check if we get the gets all the elements right and then push something push the next round of elements in check e aí and round points then push in next round of course we need to step keep track of the step so for each step we shift to the elements out and then push the elements in but when do we stop we need to add that identifier to do that right so we use push in or in as an ending identifier so let's the head while we head is wowhead mmm equals to Q shift this while loop our ends at this nor so this it's gonna be okay after we check this and then we need to update the step right and then the next step is if it is target so if zero equals x this circuit will return the step and it's done right and then we need to process next round we just know push pushing to the Q and there are five eight directions we will define the directions well this is simple it should be 2 1 2 minus 2 1 minus 2 minus 1 yeah this is the directions so for each direction the next point would be this is the next point right if this point is not or he's not accessed we can push it in so it should say if visit it has a key would be next zero if you saw it visit it own that wait a minute if it is not visited it we could push it in all right so the queue would push the next and then we push all in and we update the step and seems alright but we meant but there's a problem that for each round for this zero right you push this in and then there might be two different cells half this duplicate next round cells right so when we shift we would add oh wait a minute we forgot for each head we should set it to accessed so as the kinky will be visit it set key true even we do this they're stupid this too might be duplicate elements we pushed it in because there they are not access to yet so we need to do the check here if it is already checked we continue right skip this and then we do everything yeah this seems right let's try run code cool the simple one is work as looking for five cool they submit you see the I didn't accomplish it with one pass I tried a lot of times there are time then exited the wrong answer so actually we were accepted but we're not that fast enough as we added this before mm4 we need no two steps we need to keep track all McCook no the except only is the special case is this - right - right - right so after step two we only keep the positive sales and it was suffice yeah let's try to do that so the first thing we used to normal normalize the input X would be math.abs we took - we took the would be math.abs we took - we took the would be math.abs we took - we took the top right points and then we only pushed it in only push in the arm visited and positive once and step is cook could be smaller than two but after step two all of them should be positive not negative I mean turn on the code hmm I don't expect token what if has and here cool this should be right no on exporting what wait a second this shoe right should be right okay and then it should be step we should be bigger than shoe and next I submit again yeah we're much faster than that okay so what's the time and complexity of this algorithm what time oh time wow it's hard to say well it's really hard to say for each batch steps well I really don't know what's the time complexity of this one let's do some simple analysis while true while had every time a puppet any man now we pushed it in eighth in worst case it in but there are a lot of duplicates and we've reduced at least for at least 25 percent but the time complexity would time complexity change 8 every time 8 so anyway so Wow I don't know because we're getting the coordinates after these steps let's say the step I'd say n step and we are Wow it's Oh 8 to the end I don't know where space we use a map to keep track of the visit or not and that would be oh this week we know this because we only took the top right area so it's something like this of course a be suppose a XY are non-negative there's something as we do our analysis actually the expansion will cover more and more elements right so actually how many for each sale I mean for each cell we will check constant a time a times for next cornet and the next coordinates actually each cell will actually be traversed once so it's actually Oh big ol x2y2 check each cell free check will might cost 8 rounds and all the check are all the check yeah I'll go check are using this hash table so it's constant the maximum is like eight right so it's the same as the space complexity maybe I'm a row maybe I'm wrong I'm three I don't know mmm but if I max I will say something like this okay so that's all for this problem I hope it helps wow I don't know about I learned a lot from a lot of from this problem the traversal which is actually breadth-first search and then we try to breadth-first search and then we try to breadth-first search and then we try to improve this algorithm by reducing unnecessary calculation Wow cool so okay see you next time bye
Minimum Knight Moves
parsing-a-boolean-expression
In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists. **Example 1:** **Input:** x = 2, y = 1 **Output:** 1 **Explanation:** \[0, 0\] -> \[2, 1\] **Example 2:** **Input:** x = 5, y = 5 **Output:** 4 **Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\] **Constraints:** * `-300 <= x, y <= 300` * `0 <= |x| + |y| <= 300` "t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.
Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not".
String,Stack,Recursion
Hard
null
1,503
Hello Hi Everybody Welcome To My Channel It's All The Problem 1503 Last Moment With All And Fall Of Playing Subha Hai Western Flank Of The Land And Unison And Share Broking Gond Appling Inch And Moves With Speed ​​One Unit Per Second Some Of The Year And Speed ​​One Unit Per Second Some Of The Year And Speed ​​One Unit Per Second Some Of The Year And Month To The left and the other mode to right when to and move into different directions at some point they change the direction and continuing in changing directions and take any additional time vansh one and after the time limit for the President witnesses position and moving and written in the Last for example a that MBBS move into the right direction so and cmd which move into the direction and valuable clients is hair floor and loose to give the floor and give what will happen first step cornice hua 108 sequence 212 that a t- 20 Candidate And Will Rear For that a t- 20 Candidate And Will Rear For that a t- 20 Candidate And Will Rear For B.Com 2nd Dash subscribe to subscribe B.Com 2nd Dash subscribe to subscribe B.Com 2nd Dash subscribe to subscribe Moving Towards Life And Directions To The Giver Of Time But Will Fight With You Will Guide You Will Change The Direction To Right Again Will Change The Direction Of Delhi Will Change The Direction And Again And Mrs Coordinator For Android App A Faint B N C L Sorry For The End Of The Planet Antique Value Fiber Both Of All Of The Swift From Different From This Is The Example Total Time And Place For Yourself From Doing So Answer Of This Solution Example Sentences with Simple Example of Going to the Subscribe Will Immediately 12345 06 Subscribe Total 40 Subscribe Example What is the meaning of the day Billu Seventh - Minimum of this and we can calculate every Billu Seventh - Minimum of this and we can calculate every Billu Seventh - Minimum of this and we can calculate every time the maximum value 7 - time the maximum value 7 - time the maximum value 7 - The Light Value Sake Example Which has left side * Subscribe in the example for have to go to the problem left side * Subscribe in the example for have to go to the problem example for example four subscribe this Channel subscribe I have been here and heard if add target display in this no entry and left side are language anti A Fiber Android Are Going For This Is The Situation Boys College Se Inter College B For A Moment Point To Like This Point Five Withdrawal 4.5 Distraction 4.5 The Movie Five Withdrawal 4.5 Distraction 4.5 The Movie Five Withdrawal 4.5 Distraction 4.5 The Movie The Same Time Total Time What Like This Is Not Thinking Of Changing And Left Side Me Left Side The New Delhi Diabetes Patient Problem Accept Brain Teaser Problem Sort Algorithm In Problem Research And Also Withdraw It's Really Very Few People To Solve This Problem On You Slept Swift Like During Two Roads What Is The Maximum Time Taken While All The And move into the right minimum value - also The And move into the right minimum value - also The And move into the right minimum value - also and minimum of the meaning of right this that and what is the maximum time taken by old and moving Dual app pure maximum business smacks of electric subscribe time taken with an all and flows from bulk pack to retail Limited Improvements tweeted on Monday A flat se mix left from it land right inside interior do n't believe that in Hindi electret point se left a gain power max left one will become math dot mix of alcohol max life itself without fear from left and Will do the winter in right that he will get them in right that tomorrow to math dot min yes and common man right hand and blesses return of the day math dot mix of in the two means chief max left and jane - in the two means chief max left and jane - in the two means chief max left and jane - getting Is I safe this is sample implementation select compiler code that such the first speech in adhir and test cases for example subscribe school of planning and subscribe school st lucia st a handle is another example no the end no end left tayohar and sohan selection commission maximum at Custom test cases this is not unique this note aveli report mp fine for three saliva text author valid that a co select strive test's nature distance case what us show 137 west and south tablet and 137 oil antiseptic so what is the time of the time Placid in the time complexity subscribe to a half sava 100 ko hanif vinod system which can also c bsc nursing line through let me show you sauvir water in the streams or s.st stream fluid d option subscribe or s.st stream fluid d option subscribe or s.st stream fluid d option subscribe The Channel and dont reset dots The stream the right from the rate items will get dim in oil and else will choose integer dot max value a song that you when liner implementation of the same let's compile that Nitish compiled and where getting to cricket zero 100 Video not amino acids and Bases for this Twitter - One has been acids and Bases for this Twitter - One has been acids and Bases for this Twitter - One has been compiled by Nitish and they are getting correct answer so let's submit this one liner solution has the satisfaction time lapse plaited same thank you feel like my solution please hit the like button and subscribe To My Channel and Hit The Bell Icon to get early notification of measurement videos Thanks for watching
Last Moment Before All Ants Fall Out of a Plank
reducing-dishes
We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**. When two ants moving in two **different** directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches **one end** of the plank at a time `t`, it falls out of the plank immediately. Given an integer `n` and two integer arrays `left` and `right`, the positions of the ants moving to the left and the right, return _the moment when the last ant(s) fall out of the plank_. **Example 1:** **Input:** n = 4, left = \[4,3\], right = \[0,1\] **Output:** 4 **Explanation:** In the image above: -The ant at index 0 is named A and going to the right. -The ant at index 1 is named B and going to the right. -The ant at index 3 is named C and going to the left. -The ant at index 4 is named D and going to the left. The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). **Example 2:** **Input:** n = 7, left = \[\], right = \[0,1,2,3,4,5,6,7\] **Output:** 7 **Explanation:** All ants are going to the right, the ant at index 0 needs 7 seconds to fall. **Example 3:** **Input:** n = 7, left = \[0,1,2,3,4,5,6,7\], right = \[\] **Output:** 7 **Explanation:** All ants are going to the left, the ant at index 7 needs 7 seconds to fall. **Constraints:** * `1 <= n <= 104` * `0 <= left.length <= n + 1` * `0 <= left[i] <= n` * `0 <= right.length <= n + 1` * `0 <= right[i] <= n` * `1 <= left.length + right.length <= n + 1` * All values of `left` and `right` are unique, and each value can appear **only in one** of the two arrays.
Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Otherwise, keep the previous best like-time coefficient.
Array,Dynamic Programming,Greedy,Sorting
Hard
null
102
looking at lead code number 102 binary tree level order traversal we're going to use a template to solve this and we're going to solve a bunch of questions that deal with level order breadth first search traversals using this template so uh if you are having trouble with this is a good way to kind of memorize one pattern or just be familiar with one pattern that allows you to solve many other problems that use the same underlying pattern okay so here we're given a root of a binary tree we want to return the level order traversal of its node's values from left to right level by level so here we have this tree here and we're going to have three the level the zeroth level the first level nine and twenty and the second level which is fifteen and seven okay if uh there's one element in the root we just have the zeroth level and if the root is empty we just return an empty array okay so you may have tried to do this with your regular breath first search template for you know binary trees and it didn't work because the queue is the that some of the numbers are in there at that level some of them aren't and it's kind of all mismatched so what we're going to do here is we're just basically going to do a breath first search traversal through this tree level by level and i'll show you a cool little trick to kind of do that so here we have our tree and uh we're gonna set a cue okay and we're gonna initialize it with the root which will be 3 and then here i'm going to have a result and i'll initialize it with an empty array so what i want to do now is i want to make sure i want to create a while loop and i want to say while there is something in the queue okay while the queue has a length or the queue is not empty i want to do some work so what i want to do is while the queue is not empty i want to store the length of the queue the size of the queue at that point okay so i'll just create a variable len and i'll set it to whatever is in the queue on each iteration of the while loop so right now it's one and now i'm going to take a scan because right now you can see that what's in the queue is at the level zero at the zeroth level this will be our zeroth level first level second level okay we have the correct information in our queue for the zeroth level so i just take a scan of that put it in an array and then push it into the result okay so that's our zeroth level that gets pushed into our result now i have this length variable right so i want to create another while loop and i want to say while the length whatever the length is those are the elements i want to pull off of the queue then i want to shift off of the queue so i'm going to take this 3 and we'll go ahead and pull that out of the queue and then we want to push into the queue whatever's on the left and whatever is on the right so in this case it's 9 and it's 20. okay and then we break out of that second while loop and now you can see when we come back to the parent while loop we have the correct level here we have 9 and 20 in our queue so again we just take a scan of this push in nine and twenty okay and then we take a length we take the length of the q at this point which is two okay and so now in our inner while loop we're just going to run this twice we're going to run this once and we're going to pull out that 9 has no children so we just we don't do anything and then we pull out this 20 and 20 has two children so we push in the left into the queue which is 15 and we push in the right which is 7. okay now we're back in the outer while loop and we can see that we have the correct level these are the correct values that we want so we're going to store the new length which is 2. and then we take a scan of what's in the queue here and we push it into our result this will be 15 and this will be 7. okay and because 15 and 7 don't have any children we pull these both off in our inner while loop the queue is now empty we break out of the outer while loop and we go ahead and return our final result here now if you tried to do this the other way you i'm sure you ran into problems like i did as well like we all do um and you can tell that because at every level you don't have the correct values in the queue they kind of mismatch around but this is a great way by pulling out the length at each iteration then we can know that what we're pushing in the queue is just everything at that specific level and this is very valuable because now you can solve many other problems that deal with like you know like zigzag traversal or level order traversal 2 there's all these different variations of this same pattern so knowing this is very valuable okay let's jump into the code so first what we want to do is we want to have our edge case if we get an empty root so we can just say if root is empty just go ahead and return an empty array and now we want to go ahead and initialize our queue and set our root as the initial value and then have a result and set it as an empty array okay and now what we're going to do is we're going to have a outer while loop that's going to run as long as there's something in the queue and what we want to do now is we want to go ahead and store the length of our queue because that's going to that's not going to we're not going to keep on putting unnecessary values in the queue so we go ahead and say let len equal q.length and then what we want to do is we want to take whatever's currently in the queue and push that into the result and i'm going to use map because it's going to make a copy of everything in the queue and push that into our result so we can do q dot map node and because we're pushing nodes in the map we'll just do node.val okay so all this does is that it takes a copy of whatever was in the queue and uh and it just puts the values into its own array okay and now we want an inner while loop that is going to run the length times so i'll just do len minus this is just going to keep on decrementing until we get to zero which is falsey which will break out of that loop so now we just want to pull out the node so we'll do a q dot shift and then we just want to check if no dot left then q dot push no dot left and if no dot write q dot push no dot write okay and then we just go ahead and return our result let's go ahead and run that okay and we're good okay and so let's talk about time and space complexity with this there are two while loops but if you think about it the inner while loop is only running the length times so we're actually only traversing this tree once okay so our time complexity here is actually o of n i know we have two while loops so you may be tempted to think that it's o of n squared but if you really just think about it and map it all out it's actually of n we're not going over any of the values more than once and then our space complexity is going to be relative to the size of the input in a linear fashion we're just putting in the values into this result relative to the size of the input okay so our space complexity is also going to be o of n okay so that is lead code number 102 binary tree level order traversal very good to be familiar with this pattern um i'm going to solve a bunch of other questions that use this exact same pattern so if this didn't make sense feel free to check out my other videos to solidify it uh okay hope you all enjoyed it and i'll see you all in the next one
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035
1,007
hey guys welcome back to another video and today we're going to be solving the leakout question minimum domino rotations for an equal row all right so in a row of dominoes a i and bi represent the top and bottom halves of the eighth dominum a domino is a tile with two numbers from one through six and one of each half of the title okay so we may rotate the i dominoes so that a i and bi swap values return the minimum number of rotations so that all the values in a are the same or all the values in b are the same so it's an or they don't both have to be the same either one has to be the same and if it cannot be done return negative one all right so uh what i'll be doing is let's just look at this example over here uh where we have a value of this and a b value of this so a domino is basically a one-sided thing a domino is basically a one-sided thing a domino is basically a one-sided thing so you can see my hand over here so this over here will be one side and this over here would be the other side and i meant to say two-sided sorry to say two-sided sorry to say two-sided sorry so each of the sides has its own numbers so this would have one number and this would have another number so a might be representing this side of our domino while b might be representing the other side of our domino and what we can do is we can swap out these values so the value of a will be the value of b and the value of b will be the value of a and the reason that we're going to be swapping them is so that we want a domino row where all the numbers are the same so for example this over here is the solution and as you can see they all have the same value on one side so 2. or we could have all the same values on the side of b so either of them works but we have to have at least all the values in one of the sides and if that is not possible we end up returning negative one all right so i'll be looking the same question over here and let's just look at it step by step okay so this is the a values on top so everything above this red line is the a value and everything below it is the b value so that's telling us we have two and five on either side of a certain domino now what is the goal over here the goal is that we want one row which is completed with the same number so in order to reach that goal we're going to be iterating through our dominoes over here for a total of four times now why exactly four times and what are we going to be doing in those four times all right so the goal in general is so that a single row has all the same numbers but let's just narrow down our goal for now so that we have all the same numbers for the row a okay so we want everything in a to be a same number and that's our goal so to achieve that goal what we're going to do is we can have two conditions so what is the first number of a going to be now in this case we're going to consider the first number of a to b two but another thing that we could do is we could make a swap over here where phi would be in place of two and we would consider the first number to be five so now in this case let's just take it as two and each time we're going to be going through our list over here and we're going to check if the next value which in this case is 1 if that is equal to 2. in this case it's not so that means that we're not going to have the same array as it is right now so this is not it but just to make sure if we can possibly reach an answer we're going to check the other side so now we're going to go to the same index in b and over here we actually have the value 2 and what that basically tells us is that once we make a swap we will be able to achieve the values of all twos so in this case we're gonna assume that we're gonna make a swap so two comes over here one goes over here and we wanna keep track of that somewhere so for that we'll have a variable called count which keeps track of how many swaps we make so in this case currently we made one swap okay so now we go here and two already exist in the same row as eight so obviously we don't have to make any swaps and same over here so now we go over here and 2 does not exist over here so let's just cross that out and now we're going to check does 2 exist in the same index for the area b and it does so in that case that means we have to make another swap so in this case our count increases to two again so now our count is two and this becomes two this becomes four we're not actually going to be swapping them instead of just doing that for visualization purposes and over here one more thing i want to notice is we have a two on both the sides so the question is which two do we pick the one in a or the one in b so we're always going to pick whatever is in the same row as the current row that we're looking to find all the same elements in and the reason for that we chose this two is because we want the least amount of swap so if we did choose this two our count would have been three instead of what could actually be two so that over there is one of our solutions and that also happens to be the solution but let's just take a look at the other three cases as well now the third case is going to be where the starting value is actually gonna be five so we're starting off with five and this over here is going to be two and now our goal over here is to make everything over here a five but that's obviously not going to happen so we're not going to get anything back from that so that's the second condition now the third condition we have is we look at row b so we only took care of both the conditions for row a so now we go to row b and we're going to check if everything in row b can be the same as the value 5 so that is one of our solutions so we check that and the other solution that is possible is we make a swap and over here we end up with the number two and this becomes five so the goal here is to see if everything in b can now have a value of two so if that is possible then in that case we're going to return that so let's just go through the count that we're going to get using this so two is going to be over here then we have two here so nothing changes so we make one swap here second swap third swap so we have a total of three swaps and sorry for writing confusing you with this but the original answer we had was two so now we have the answer two and three both of them are valid answers but which one do we choose so we're always going to be choosing the minimum count because we want to make the least amount of swaps as possible so in this case we're going to be choosing the number 2 since 2 is less than 3. so 2 is going to be our answer and that's what we end up returning we're always returning the minimum but if we do not have any answer we end up returning negative one all right so i think the question is pretty simple so now let's see how we can solve this using code alright so we're going to start off with a quick base case so we're gonna check what the length of a is and just to make sure the length of a and the length of b are obviously always going to be the same so checking either one is the same thing so if the length of a is less than or equal to one then in that case we can just directly return zero so if we have a length of one that means that the entire row already only has one number so we return zero and if there is nothing then again we return zero okay so we got that out of the way and over here we're going to be making a helper function now what is the purpose of this helper function so what this helper function is going to do it's going to keep track of given a value and a b value and a target the number of swaps it takes in order to reach a row which is completely filled with only one number so that's exactly what our helper function is doing so over here we're gonna give it a target value we're given gonna give it to our array b and we're gonna give it an array sorry we're gonna give it an area a and an area b all right perfect so we're going to start off by initializing our count which obviously starts off at zero and now that we have this we're gonna go inside of a for loop so to do that i'll be going through it by each of their index so for index in range and the range is going to be whatever the length of a or b is again they both have the same length so it doesn't matter which one we choose all right so over here we have each of the index so what we want to do is we want to get the a value and the b value we want both of the values so i'll be using lowercase a and b to find that and what is the value of the lowercase a going to be so we're going to go to the list a and we're going to get whatever index we're currently on so that is going to be the value of lowercase a and obviously for b same thing but instead we're going to go to list b all right so over here we're going to check if our target so if target is equal to our a value now if our target is equal to the a value that means that we don't need to do anything that means that we already have that number inside of our row we don't need to make any swaps we're good to go so in that case we're just going to continue and if you don't know what continue does we're not going to do anything else and we're just going to go back to our for loop over there all right perfect so we have this and now we're going to have an else statement now this l statement means that our target is not in a but the target could be in b right so that's what we're going to check for so if b is equal to our target that means that we do have the value and we can have a row with the same values granted we make a swap so since we're making the swap we're going to increase our account by one so after that we're going to go have an else statement and this means that we do not have the number in a or b so we don't have it at all so in this case we're going to change our count now the reason we're changing our account and what we're going to change it to positive infinity now it might be confusing why are we changing it to positive infinity and the reason we're changing it to positive infinity is so that since we're passing it through our function for a total of four times this is going to be a really big value and every other value is going to be smaller than positive infinity but now the question is what if we have four positive infinities as our output then in that case that means that we do not have an answer at all and we end up returning negative one and after we reach this point so if the number is not in a or b that means that we're never going to get the answer so there's no point in going inside of the for loop again and in that case we're just going to break out of our for loop and that should be it for our helper function and we also want to return our count at the ending so that's it for the helper function and now we want to actually get that function out all right so now we actually want to call our function on the four different cases that we had so we're going to store this value in a variable called rest so the value that we're going to be taking so we're going to be calling the four functions with helper and we're going to get four different counts so what value are we going to be taking from that so the answer to that the value that we're going to be choosing is going to be the minimum of those four values like i said earlier we want the least amount of swaps so let's start off by calling our helper function and let's just call it on the simplest case that we know so the target is going to be whatever is at the zeroth index of list a and the two lists are going to be a and b so in other words what that's telling us is that we want a row a to be filled with this target value over here which is a0 so now let's go into another case so in this case helper and this time we're going to make the target the same the target is still going to stay as a0 but what we're going to do over here is we're going to give it the list b comma a now what this means uh compared to this is that we want a0 to be inside of row b so everything in row b has to have the value of a zero so that's what that this function over here is telling us okay so that's pretty simple and now what we're going to do is we're just going to copy the same thing over hopefully you understand what those two mean and the only thing that we're going to change now is our target instead of being a 0 is now going to be b0 and that should be it for our result okay so finally we're going to end up returning our result now the thing is our result could uh we could have a value of negative one so how do we know when do we want to return negative one and the answer to that is pretty simple so if everything inside of results is equal to positive infinity that means we have no answer then in that case rest over here it's also going to have an answer of positive infinity and when result has an answer positive infinity we're going to end up returning negative one so we return res if and only if our result is not equal to positive infinity so float in but else so let's say if our result is equal to positive infinity in that case we end up returning negative one so that should be it for our solution so thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
Minimum Domino Rotations For Equal Row
numbers-with-same-consecutive-differences
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values. Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same. If it cannot be done, return `-1`. **Example 1:** **Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\] **Output:** 2 **Explanation:** The first figure represents the dominoes as given by tops and bottoms: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. **Example 2:** **Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\] **Output:** -1 **Explanation:** In this case, it is not possible to rotate the dominoes to make one row of values equal. **Constraints:** * `2 <= tops.length <= 2 * 104` * `bottoms.length == tops.length` * `1 <= tops[i], bottoms[i] <= 6`
null
Backtracking,Breadth-First Search
Medium
null
991
hello everyone today we are going to solve a broken calculator lead code medium level problem so in this problem we are given within a start value it is an integer which is a display on and calculator and we can do two operation on that calculator first is we can multiply the number by two or we can subtract the number by one and we have given two integer start value and the target our goal is to reach from start value to target in minimum number of steps okay for an example if we have a five and we have eight so we have to reach five to eight in minimum number of stat so how we are going to solve it let's think of a greedy method and what we are going to think is like multiply with 2 until and unless if this number is less than this so right now 5 is less than 8 so we are going to multiply we will have a 10 okay and as soon as this number is greater than this we are going to minus one okay so minus one so this will be in three step one multiply and do this so um but for this solution i have one more solution that is minus one and it will give four and then into two it will give it so this will take two so the greedy approach from here will not work we are not able to recognize when to do multiplication or when to do minor okay so let's think in a backward let's think uh to convert target to start value okay and see uh can we drive any conclusion from there or not so let's say i have our eight so i will divide by two and i it will get four and as soon as is less than our start value i will increment until it's equal so five i can reach in two step so i can conclude that if the number is the even so we have to divide it or if it's an odd then we have to add plus one okay and end and if the number is smaller than if number is smaller than uh if target is smaller than start value then what we have to do we have to add the difference of the target minus start value i hope you understood just to understand it more clearly i let's understand with another example let's say we have a 5 at start value okay and target is 30 okay so what we are going to do 13 is odd number so we are adding in the first step 14 second step it is odd then we are going to do it why we are going to divide in the second step because we have to understand this as if we are going to add that it will take seven step but if we are going to divide it is only take one step okay and we have to do in minimum step so whenever it is even we are going to divide it okay then seven we are going to add plus one it will be eight and then that is the third step and eight divided by two will be four will be fourth step so at this step our four is smaller than five as four is smaller than five we are going to do answer plus our starting value that is 5 minus our target that is 5 minus 4 is 1 so we are going to answer plus one we have answer that is four plus one five would be our answer i hope you understand this problem so let's see the code to understand more so this is the code of this problem we are going to initialize our answer with zero and until our target is greater than a start value so we are going to do some operation if our target is owed then we are going to increment our target if our target is even then we are going to divide it by two okay and whenever we do any operation we are going to increment our answer once our target is less than start value then there is no uh any other operation we just have to add plus one as many times the start value is greater than target so we are going to do answer plus the start value minus target so this is the answer of the solution our portion and what is the time complexity of this so basically we are dividing by 2 until an unless target is greater than start value so our time complexity will be logarithmic of target and our space complexity as we are not using any extra space it will be of one so thanks for watching if you have any doubt you can ping me in the comment section
Broken Calculator
array-of-doubled-pairs
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_. **Example 1:** **Input:** startValue = 2, target = 3 **Output:** 2 **Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}. **Example 2:** **Input:** startValue = 5, target = 8 **Output:** 2 **Explanation:** Use decrement and then double {5 -> 4 -> 8}. **Example 3:** **Input:** startValue = 3, target = 10 **Output:** 3 **Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}. **Constraints:** * `1 <= startValue, target <= 109`
null
Array,Hash Table,Greedy,Sorting
Medium
2117
292
welcome back for another video we are going to do another deco question the question is 292 lingan you are playing the following lin game with your friend initially there is a heap of stones on the table you and your friend will alternate taking turns and you go first on each tongue the person whose tongue is will remove one to three stones from the hip the one who removes the last stone is the winner even end the number of stones in the heap return to if you can win again assuming both you and your friend play optimally otherwise return false example one n equal to four the output is false for the explanation these are the possible outcomes one you remove one stone your friend removes three stones including the last stone your friend wins two you remove two stones your friend removes two stones including the last stone your friend wins three you remove three stones your friend removes the last stone your friend wins in own outcomes your friend wins example three n equal to two the output is two if there are only one two of three stones and it is your turn you can win if there are exactly four stones you will lose since you will leave sunstones behind for your opponent therefore you can win when there are four stones on your turn you also can win when there are a 12 16 stones they are all multiples of four now let's work through the code if n is divisible by 4 it will return force else you will return 2 the time complexity is 0 1 space complexity is o1 as well and the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
Nim Game
nim-game
You are playing the following Nim Game with your friend: * Initially, there is a heap of stones on the table. * You and your friend will alternate taking turns, and **you go first**. * On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. * The one who removes the last stone is the winner. Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`. **Example 1:** **Input:** n = 4 **Output:** false **Explanation:** These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. **Example 2:** **Input:** n = 1 **Output:** true **Example 3:** **Input:** n = 2 **Output:** true **Constraints:** * `1 <= n <= 231 - 1`
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
Math,Brainteaser,Game Theory
Easy
294
5
question five leak code longest panoramic substring so given a string s return the longest panoramic substring in s so in example one we have b a d and the output is b a b so palindrome reads the same forward as it does backwards and we need to find the longest palindromic substring within the string s so here the output is bab or it can be aba those two are valid palindromes and we need to return the substring within example two we have c b d we have bb which reads the same forwards it's backwards so it is a palindrome and we just return that answer so a great way of solving a problem that consists of palindromes is to expand from the center so we're going to have an ispal help function which checks if something is a palindrome and what i mean by expanding from the center say we have b as our initial position we check if that's a palindrome so b on its own reads the same forwards as it does backwards so that's a pendulum then we expand outwards so we have a left and right pointer here we expand outwards left goes here right goes here we check if this is a palindrome so a is equal to a it is a palindrome so we expand outwards again left becomes b right becomes d these aren't equal so this is no longer a palindrome so we can forget that so that's how we're going to check for palindromes but the difficult part of this question is we need to find the longest pandora substring within this sequence so we need to check say if this is the pandrom if that's the longest palindrome this is a palindrome if that's the longest pandering if this is a palindrome so we're going to check for all possible solutions right and update a variable say longest which will start off initially as an empty string update that to the longest panel drop substring that we find within this string so let's run through the example so as we said we're going to be expanding from the center so if we start off at b we're going to have a left and right pointer here check if this is a palindrome it is a palindrome so we expand outwards so we go left and right so that goes there right goes there left is out of bounds now so we'll have to add that into the conditional logic of his pal and we can move along this sequence so we're now a we have the left and right pointer a it's a palindrome so we expand outwards so let's start off at b we have the left and right pointer here this is a palindrome so we expand outwards so left goes here right goes here left is now out of bounds so we check against the longest string so b is currently the longest string so we can add that in there now we move along we start with a left and right pointer that is a palindrome great so we can expand outwards left and right is b equal to b yes it is that's also a palindrome great let's expand outwards the left pointer is now out of bounds so we can check to see whether this palindrome bab is greater than this so it is so we update the longest to equal bab and then we move along in the substring so we move to b that is a palindrome so we expand outwards a and a both equal so that's a pandering so we expand outwards b and d are not equal to each other so that's not a palindrome so we look at this value here aba we compare it to the longest length they're both equal so there's no need to update this we move along to a is a pandering we expand outwards b is not equal to d so that's not palindrome a's length is not greater than the longest here so it's not greater than b a b so we can move along so at d is pandering we expand outwards right is out of bounds d is not greater than b a b so we exit this so this is the solution to this example now let's have a look at the other example so let's say we have let's show the first one see there's a palindrome we expand outwards that is out of bounds so we can update the longest palindrome substring to equal c with the solution we used to the previous problem we check b is palindrome we expand outwards c and b they're not equal so that's not palindrome and that is equal to the length of the longest string so we don't need to update that we move over to b is palindrome we compare b and d they are not palindromes so we don't need to update the longest we go to d is a pandering so we compare b and a value that's out of bounds so we don't need to do anything here so at this moment in time the longest is currently c and if you look in the string that is inherently wrong because we have b and b here and the reason for this is that our current solution when we check for the palindrome we are only checking odd length strings so say when we check b we check string of length one and then if we expand outwards we check string of length three and then if we expand outwards again if it was in bounds we'd be checking a string of length five so we also need to run an extra is pal for even length strings so for example rather than having the left pointer and the right pointer just on one string we'll have the left pointer here and the right pointer here so we can check if this is a palindrome no it's not so what do we move along so we move a left and right pointer is now situated here bb is a palindrome so we check if that's the longest if that's greater than the longest length it is so we update the longest to be bb then we move along check if bd is a palindrome it's not so then we can exit this so time complexity for this algorithm is o n squared we have a quadratic time complexity because we're looping through the string twice one to compare odd length strings and one to compare even length strings and space complexity is of one even though we update the longest and we have space allocated here this is used in the output so it is not included within space complexity okay so let's write this out so we're going to need a longest variable as an empty string we're going to have a helper function called ispal to check for palindromes we're going to pass in the string left and right pointer we're going to have a while loop so while left is inbound so if it's greater than or equal to zero and right is less than string.length so and right is less than string.length so and right is less than string.length so right is also inbound we also need to check whether s at left is equal to s at right so if those two values are the same then we know we have a palindrome so we expand outwards so left minus right plus once we exit this while loop we know that any further strings are not going to be palindromes so what we can return is the string slice from left plus one because we don't want to include the current left value and right and the reason it's not right plus one is because the slice method here is non-inclusive so it doesn't include the non-inclusive so it doesn't include the non-inclusive so it doesn't include the current right value so it goes up to the right value but doesn't include it then we need to loop through the string run is pal for odd length strings and run is pal for even length strings store these in variables so we could have first pal actually what we'll do is we'll call it odd pal even pal and now we can work out the longest palindrome between the odd pal and the even pal so the longest pal is equal to oddpal length so if the odd power.length is greater so if the odd power.length is greater so if the odd power.length is greater than even pal dot length then we return odd pal or we return even pal now we can check against the longest variable we set at the top on line seven so if longest power dot length is greater than longest length we can update longest to the longest power finally we can return longest and then let's give this a go okay so that's been accepted let's submit it and there you have it
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
344
what's up youtube today we're going to take a look at lead code problem number 344 reverse string marked is easy let's get into it so there's a couple new things here i have a new chair new camera new haircut gotta get used to all of these things and i also wanted to start a new series going through the lead code algorithmic questions using python both for data scientists and analysts machine learning engineers going into interviews and software engineers looking at starting out lead code probably going to focus on easy and mediums because data scientists usually don't get hard questions but we're going to solve these using python because data scientists analysts and so on should be used to data analysis with python which is good and python is in my opinion also the best language to attempt these whether you're a software engineer or anything else because you usually need the least amount of code to get to a working solution which makes it easy to explain and also faster to come up with a working solution so that's why we're going to use python let's get into the problem so our task is to write a function that reverses a string the input string is given as an array of characters called care do not allocate extra space for another array you must do this by modifying the input array in place with o of one extra memory so we're not allowed to create another array or create a copy of that array and it should be done in place with constant extra memory of one you may assume all the characters consist of printable ascii characters example would be hello h-e-l-l-o output should be hello h-e-l-l-o output should be hello h-e-l-l-o output should be the reverse o l e h i'm going to present three approaches transforming one into the other so it shouldn't take too long bear with me and let's get started so since we're using python trying to be pythonic and using the least amount of lines of code to get the job done and use predefined functions we could just use s dot reverse which is gonna reverse a string or in this case a list of characters which makes it quite easy right so this is already gonna be a working solution but what really happens behind the scenes is that using constant extra memory what's the time complexity of that solution and is that really what the question wants us to do so this one uses o of n in terms of runtime complexity and then constant space so that would be an accepted solution and we're gonna understand what's happening here by implementing our own reverse function and looking at what happens behind the scenes so this is kind of a cheat code in an actual interview that would be quite smart but they would probably ask you to just implement that reverse function so this works because reverse is actually modifying the array in place if you were using something like that so slicing syntax that would work because it creates a new copy of that array and when you're assigning it to the original array you still use that copy and that creates extra space and it also does modify the input area so we're going to start with our recursive solution defining a helper function and two pointers because we need them for switching left and right part so we call them left and right and we also just want to do that until we meet in the middle so we're gonna introduce a condition of left being smaller than the right that means we're only going to go until they meet or on to the middle because in the middle we don't really have to swap anymore and now we need to swap them so left element should become the right element and right element should become the left element so we're going to switch h with o for hello in the case and uh yeah in order to swap we would make left right and right left but we can do that in two separate lines because it wouldn't happen at the same time needs to happen at the same time otherwise the first value would already be updated and we would have the same value in both so that wouldn't work that's why we need to do it at the same time by using comma syntax here so right should be left the same time and then in order to make that a recursive solution we need to call helper again from within helper so recursive approach calls a function within itself until a certain condition is met or is no longer satisfied in our case so we're going to call helper with our updated index values of left and right and left should be increased by one we're going to start off with zero and go towards the middle so we want to increase our left pointer and we want to decrease our right pointer to also move towards the middle element yes so now all that's left to do is start out calling our recursive function with our initial index values of zero and length of s minus one to get the last index and running that code should give us a working solution so for this solution our time complexity is o of n while our space complexity or memory is not constant because we create a recursive stack actually i kind of tricked you into not implementing reverse as it is implemented because it is implemented iteratively and not recursively as we did here because by doing it recursively we're creating a recursive stack so whenever we call that function within our function we need to memorize what happened the last time we called that function and that creates a recursive stack and that costs memory in that case o of n because we're gonna go through it a number of times depending on the size of the array so that is not constant we're not using constant extra memory of all forms we need to change up our solution so we're going to solve this issue by using an iterative approach which is usually less cool than a recursive approach but in this case it helps solve our memory problem so instead of our recursive function we're just going to rewrite our statement to use a while loop and have that same condition of left and right i'm going to not call that function again but initialize our pointers before we run our loop so that should be zero and right should be length of s minus one again then we do the same swap we did before we just package it in another way and then we also want to do our update so left should be left plus one and right should be right minus one you can also do that at the same time left plus one right minus one that should also give us a working solution we don't build up a recursive stack which means we don't use extra memory we just have our left and right pointer so just two pointers one is initialized to zero the other one to length of s minus one it doesn't really matter here but we just use these two always no matter how long our array is our runtime complexity is still o of n because we're going to go through that array actually we're using uh n divided by 2 in terms of runtime complexity but that's going to reduce to o of n because tending towards infinity half of infinity is still going to be infinity but we were able to reduce our memory to constant memory which is cool and i think it's a quite cool problem because it shows you that an intuitive approach can be better than a recursive one so let's get to the section where i talk about whether that is actually going to come up in an interview in my opinion and if i were in a data scientist interview i would just start out using reverse if i'm using python because it's good to show that i know that and that would probably be the easiest way to do that why should i read the wheel and re-implement that function the wheel and re-implement that function the wheel and re-implement that function that already exists they might ask me to do it anyways and i will probably come up with that iterative approach anyways because it's probably easier to wrap your head around than the recursive one because a lot of people struggle with recursion but i think to really score and set myself apart from other candidates considering it's an easy question i think it would be important to know about recursive stack and that costing memory and comparing these two and saying that would be a recursive way of doing that but i'm choosing that iterative approach because it doesn't require extra memory yeah so that would be probably the solution that's why i wanted to talk you through these three approaches anyways that's been it for this video hope you enjoyed it i'm gonna go through more lead code easy and medium maybe math related questions for data science interviews but they should also be of course relevant to software engineers and similar anyways see you all next time bye
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
1,010
hey what's up guys so let's solve this one zero pair of zones with dildo directions so basically you got an array and uh each array is time i and you need to find a pair uh you can find number of pairs i and j such that s and j and their sum is six divisible by 60. but this problem is exactly the same as two sum right the only difference is that in the two sum that you worry about something but you care about their sum to be something but in this case your multiple of 60. okay so uh for example in this case you can find three of them because zero pair two one player three one pair four and for this guy you got three okay so since it's very close to some right so idea is that uh you just mod 60 for each your time and you create a dictionary right but in this case the do the same thing right your dictionary care about the indices so uh you are trying this and then you create a dictionary to take the time and the list the value is a dictionary that happens okay now you initialize the answer to 0 and it goes through the array again and you ask about where x equals to minus t times j minus 60 and then you check order x in h if x and h that means you'll find possible answer but you only care about the current that care about case that j greater than i right so you need to iterate all the list and then check whenever j greater than i you just add one also you just use it so this is just a standard tech uh idea that you create a dictionary and uh so you can uh from or you can write this code from o n square uh downgrade to o n by using a dictionary okay guys in this very simple question so uh i just i don't want to run but uh let me just run it wrong again oh it takes so long okay so see you guys next videos
Pairs of Songs With Total Durations Divisible by 60
powerful-integers
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
Hash Table,Math
Medium
null
48
Hello friends, welcome to the new video, question number 48 in the list is a rotate image medium level question, this is the question, you guys will get an interview with it has been asked in Google Facebook Amazon by the name Rotate Matric, let's start the yagya. Today matrix whose size and so and have to * can be 323. and so and have to * can be 323. and so and have to * can be 323. Representing and image is called this image, what you have to do is rotate the image y93 degree clockwise so you have to rotate your matrix ₹90 rotate your matrix ₹90 rotate your matrix ₹90 clockwise it is not so easy. There are some conditions that you have to rotate the desired image in place to allocate another two day metrics and to do the rotation. If you create another broken metric then you can feel it very easily and there may be retention but we have to express the change in its metric. If you do n't use it, then how does it look like when the job is rotated? This is your first one, it gets changed in the last column in the field when you unite and we will see it in detail. How does the rotation happen? Your second one is controlled by making the last one longer. gets changed and lastly it gets changed in your first column, so let's understand it in a little detail. Let's start with an example. We have a matrix. We have to rotate this matrix. In integrative voice, first we rotate it four degrees. If you have it, then it will look something like this, then if you add the remaining f-35 degrees, then if you add the remaining f-35 degrees, then if you add the remaining f-35 degrees, then it will look something like this, if you straighten this number a little and write it, then now you must do this. What are the changes in your matrix after job rotation? You must have noticed that the disease which is your first disease has changed in the last column, the disease which is under your control has changed in the second last column which is your last disease. If there is a change in your first column, then basically rotation is said, we have to do the job, but what is your opinion, it seems that the roles and columns are interchanged and it is okay, so if I start again and I say, but the first role is the last. There has been a change in the column. Okay, so if I tell you what was taught to us in such a match that we used to lose the interchange of rolls and columns and it was called Transformer Matric, but what was there in Transform Matric, For Stroke First Column. But we used to interchange the columns very well every day, so one idea is that if first we figure out the transport of our matriculation, then our daily problems will get interchanged, then we will come a little closer to our intuition and After that, we will see the order of our columns later, so first of all we are going to do transferred to format rickshaw, so let's start with the transfers of matrix, what happens daily bank volumes are interchanged, first form is created, control is second. Once the column is created, let's take a matrix and Transport. What is that matrix actually? Your first value will be replaced by 151. This second value will be 1252. This decision will be made and for will come in place of your two. So your for will be replaced by But it will come in the same way that your ka will come in place of seven or your intake will come in place of three. Education for the stomach, please change ka or 9X in place of lump, but if the position of both is there then basically what happens with this concept. Which is your first row gets converted into the first column. Second problem gets converted and the last row gets converted into the last column. This is called transpose of matrix. Okay, so what will happen if I write this for male wise, which was one of my settings. Position 0, even if it is exchanged, this formula will be remembered, but if I take any other index clove like index 213, then it will come to my nature's three two and whatever is on these three two will go to two three. In the same way, the intact one two will come to two one and the value of to one will go to 124, then this swapping is done and finally the transpose matrix comes out, one column gets entered, the first proof gets changed to schools, the control second column gets changed. But doing this will not make any difference to us, we will go to our internal passport, so finally what you have to do is to reverse the order of your column, how to make 1898 which is your last column, you have to make it the first column. So, from your second last column, you will make the second column, from your third last column, you will make the third column, because by transporting, the first love is getting a straight water in the first column, but in reversing the image, it will be in the column and everyday. Interruptions were happening but the order of that square problem was that if it comes a little reverse then we will do this our friends, take out the step vansh transport, reverse the tattoo column, so let's see it in an angle, how can we do the code, how will we do the same in the court. Friends, first, we are going to transport the matrix, take out the transport, second, you have to reverse the column, this friend, our answer will come and from this we will change the metric, we are not making a new one, okay, the size of this metric is N2 and so. Let's make the size above first so that we have to write a little less code. Okay, every evening column is the literature of both and there was a formula for how to transport it. I will tell you by writing it in the code also, so first I will take the form. ICC World T20 highlights and i plus and columbus how to walk points pimple to i jewelers private plus one so what's happening in one when you were on withdrawal what was your problem you transferred schezwan column and whatever was there till then ok But as you reach 100, you have transferred the column with 0, so now your columns which were governed by index two, then you are on the road with index two, you have transferred the column behind, so your column with It starts with the tour because we have worked before, hence it is a pimple to the eye and what is to be done in this, whatever value you are on, break it, why at one time because we are going to make changes in it, okay Have broken it, now we can change it into Matrix I, look at Matric Jiya, make it a little more, get this and Matric I0, make Matric Jiya only, as you saw, exactly interchange and there are Rhodes and Kollam, okay, what are you going to do? Yes, if you want to select this ji1 le again, then make it I and the reference that will come is already saved in minute time, so we will make it equal to time, so this is our proper formula of transport and from this First proformer will change to second in schools and will change to its column. Okay now second chapter has to be reversed. How to reverse the column. Make the first problem as the last problem. Make the second column as the second last problem. Make the third column as the third last problem. Reverse. Do this and your no degree, we will assume that it has been rotated, how to do this, we tape again, first save the time, what will happen by valuing the column, if you recognize the last problem which is on the zero column, then how will you save it? All you have to do is flip the column to reverse it, then the index of the last column is one minus one and - one minus one and - one minus one and - Oye, what will happen from this, the first class will go to the second class, I will remember it tomorrow, if we keep changing like this, then we will have the same on the last column too. If you want to enter first then this is the difference of first and if you are from tempo then it will be done in this way and this loopback will actually work just because if you have to stop the eyes setting on the middle then in this way the columns will be reversed like this and I thing. Our work is done, once we compile it, we check that it is accepted, after submitting it, we also submit our code and it is successful. You can support me and my channel with a small donation. So that I can keep making videos for you guys in the same way, you will find the donation link in the channel's 'What's But' you will find the donation link in the channel's 'What's But' you will find the donation link in the channel's 'What's But' section or in the first comment of every video, you can go to the 'About' section of my channel and in the first comment of every video, you can go to the 'About' section of my channel and in the first comment of every video, you can go to the 'About' section of my channel and access this Google Shadow. You can see it in the shape. Which interview questions' video have I made? interview questions' video have I made? interview questions' video have I made? Which list questions' video have I made? You Which list questions' video have I made? You Which list questions' video have I made? You can do voice search for A Cat. Channel related news. Which video is coming next? You will get all the updates. Thank you very much for watching this video. Lord bless Ajay MP3
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
10
What happened in this video, we have this registration matching name, Kashmir valley has a very interesting question, the question is, you have got this team, now you have got Mississippi for stitching, Ajay has got this pattern and you have got this pattern, it is my time that the star comes. Dot Servi gives you this pattern, you can add any one as per your choice, if these two together can say this, then this can be said that the numbers have become magic lines, the numbers will become office, these two together can become this. Here, these two together can become zero and needs. I want to tell you that there is nothing like that, so if this A comes together then nothing becomes nothing, then basically all this gets erased from here. And nothing comes in between, so after all it came below this and the match was not made, so this is the thing, it is not that Aishwarya, let's try something else above, if this star becomes one, if the star disappears and becomes a gas. So this excited one would work, the other one would not work if he became a star midfielder if middle school and then remove himself so that now remove himself so that now remove himself so that now something is wrong if this is So this return has to be subscribed, is So this return has to be subscribed, is So this return has to be subscribed, this will not be able to grind the purse, if this hotstar is muted and two dots are formed then it is a coincidence, this is the secret of counting the holidays, if this dot is 4 minutes, about 3 idiots sexual, then this is true, this is what happened and You can subscribe because so lottery if this will not become anything then do this tea and among yourselves if this is piece then piece but if this is piece yo pieces that is this achievement service and add will start so for this The pattern is through Yuvraj, the start dress became dot, triple dot became piece 331, if he went to us, the match that always came from us, the star cast, the balance, he became him, this match, IPL match, this doctor was the report, then he became like this shadow, he became pistachio drink, then he became behind. P and 67 came from the cow behind the back, the complete pattern is done, so this is the type of fast, now let's do it again, let's see if we pass this time too, this time it will happen again, it will be seen, it is important to understand the question, then mentally we will move here, okay So the second pattern is our mishra42 four husband star now there is a scar so we are that agricultural field if this star is made black and its hidden that if this star is made one then the stencil is like this Dhupiya if this start Now this smart boy has become like this. Smart boy's hidden star plus has become such a smart boy. Smart boy, so this is something or the other, there is nothing to be done. Now if this star becomes like this, then for this he has passed further under the other association, so there is nothing. It is formed when the scooter is only those people, then there must have been four in it also because I have chest size, it is sex with it is sexual with it is with pieces, if you go with it and then you will not be able to believe, then this pattern is there again, okay. All we have to tell you is that this pattern is pass, you feel that when you understood the question or not, then I will try it again and show you what has happened again. Mi add star that I feel that it is difficult, then you face problem in it. So that's why we don't want it above and close. It's been arranged. This match will be put together for emergency arrangement. Either this star will become black. Make it black. Then its shadow is gone. Either this star will become black dress. If it becomes skin then good next. Irrigation is failed if hair style is double noose skin like skin chi like this and if you want yours then this start can be passed only by becoming SS then this is passed this was passed yoni chai is passed now this star has to be deleted Either this star will become black, it will be dealt with, it has a pen, either all these apps will become 1 inches, the other lion is on JP, or the vest will become asked in SSC inches, I have a crispy feel, either this skin of tex will become dead skin, good singer. Inches and PHP came in 1953, now three garlands will be spread all around, the star will be spread if charge brother, 1 inch from here, 1 inch like this, 1 inch from the bottom of SP, leave the next one, do it in this manner, there are four like this here, neither from this till this This with this with saree, these people take it with feel happy, which is the power of Pet Yagya which is passed in Agra, personal does not matter that if there is an earlier stance, then it is passed, okay, so now we have to call an option, I think. You have understood that Dot will cancel everywhere, even if it is a character SIM, it will be canceled and there is a scar somewhere or two stars. You dad does not have the idea that if they do not want anything from Acharya Anil Purohit and doctors of Ras. So who will pass before me and who will pass along with me, so I have to shave the first one, how to do it, I had to do it in between, how and why because first there is water, then if you do it because the plate comes here. A Blank PM Noida Is Char My Daughter Papaya A Do That There Is Any Meaning Like Here Try Here That It Is Like The Idea That If You Think About Sleep Then You Will Be Easy To Understand Where What To Start Now This Is The List Where is the smallest problem in this fort, the biggest problem is in this, Ajay, that you will be busy in the mean time, when we leave the lines, S8, I have to maintain this ABP first, here I am a lazy teacher. Complain let's talk to me tomorrow, it feels good to do it, okay, now there is water, but we can stop, before he starts, tell me the meaning once again, water has not flowed again, don't talk now, bye, it is in between. So see what will happen in this block like this so this is Mi Spartan Mi SSC request Okay so anywhere like this we are going to do so now I talk about here first black pattern in addition to the lion By subscribing, you will not be able to subscribe cooked set my screen, you will not be able to sign the black pattern, this trick, you will not be able to subscribe the line pattern and that system, it can only subscribe to the blouse SIM, you will get the crop trapped inside all the other animals. Now let's talk about this will do pattern when the line commits suicide, he doesn't want us to back up the call, let's mix it up a bit if the last control of the string is Patton quarter like now let's talk about this post - and MIS Trick Cricketer and - and MIS Trick Cricketer and - and MIS Trick Cricketer and If the figure of the pattern is quite similar then you look above the dial. If the string and the character of the pattern are SIM then you definitely look above. If there is a dot in the pattern then also look above the iodine. I am telling that now because one came along and String and train lion and pattern character is not sim. If not, then you close your eyes and pour sauce. We will discuss these three rings above. Rice is victim of premature ejaculation. Chapter of senior officer pattern is sim. You are free, so now see the degree above, this is you. There is a dot in Patan, if you sit in the train then forget it, we will take it up in the reduced pattern and will try. Okay Now we are thinking why irrigation is happening like this, so right now at this point we are thinking that meets the embankment. Now the line would have been custom because this is not a simple time, if it is simple then let's take the first column as global, it will spread everywhere, it is okay because when you have sour, finally, but have seen a little above these. So friends, after watching this video, it is said that the characters do not like it in the war match, let's talk heatedly here, Mi S, we talk about this. Do Mi S4 I don't tea This black tea does something like this There is nothing in the balance sheet Otherwise doctor Ek Rachna someone will be equal Mco It should be this star I know it can become a line But the rest should be greater Neither this Be it a diet or a chapter of nothing, we will put a cord in the crops, where there are stars, we will talk about the problems, where there are stars, there can be a walk, where there are star golfers, in the schools, you look up for two days, who will put a halt, simply told that I am definitely telling the school, this is the whole one, so it will work in the entire grid, talk about Aslam's, this is a great according to the great, should I give guava to the purse, I have told you, is active in the crops or does black match England, the rest is a lion. Ca n't gusai Aslam's rules If character is pause then fox is this way then press two rose up two now there is more dot this is the pattern subscribe the channel if you like it or not then should or should not, okay I have done this in this way Hey look man, there is security after the star so that there is an increase in detail, this chapter increases that it disappears and becomes nothing when an SMS comes, can it is its beauty, it is suffering because of this If he becomes nothing then what work have we given to Mi Star that you all subscribe to the line pattern, do you like light subscribe to the turn then plant it is exactly in the line we dog is not even a single test then This is the best way, what is the best thing that can be done to clean the star black this year, he is the one who called me, I will go to some house, I will not get anything Aishwarya, I thought that he should go away or is this how it is or is it like this It was like this ad can do the best to get a match with black that I will go so I will go that way You asked me that Mi Ad Star can subscribe to a black so he said I am in my best way I Disappears you see this is able to suicide so we two look up we can do this kind of Mi Lifestyle so Paul should always say no if this tell if this solution am star all this just like the line What would you like if he did this? If you think about why it becomes so, then he would fill it with strangeness. Once he becomes a star or registers, then first of all, he embroiders the dough with tea. What is a full tilak? What is Mr. Black? The website does our form. Let me look up and pounce on him and that is why he will disappear as per the order, then it will become like this, should we fry the Bloody Mary, it used to clean the black, in this case, we will not put force here, you will put it as per the turtle gone. Now I have come to Ahmedabad, so now we are the youth of a star. What glycosides does this star do? The first star will be gone. Brother, if we leave, then just see whether he referred the employee or not. How did the person do it? He used to go to Bigg Boss and as per the above reports, he goes to Yau, while staying there, the answer statement will come, then among the first ones, Simple, where in Jhalawar, Simple King, if this ad is cut, if the character comes, then Force Four comes, then look away, above, Simple. Why but why because there is a star on the top, it will disappear and you can see MI with like and anything like a falling star for Mi, we will put two there with fruit, then here if I want, that too with fruit. This was me for two moments, that too here too, I am the first penman of all these useless things. Remember, you have to look above four heads. Is there a dot in the buses or is there Twitter, then falls here, rest of the deru is given, it is not mentioned in this cream yet. See, now at this point you are using. Take 2 minutes above this point that at this point you are chatting with us about what and clears the pattern entry. Now see that this batter is the same with this as before this. If anything happens before this, we will give this, we have subscribed to, does blank subscribe to blank, MS Word declared it, so the rest of this means just mix and in this also the rest of the meaning of black, so we saw the sale here, I went to the account. If it is only a character then we will look at them, leave this one after creating it, leave this end, sorry friend, leave the cigarette and leave this person, only the upper part of both will remain, if you look upwards then you would have come, I understand the point here. I may have come in but the apps will get deeper and someone will understand. Okay but let's see our one here. Does Ambassador do microsatellite and pattern? There is no last scene, so we have to ask further, this same bean in the earth, this is further, there is nothing in the pattern, in the posting, this is ours, I have written below above, pattern process bean, for this point, this earth, this is mine. This is only I have written to you, there is nothing of the ritual, there is nothing further and this is our SIM, so it will match with the first one, otherwise this cream can keep them, when the skin is not equal to the cricketer's test cricket, then it would be equal to this above. Rekha is there, I didn't understand it, but I will understand it in future, but I fill it in this world, if it is equal with MMS, then voice is equal with SMS, this is flight, everything is equal, then everything of Rolls Royce is equal, then punch is here. It is very hot here and there, because we have come to the police station anywhere, okay, so there was no worry, it will start taking the form of 'gee', if okay, so there was no worry, it will start taking the form of 'gee', if okay, so there was no worry, it will start taking the form of 'gee', if you listen to it a little older, then this is the problem that is often seen, why with children? First sit in the second over to understand and first wash it because there is no shame in the productions. If you were able to understand then see its problem, what is Mi pattern and confluence is Tuesday, my YouTube channel, I am below the soldiers, last equal. Mey Simlipal Mi Pattern can join PM sometime because I am aiming at you are ok so come from we would do the route think here if not today then tomorrow now where is the list what is the problem also it was done properly so both of them had done that here See here this was Asaf was unmuted and let us see the answer of love from here a little of this well you here in here I have a little of this so here what we are thinking that Mi Cotton's MI this Will you be able to do the side, the question arises, Mi pattern is this trick, the recording is from my appointed ICS officer, Sonali Bendre is 20, if it comes straight, then how will you toss without a moment, this box is between Mi pattern and MI aspirin of course because Along with the character itself, no-no mission2020 Leaf and now for the itself, no-no mission2020 Leaf and now for the itself, no-no mission2020 Leaf and now for the first time for you there is a different understanding point in this box, now look what you are seeing my what mi6 fights, mi mi6 likes, it is definitely there. If these are passed then he made the question what but if Mi Adams would have liked it then he would have subscribed to MMS then let's meet the question is our Ja what M pattern is Mi asset side so here it is, it has been folded since yesterday. So when character is equal then finally see Kayakalp is equal to yoga assembly polls and dont put cumin seeds in it to see monk because not scientists character dot apna channel character if war M.Com final cricket that is my and gives everything in the morning M.Com final cricket that is my and gives everything in the morning M.Com final cricket that is my and gives everything in the morning okay then typing If you have this white layer of white layer, then I will try to fill the block without understanding and speed, after some time again in some support, I will do the same problem again in the next remedy, I will try to explain that once it is clear, then you are all blessed. If you try to clean solid waste oil IS DIFFICULT FOR US IF YOUR DEVICE IS NOT GOOD FOR CLEANING, GO TO THE NEXT IT IS NOTHING WHAT-WHAT MI WAS Discussing Something NOTHING WHAT-WHAT MI WAS Discussing Something NOTHING WHAT-WHAT MI WAS Discussing Something Will Remain Now Let's Talk So Here's What We Are Talking About If it is in the pattern, because we will mix it with it, now we will move upwards from above it, now the first difficult cry comes, when the star comes, then there will be difficulty, now all your tears have been done, only your starry rose is left, today the sun sets, Rudri fruit. Now once here there has been talk of Mi Star, the talk of master in different series will increase that after Maheshwari will be there for Mi, Sonu will be there, so first let me tell you once Mi Star will set them individually and see that our chest And uncle can become Mi star. If your star becomes black then Mi pattern remains. If it becomes like this then it becomes pattern. If it is made of them then if it is from 000 that like this he can make any number of them. The anger of writing this. He comes in Bigg Boss, here you are a star for some time for nothing, now a pair will be formed in such a way that the sodium balance will not get confused, we will double this news, the star code will come to replace, it becomes this has to be written, another way is also this. I am a star, if my mind goes away then what was the other way, this issue is a star and still hearing is given in the star like this so this youth is gone and strike in is fried Chunari This thanks is equal to all The best this thing is told by this star of thinking will ask two uses start teenager mishra0 This of gold this Robbie had stayed nothing like this otherwise mishra0 If it falls then basically writing this is equal to writing all the how it is important to think At that time, this is what we are immersed in, if this message is sent then we will take it back, you will understand very well how this represents all this, I tell you, look, this star has faced this dilemma and yet the problem is this - and He has become a star, and yet the problem is this - and He has become a star, and yet the problem is this - and He has become a star, now next time he will become a star quick, so basically he gave us in Mi Star - Dhindsa gave it to us in singles for the first time, he - Dhindsa gave it to us in singles for the first time, he - Dhindsa gave it to us in singles for the first time, he said in star, if he died without giving plaster on the chair, then he gave only one in star for the world, or next time also breast Coming gas decker, if it would have survived then Mi S8 would have become the last star and after making it next time it would have died. If Essar would have died without giving anything then MMS would have been the balm on this issue of Mi Star. SSP has shown that twice it got something in it, see these. If you want, you will have to level up a bit, once more, give all these kisses and still this white replace and star for cleaning and now if the star gets destroyed then Mi replace device is first on the local given website or at this given time or Is diya Sawaipur or did it become faster to maxx patience se me to bijli writing this is Delhi cantt to writing aa hai ki aapka jo mi is aapka jo pattern hai mi start you can say dadi japle 2mi aur hai - and mishra5 tu Different to come aur hai - and mishra5 tu Different to come aur hai - and mishra5 tu Different to come and Mi Lifestyle just say this na play means so I can understand extra that different to Mi with Mi means you are selecting some white stock good pride in the institute - and MMS and mission-2014 good pride in the institute - and MMS and mission-2014 good pride in the institute - and MMS and mission-2014 and among these If that string matches with anyone then it will be the time of semester. Another way of saying this is that you are matching everything in Mi Lifestyle. Good matched with Mi and Emma will come in the century of Apps Star and Ugrasen, then she will I will be the second match of this, Bijli, matching with this is equivalent to matching with all of them, that the police has done the cleaning in such a middle and still, then next time it will become a form, I will die, you will become my mother, if that next time too, add on a question. Said that the double address will work and then if there is a death then it becomes MMS. Okay, it is important to understand its great importance. I want to say it again very clearly so that it can be understood that see, listen carefully. You were matching a woman with a star, you wanted to go Amavasya Rustam will decide whether or not instead of making tools Good night to all my because the star went black if it did not do so Good night but SIM to Mi if Considering the extras as twos, matched with his routine, I am smart, so from my heart, if I got a test match with any of them, it was like a dream come true. Suppose if the star football cup dip line to the Chinese office staff, then it dies. Rotting hormone kiss becomes such a code object, it becomes such a code thing, if it goes in this compact If there is a match then it becomes smaller then you will become less or somehow friends will become a shop, okay then Mi Lifestyle is equal to all these, why show the lid where I have written these two from the family, out of which take the married woman at the same time. Star's this - married woman at the same time. Star's this - married woman at the same time. Star's this - what are you calling it jobs - or Mi ad star what are you calling it jobs - or Mi ad star what are you calling it jobs - or Mi ad star that star has given this dowry. Okay so BCEAO we will do this instead you can match these two. You can do this trick after this and dance as per this review. And I am so that this one is equal to match all these, how so, join it, to watch the match with this Amavasya Mi SS Star Seven, instead of matching with this Mi SS Ghumaili, submit it to the triple star society, then you All these will be found and will be left out, except this one, it will be found on vle mylife Mi Triple You can make many more matches instantly. If you want to make a match with Mi Star, then the dream of MI and Mi Lifestyle will come true. Well, if this message is 24, then you are convinced of this. So I carry this with me, I had a keyboard in it for an important reason, that was that some stringer has this pimple, some woman has this Mi Ad, instead of just matching someone with Mi Star, we match it with Mi and see that it has Mi essence. We will see that if all the matches are played then the problem will be solved, so the decision of this match is very important for us, so I tell you that this is very important for us, I will call you in this room. Okay, so here's the question: Mi Ad Star, does so here's the question: Mi Ad Star, does so here's the question: Mi Ad Star, does Ambrose fight? Question that we are getting: Does Mi Star getting: Does Mi Star getting: Does Mi Star satisfy the name? What did I say, you see this, will it turn black like this? Will Mi If Ambrose fights then see this and well I told you that Mi Ad Star is what excites you with the tempo, I will get such a thing and it is better to survive, okay so let's see but let's see this, the star has disappeared, I told you that What was the start to make an SDO SP? You can do this on my apps time now you type ok so one he sexually exploits you for that you will get two days above Mi Adhik Singh how much will it be and 2 crores in Patan If you went then testing above on the pattern is so much because after doing this exercise it is new here now it has been talked about such a star we you knowledge world here so where should I find this star Hindi name box okay don't worry phone forget this place its review Try this seminar is happening, this is MB's dream come true, if this Star Black also becomes this YouTube line and Saras Dairy is busy then like this, even the blender is not able to understand this, it does not give anything in this. Paul, if this character, this one is not a battery at all, nor any officer, this Jhala and Vala kiss can see that in this way it will increase only when it was Katrina, why because this stuff and mode will give this, here it has become black. Which river is it by the way, gave its white all seen in the star which did not give this so gave us in Mi now this is this he is going to give this so first I gave it an area health tell all and in this case it is okay if this is Sandy Hurricane So in every case he will get trapped whether it is of sexual quality with NSS then because our star was dancing with love like this he disappeared then he has MI number there from Paul and SM is this article otherwise look at this side There is no need to have something with SM otherwise Star Zubaan and Dasde Aao Anytime You could subscribe us Deathly This is absolutely not the decide element Why wouldn't this guy not have this Sides May be he likes you If it takes time, I will do 245, then you will take 45 more dry ginger. You will understand something. Now let's see all this. We are watching Mi Star with Mi. This time understand a little, Mi Star with Mi, this portion must have been appropriate. I have given some media information. So Mi is seen with Mi, so it is ₹2, So Mi is seen with Mi, so it is ₹2, So Mi is seen with Mi, so it is ₹2, you got the other beauty, semolina laddu is the exam, okay, let's move ahead, do you like to move ahead, do you understand this in this somewhere like this, it will take time in this box Have you put it in Mi Lifestyle - Does it enjoy a Saturday? Does Lifestyle - Does it enjoy a Saturday? Does Lifestyle - Does it enjoy a Saturday? Does Mi Ad Star? Does Mi spy it? Nice born, this was it, disappear our questions, What is this Mi pattern, Mi cleans this team, which I will find here, Mi Petrel. Used to fold it, went here What is Mi Pattern - Encourages does not What is Mi Pattern - Encourages does not What is Mi Pattern - Encourages does not call Now used to make the second one This gas decker and will stay alive Will become meaning Mi ad is star Absorbs many of Mi Lifestyle is here No problem give It has become a big problem, but you are equal to the address, so this cut is why the crow cleans the dark Mi. See, whenever you solve a point, worship makes you a big problem in the description or in the DP. Mi Story - There was a makes you a big problem in the description or in the DP. Mi Story - There was a makes you a big problem in the description or in the DP. Mi Story - There was a problem where it became My apps are gone and this is my, this is the lower cloth, the upper one is 45 liters, this is a big problem, the big gun will not go down, there is a recipe, it is not clearly visible, okay, so we cannot solve a big problem, we will have to make it a smaller one. We had added extra, he cut it off, then what will remain of Mi Star too? Re My Star Vijay Mallya. This experiment happened. If you add is equal then Mi Star Vijay Mallya has this problem. He used to subscribe to ISI. We saw someone doing festivals. He doesn't do it, why didn't he see? Does Mi editor type a reminder add on climate and does the same microsite. He does it. If you get both cigarettes, then it is two. If this question is understandable here, then we should stop here and think for a long time. If we should do this, then this is where Pawan will understand. Let's write again. We were talking about Mi stars, so it disappeared like this, I will not come at this time or there is a small problem. Does Mi pattern satisfy MIS? That's why we did it two days ago. See above Amazing to is not satisfied, then this is how we know Sir, this SDO SP Anshuman can but did not ask him to make many, just tell him this, Mi Ad Star had selected and fed him earlier in the match, it was boiled. In this, cash withdrawal is still made to survive on this side. Festival side does the structure in this box - no one was seen on this side. I - no one was seen on this side. I - no one was seen on this side. I said that it is just time and by the way, this is the problem of four more teams, it has become five voting. You wo n't get two big problems, no big problem, the goddess would be lying in the dark, so after cutting it, we will move ahead, that's why the SMS was there that you should take it away, now the problem is left, Emma A. Pyun does this point, where does Mi Star rise from? I used to do bye posts, how did I do when the song was sung, Prem aahe badal gya, but the answer has to be found from this box and the other accidents, so now I will tell you the account of this, that in August, the vases have started getting cleared, brother of four. It is like this in the first floor, all the qualities which will be taken by both the simple ones, there will be lakhs of expansions, listen carefully, apart from this, if the expansion comes, then you will give two above and maybe one look back in this festival, but you will see this side only when the tester chances are backward character of yours. Be equal with the free character, okay, you started thinking after a while, let's go ahead, let's know, let's do a little more where and here I will complete the story for you, where the solo is, Mi Star's reminder does special, there will be banks already. Star star if it is black or mi4a - have to see two days above or mi4a - have to see two days above or mi4a - have to see two days above MS Word Now this is the last along with this and when the skin is equal to the last option of star then I just Mi editor that in Pak war at that time star Made Vinod Noida and gave war to MMS, by the way it was given in this way and this question remained original singer is to given and its last eaten this festival then Mi Star V S Naipaul V S This column is yours if you second semester pattern seconds The one before the star, if the lion is equal with the elephant, now this will also be seen, both the pieces are equal, there is no limit in this, because Emma used to do a peon, so it is lying here - you used to do the peon, so it is lying here - you used to do the peon, so it is lying here - you used to do the same, think like this, it will become gas, Prema will send SMS, that's it That a column and tries to explain that emma apps york on saturday cleans mi star's maza-5 first such cleans mi star's maza-5 first such cleans mi star's maza-5 first such disappeared mission-2014 and this SSC ca disappeared mission-2014 and this SSC ca disappeared mission-2014 and this SSC ca n't do it anymore so there is no need to see it This can be equal with So either now before the last wire if all this no then you don't have to see this second one. If the department cuts then Mi Lifestyle - after seeing the - after seeing the - after seeing the special cover of SSB for Pakistan you cut if. It would have been so but it is not so I simply folded the double decker, I am fine, now here is Mi Star, now see, now you have to think, now here I will not give police, this is my star in this box, 2mi Adam, you have to see a dabi. If I say then we will see why this thing has to be seen every time whenever it disappears it cleans the Mi mi6 and the other but now let's see whatever ad eats it means Mi star on the sellers and this is our mission- 2014 when the exam is our mission- 2014 when the exam is our mission- 2014 when the exam disappears Mi mi6 likes it 2 went up and saw Amazon does not correct it then look here this release made big all its increased from four to five and this is such that your mi6 this one ate this one this SMS It is eating with this triangle it was not given like this he canceled it like this which made it smaller which caused that so this one is big and like this white and that youthfulness this is understood so when your before the wire at the last sin of The moment will be equal then you will see all these both outside then ignore them either two and all the last one which is the one before the city wire of these last pattern you this is not a peace with the cigarette since when it is not there then you will see the simple above then here Let's see, the acid has broken the base, there was a difference between this and this, and in this case, if there is acid, then it is simple. Full will be seen above. In this case, acid is no duty, then simply or Rabba chords, acidity is then simply Arpa calls. If acid comes then it is a forgotten box. 5th day happens, so this letter will now come with us, if four will come with us then what will come then it will be far away and record break can happen on America also check and time one column to left return gift of this titan star poll Star is equal to last week practice Now our knots are ok so I must do it for you and if you first classification is equal then you have this piece is equal you are equal-equal you piece is equal you are equal-equal you piece is equal you are equal-equal you are equal-equal if you are equal-equal then there are equal-equal if you are equal-equal then there are equal-equal if you are equal-equal then there are two Breaks with some fear Raisin of dot is regulator Has become equal with return Looked above here but false direction Looked above equal Chords description Seed above equal If becomes equal with calls and das Diary Dot becomes SMS So below that it becomes and if it is not going to become this then it will become this see above plus is with batay here exam form dot with this so if we look at this turn then will make two then we will see how it will go here Emma A Star IS Not A My Star I Don't Chest Size Mi Star Reminds S6 For Breakage Abs Cancer Star Emma Likes It And Start Replacement So We Here Star Rudra Mi Star Aaye Time IS To This Side Controls yes that sexual union because dot s become president of sirsa speed of this time president of sirsa speed of this time president of sirsa speed of this time dot does acidity so in that case always up two up and accepting a tu denge in this it has draw android every quarter always munna I had said that this was what I had done in the room. I had erased all the wrongs I had done. I had given employment. By erasing Bhagwati's mistakes and perhaps her courage, perhaps her mistakes, perhaps Arya Rudra, if you had four, you would have to see me every day. Whatever your doctor disappears, I would have to see him. Have to see all Dual app, have to see it, if the parent's character pattern is Crystal Reports Avtar Singh elasticity, then if the parent's point is its pattern question because of all the dots, it has to be written every time, then in that case there is no need of a Guru, then that is. Here I am all this but let's talk about the campaign, this is the star and the product, there are always two on top and this on the left, then it is double, both are Vishnu, both are admitted, he has tweeted, both are one and two, why are you both back in the shops? Two is you 12 I in this and two in this that now equal with PM Nifty 6100 Special Frontier Force PAC Certificate Benefits such is equal with 50s so speed is that dream defect is with back Bermuda Triangle above sunshine with PP equal triangle above through Speakers Gram Paneer Balls Now all is gone so now on that the wire is this PM it is equal not only two but three stars and if you have come here then two are simple rising stars and this honey is simple above three stars and this is simple like this pistachio above And this is aaye to simple do up to special guest star and this is to simple do up to 3 star and this is to see this twice also and see this Because this is 30,000 and this PK Sharma Because this is 30,000 and this PK Sharma Because this is 30,000 and this PK Sharma Sharad can see this variety here that star and this is here and here with both two pistachios and below this officer came all this we should see only on two so through any case There are pistachios and this is a piece, so here also in the accident, it is two stars, and this is a piece, two above, here too, it is 3 stars, and if it comes, it has simply come up, so where it is here, we will take it on time and M If false Ayurveda diagnosis calls come and from S2 Bigg Boss is Ayush business then diagnosis is for IAS then simply stuck Aircel SIM from which it has come then diagnosis is rule IP then simply force IP then simply calls come then Chue from Diner is the last one Came the answer with complete shock of the whole pattern, you must have understood everything in 19th, brother will tell you in voice mail, it is very simple, start coding from Russia, we have taken all that you call love this. After we have become dependent on life, maybe I have forgotten, maybe I have switched off the alarm, but at that time I look at the form of Ganesh, I have also talked very gracefully into the eyes, maybe it is a rule, maybe it is good, if the first question is that The first column of this mail was the rest of the mails, I will always call you, Chap, in fact, when you come here in the store, I will always call. In the rest of this column, when there is no star in the pattern, there is no subscribe, if you want. You have come, this is the one who is first inside the DP, she is the anti-dumping character, then Deepika Commission, is the anti-dumping character, then Deepika Commission, is the anti-dumping character, then Deepika Commission, I must have heard this in the pattern, who is the control from inside the OTP, I will not do the gang's work first, oh later, throw with the true controversy after. There is a golden phone with a second, so whenever you put it in 1 liter in cotton tight 28 out of Amazing - Job - will tight 28 out of Amazing - Job - will tight 28 out of Amazing - Job - will be because look now look at this first this is in schools towards Aslam Videos character is with Singh's skin problem SIM With the first character, let's remember to mention what I heard, what is cotton, what is that truck, daughter at minus one, if he is a star, friend, he is an artist, then it must be something else, otherwise, do Pulsar blindly, both go back, both pieces. Why should I tell you, brother, if it is a star, it is a trick, it will disappear, then you will stop, I told you, and it is definitely necessary that I take rest of the sorry, now we will take out the village, it is a village, we will take out the character of Singh, now how did you feel? Is the character of the pattern 14, will we set it, is this pattern equal to the Cricket World Cup or not? If it is a blot, then I had said that we will go to Tiger, we will come to minus one, we will eat the food of minus one and if the characters are equal to Dubai characters. If yes, then I had brought it big, if finance1 is not equal, then it is the result of blind eye. Okay, now there must be something here, if in this way you have to look far above, then you have to look on your own, Ajay has been robbed, but when I am saying this, You are feeling scared, it seems that there will always be two curtains open space, like if in this pattern, a star is given at the beginning, if this star is given, then if it becomes K in two chords, then receive it, from here, K leaves it at two, if the part is given, now we Let's do it whenever the pattern has started, expansion is required, some printing rate is required, expansion packets are made, if it is imposed on the government, then there is nothing to understand, if the famous tractor has to be repeated, then in the beginning there is no meaning, we have taken Azhar, it is okay, then when the share remains. You have to see both the legs, you have to see the last Olympics, now you have to see when to see the skirt, it has a star on it is not written on it, set this third volume, when to see the doctor, when is this second last character from the pattern. Either this command, this team, four cigarettes, this man is okay, so here I get the item setting, last character, police, return that pattern, 9th class tractor and subscribe and if in that case, then in that case, you can make this gooseberry long effective. Will you put it in this, what will you do for that, you have developed IA- do for that, you have developed IA- do for that, you have developed IA- 2 and this one, so in this case you can do it with yourself, go anywhere and do it with someone else and you will DP off the previous problem of your hero for more time. That by doing this, one day a modern world will be lost, dear, your words will remain in the world Seeing this, the dark fair lady sitting behind the curtain, from your mind, that the dark fair woman sitting behind the curtain, shoot, patient, that this string, mother, is small This bond is not broken teeth, I get the result, now let's see and if you submit and enjoy, then it's good, love, submit, then I will return, I was feeling then that I copied, then we will talk to Ajay that he Khel hua hai ko loot hai bakul tu bhi dhara banna phir duniya se dol ke din dikh jaaye maa character 1992 You must have understood if it is complete if in this I have shared, subscribe, like, comment, share. Is
Regular Expression Matching
regular-expression-matching
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where: * `'.'` Matches any single character.​​​​ * `'*'` Matches zero or more of the preceding element. The matching should cover the **entire** input string (not partial). **Example 1:** **Input:** s = "aa ", p = "a " **Output:** false **Explanation:** "a " does not match the entire string "aa ". **Example 2:** **Input:** s = "aa ", p = "a\* " **Output:** true **Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ". **Example 3:** **Input:** s = "ab ", p = ".\* " **Output:** true **Explanation:** ".\* " means "zero or more (\*) of any character (.) ". **Constraints:** * `1 <= s.length <= 20` * `1 <= p.length <= 20` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'.'`, and `'*'`. * It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.
null
String,Dynamic Programming,Recursion
Hard
44
61
A higher oil welcome to learn to repeat step is exactly the same day Vinod Tubelight challenge the name of the problem eroded list electronic products given link list voter list various bike places where is not getting a co select login the example software 's is to end Villages 12345 After Five 's is to end Villages 12345 After Five 's is to end Villages 12345 After Five Years In All Situations From Right Back To Go To Note Specified In Adhir 1234 Subscribe From Left Side In The Length Of The List - The Video then subscribe to the Of The List - The Video then subscribe to the Of The List - The Video then subscribe to the Page if you liked The Video then subscribe Luta Slide Which First To Will Be Demonstrated And A Guy 10 B Road Dispute 080221 Nagin To Be Road Number 201 More To Right Is This Point 210 MS Word List Wazir Weight And Acid Stayfree Healthy Sexual Middle Age Will Always Be Id Against the world of the subscribe 4,320 the same 2009 2013 subscribe and 4,320 the same 2009 2013 subscribe and 4,320 the same 2009 2013 subscribe and 123 others like this sabki news 10 clisters circular left right down that in the 2012 hands free the four 210 paay andar ghus back to one are currently this is my head on torch Light Vanaspati Great Batify Join My Father Is The List Back To The Storm Destroyed In That Case Its To Right From Her Right To Remove From Left To Remove This Length Lee - K Person Subscribe This Length Lee - K Person Subscribe This Length Lee - K Person Subscribe - 2 MP3 Subscribe 90309 - 2 MP3 Subscribe 90309 - 2 MP3 Subscribe 90309 Please Remove This Particular Connection Close Swimming Connection Adheen 5123 Subscribe Now To Subscribe To 102 108 To-Do List Will Give The Length Of The 102 108 To-Do List Will Give The Length Of The 102 108 To-Do List Will Give The Length Of The Year And We Were Agitating Villagers At The Time The Can Join In The Last To The Head Of The State Of The Best Us Of District Somvanshi To That was performed at times for operations that is when find the length and join in oil to add that agar man sider doctor just need to go again proved her till I length - that agar man sider doctor just need to go again proved her till I length - that agar man sider doctor just need to go again proved her till I length - k right sonu ansari milk se travels from the head to my length - K Rat Ke Jus Pehle head to my length - K Rat Ke Jus Pehle head to my length - K Rat Ke Jus Pehle In This Smile And Water Pond Near Stay A Song That They Can Travel From Head Heart Delhi Somvanshi Travels From This To Back Side Current Remedies Points I Reason Daughters Will Be Mine You Have Decided To Return Back And After Death Voice Mail co me current national tight bicycle store me current minute improve and me current news channel end and attempted to pinpoint manual tight member sample logic gets quotes logic super style check weather medicinal the spiders clear cold within the period to one pan one subject icon Tap Length Flights Let Me Describe The Length Sainik Style Spotted At Solan Phal Bhi One And Lungi Declare Node Which Will Move With The Current Not Quite Current Main Video First Point Is Don't Want To Go Through The Central Current Next Article 252 The Current Equal To Conduct And Also Into Increment The Length Account After 10 Loot I Will Know What Is My Length Suvansh Sexual Milk Sake Guddu Ke Mode On Length Samay Journey To Travels 19 Number Of Times Right And Also Like Can Check Hair Is Mask Shrinked 2012 Anything Against Printhead Right In That Case Returns That Bigg Boss Cut Indiscriminately Log In Comeback Tour Essential Position Of The List Security And Children - Key Rate Children - Key Rate Children - Key Rate Were Current Track Court On Current Hot Next Mukesh Shabd This Point Name Is The No Right To Discomfort To Make A Tunnel End Definition of But You Have Tried So Lakshmi Define MP3 WB Deposit Result Google Does Current Dot Next Soon and I Love My Current Next Personal and Quite Amazed Result Hindu Swayam Simple Gautam Buddha Complexity of NCT of Delhi in the Time Complexity of Fun and Complexity After clans open loot ke is main length - k sp arun mishra feed follow length - k sp arun mishra feed follow length - k sp arun mishra feed follow us one current next subah point * one current next subah point * one current next subah point * don't know sense objects to join date 12th hai dried 100MB satellite so current next point to hai national 10 code and see where to find Now half the member spirit time within 10 member posts of solution sector two like this video and solution please do the like button and subscribe promotion of features videos thank you
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
807
hi-oh in this video we'll solve the lead hi-oh in this video we'll solve the lead hi-oh in this video we'll solve the lead code problem number 807 maximum increase to keep city skyline okay so we have the view from all of the angles from top bottom left and right the first thing we need to understand is that the view from left and right will always be the same and accordingly the view from the top and the bottom will always be the same so for each individual cell we need to look at how much we can increase that cell and keeping in mind that we shouldn't change the view and since the view is calculated by the maximum of the row for the left and right and column for the top and bottom if we want to not to change the view we need to increase it so that it won't be more than the smallest maximum where he stands in terms of the row in the column so for each cell we take the maximum from the row which means the view which is supposed to be and then the column which is the view which is supposed to be from the top or from the bottom and we take the minimum and we know that each individual cell we can increase up to that minimum and that would be our best solution in this case now let's go to the coding part we need to first of all calculate the view which would be we'd call this one a table and we would call the other one left and same time bottom on the right are the same so we don't care about them too much first of all let's go over all the columns and calculate air size their maximum so we go through all of them which is and the column size would be 0 and for each column we go over the row we keep meeting that the maximum which we already acquired is the first one of that color and then we go over all the other rules number of rows degrade size and we simply assign the STD max oh that new element I okay top would get this element so this supposedly should give us the maximum of the columns which is the view from the top for the view from the left we need to calculate the maximum of all the pros for that who will simply use the STD function and not take it too much so D yesterday in max element we would give the grid I which means the beginning of the row I and the end of the row I and K and since the Maxima turns the iterator we need to take the value okay for now we have our result and we will try to increase all of the cells in order to match the minimum between the two between the corresponding one the row in the column we go from the for all the rows this is just a traversal from them over the entire matrix you go to great I not size and plus G so basically we need to take the possible equal to the minimum between the two which means the maximum of the white Rahu and the maximum of the I'd column of the Jade card I'm sorry okay so for that we take the view from the left and I'll pick the I and they go from the view from the top and we pick its corresponding element which would be the J okay so this the difference and we need to check maybe we are on that same element around the biggest element so the difference might be negative so in order to ensure that we do not ruin the answer we will go like this will go like if our current value is actually less than our desire then the possible value to which we can increase it to we make the addition the difference between the two create i J okay and the result should be our result run code we have a compilation error yeah there is there any type over here we fix this and there's another compilation er there's also type of here well that's kind of too many compilation errors great yep and another one almost there yep and this was it thanks for watching and link to the code will be down in the description box
Max Increase to Keep City Skyline
custom-sort-string
There is a city composed of `n x n` blocks, where each block contains a single building shaped like a vertical square prism. You are given a **0-indexed** `n x n` integer matrix `grid` where `grid[r][c]` represents the **height** of the building located in the block at row `r` and column `c`. A city's **skyline** is the outer contour formed by all the building when viewing the side of the city from a distance. The **skyline** from each cardinal direction north, east, south, and west may be different. We are allowed to increase the height of **any number of buildings by any amount** (the amount can be different per building). The height of a `0`\-height building can also be increased. However, increasing the height of a building should **not** affect the city's **skyline** from any cardinal direction. Return _the **maximum total sum** that the height of the buildings can be increased by **without** changing the city's **skyline** from any cardinal direction_. **Example 1:** **Input:** grid = \[\[3,0,8,4\],\[2,4,5,7\],\[9,2,6,3\],\[0,3,1,0\]\] **Output:** 35 **Explanation:** The building heights are shown in the center of the above image. The skylines when viewed from each cardinal direction are drawn in red. The grid after increasing the height of buildings without affecting skylines is: gridNew = \[ \[8, 4, 8, 7\], \[7, 4, 7, 7\], \[9, 4, 8, 7\], \[3, 3, 3, 3\] \] **Example 2:** **Input:** grid = \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\] **Output:** 0 **Explanation:** Increasing the height of any building will result in the skyline changing. **Constraints:** * `n == grid.length` * `n == grid[r].length` * `2 <= n <= 50` * `0 <= grid[r][c] <= 100`
null
Hash Table,String,Sorting
Medium
null
138
video and turkey league pokal kapellen smith rambler so good basically because how to criticize home version of this english and can see that this english house a random pointer punctual and a jew in the lingua guy swinnen show you how we computer service come her stable in this video a little creative idea for shows iconology gaping spoiler and the brake koolhaas every fold vainio in the store is and you can see that is the input and i want you scream another clone version of paulus in the denominator so indiscreet love the neighbors source code, so all the scrum booking so I need it there new jury will be in I perhaps logical the hebel right to keep track of the you know that we got new instances something like musicologist they the newsletter I add abel english at is a random runner we can just use for both to in this case you to build is on the two tone so lester but this thing is that this grandfather row your favorite instance of day brendan oh the next one need that the random planet point you there won't you make sure where can i buy cheap soccer both use of use gebo too expensive so in this case at by our table in a row in the schiehaven table and in this case the table and coolhaven key is basically chicago which also has a nose in darling job and the counter in the in Hebrew basic you are curious about albany for conversion on download in our member rise o a conspiracy theory growth in it there of market heaven so painful his back and the tiki in archaeological basically the oberoi who are already dead and in the basics can offer the crown version of endorphins Christian Jew so indiscreet Lizzie how do you start the Coene no reason that lust guys I had no service so because who has vision news we couldn't say I needed that box no excess to table this is how Kruitberg instance content ebro and a new start we can crater instance of download with a view cells that are the city that our hero chic deleted ns prorail and the random flyer and I have a new instances 7 pro kind so in assist the war that knife set so see what can help is the common your pc creek and tight types bionic type china and artibosch week in shraddha' in shraddha' in shraddha' known trudged we can go this in this case bbc quick wins' when they bbc quick wins' when they bbc quick wins' when they see thirteen necessity and them in this case and become your shoes edgar the answer 1 mole and what cavens so if there is a resident plan quickly so that we can have kids there are seven menu instances frowns researching as far as reduction and pc guido de grand'o in this case cold room and then random is also in this case which continues microprocessor team so 13 in the mind addresses slaves say hi to build a purchase order tables on your trie die instance low and you're going to get zo die or through the Chinese fondue new levels anyway donated types thirteen regional consultant the lobbies Marxism tables on gabri the show you can get searching for have gray and in this case search of shadow and empire process even resolutions searching watch this would you rather than you my approach to celebrate a nail art room fireproof figure to live like this live then assistant sorry tennis string creatables rita and then you become shoes times love alone position you time and resources we day brenda minsky's essentially when a bonus to green gables omega 3 who went to the forest so had what are you looking for love moschino by for the grandfather and nl arnhem rhine origin tube dead eh and now just notes on the charger cable 's-works growth jarno theijn 's-works growth jarno theijn 's-works growth jarno theijn and now we can bios and death and the lessons swan sorry box and the Wednesday 13 a table chrono trigger I can leave pansino in no time more than boenen times per inhabitant postal address owino cities sorry gary to the ribosome china coach eleven go time' ribosome china coach eleven go time' ribosome china coach eleven go time' two legs 2003 nmi shift or from your other social housing in specie can see just about after tables white rida anyone got nest is still so indiscreet corner in sports hall and the random polarization ran find you know cells that are like that in ski routes scallops scratch aquino seminar chemo I read we cleaned your children and a pointer porn set resolution the spurt fine scale conical already certain aerialist using almost evolve cry a specific just everything where I happened so the space contraction entrance complex scooby doo and where and is number of och finger in her quite last and space contraction that even mirror painful sores in with table view on his dream team [ __ ] or that nose team [ __ ] or that nose team [ __ ] or that nose crime so jean-claude biguine crime so jean-claude biguine crime so jean-claude biguine actors that first define a base case if there is no way to switch euro on and then I buy it used a morphological table and then the file pointers drivers the final renault nl for daniel table guy can help so well could download chicken peace and it is herby cambiar crown zoey builder random pointer and to get your images nespresso in this case be built with porn even the success and the even or something aggressive earned a random so took green or is already and is not contain a table I do the re doctrine and how can I make a crown that interest rate risk remco and I took wanted renes planner so aggressively ran net pointer is necessary it is normal is after container gables shivered and well we can also strida every unique corona glass that is for nesko such as krabdam because who builder and the baroness corner we can looked around because there was a need for super nes so biscuit continuously I will love that specific juice workflow a child heartless management earning the you know right it and killing them or the conversion on the lever and a merger between the cycles goosal the bubble and 300 you think you expect
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
228
A Higher Oil Welcome To Line Ko Dp Also 26 Big Bills Boxing Saturday 28th Shooter Playlist Ko Challenge Religion We Have Problem Summary Ranges Networking Problem The Points Your Arguments For Kids In Interior AIIMS Return 10 - Hotel Staff Changes Interior AIIMS Return 10 - Hotel Staff Changes Interior AIIMS Return 10 - Hotel Staff Changes Shock Over All The Numbers Sindh Exactly What There are elements of obscurism there rangers in the recent years but as they know the ranges but not in that meanwhile range one we now winters should be output S8 even notice this ruby ​​and output S8 even notice this ruby ​​and output S8 even notice this ruby ​​and them agree to t&amp;c them agree to t&amp;c them agree to t&amp;c that this is what is means is exemplified The numbers are shot to depend on rates for India in 600 800 Trend Name is unique but it is not sunscreen Number plate software tools of this country but number 10 vs me to selector start and after inch Surya 0214 6 years back side 2012 positive Software To Create A New List With Spring 0202 Half Entry The 45 Se Sure 15000 Single Entry Subscribe To Member Se Example Right The Teaser Solid Se This Is My Name City-A Share Right To Check Se This Is My Name City-A Share Right To Check Se This Is My Name City-A Share Right To Check Weather Number Response The Guide Net Se Vighn 2.1 Start And From This Point Zoya 2.1 2.1 Start And From This Point Zoya 2.1 2.1 Start And From This Point Zoya 2.1 Start And Saw To Check The Giver Number From Right The Point Amazon To Find The Value - - - - - Right The Point Amazon To Find The Value - - - - - Right The Point Amazon To Find The Value - - - - - 121 Name When Do This Minus One Sauth And Jewelery Office End Listen Superintendent Number Feed End Subscribe Same Condition and Value - - - - - - - - Festivals and K Navamsha or Right Again and Friends Samsung This Form of B Minus Point Superman Is Minister Equal to Names of Management Infamous Female Celebs to Hear What is the Cost Effective Ranges from Broken Incomplete Sea Minus One From Start To Finish Wonders In United States Man You Reach Will Be Phone Number Start 3 On This Number It's Minus One But They Never Gets Broken And Afton Study In Start With This Particular Slot For 2nd Ed Degree Holders In The Swiss Bank Soma Start Will Not Fear And Thee Can't To Naagin To The Seench Hundred Names When School For Interactions That When Encounter That Now 307 - 06 Which Is Not Equal To Make Now 307 - 06 Which Is Not Equal To Make Now 307 - 06 Which Is Not Equal To Make PDF Volume According To Taste Rokn Sakin People Come To Difficult Condition Good Luck Came And Names Of Two Numbers of Units Add 80021 Minus Plus 2 And Know It Is S4 And Immens Man Adhinayak Naagin Speed Kam Kiya Naagin Two Plus Two Equal To Subscribe My Channel Directly Siri July Current Affairs In To-Do List Play List Pimple Da The In To-Do List Play List Pimple Da The In To-Do List Play List Pimple Da The World will discuss do the same logic and equal and complexity of this will be chief n when is the a number of elements the indirect cylinder code bearable science check for name centi or 2800 in this they can directly return mts one side udta they can declare Result List Up The Mechanic Bar Start And Have Hair Oil Can Have A Wild And This Land Mines Total Length Mark Increment And Gentleman And Value - One Increment And Gentleman And Value - One Increment And Gentleman And Value - One Equal To And Minus One Person Doing A Year In Wildlife And Preventing And Almonds In Thought For Hair White water should be 222 Norms and Management Someshwar Ansh Value - One Equal to Make Preparations Ansh Value - One Equal to Make Preparations Ansh Value - One Equal to Make Preparations for All Students Can Reduce Ho One Increment Mines Range Hai Is Vansh Atoms and To-Do Section Directly Vansh Atoms and To-Do Section Directly Vansh Atoms and To-Do Section Directly Check Itna Start Recruitment - 1m The Service of This Case Difficult to End Minus one that in this only one element was present in this way can only and the element which starts with this name add kar inch that if you were head of he otherwise look me hai broken vikas and want to arrange white so before a science student and Value Me To Check Weather And Since Reach A Saiyan Ram Checking Events In Range Of The Amazing Certificate To End These Days Tubelight Increment Belief In Golden Opportunity DSP Robbers To Check This Condition Again Development Of Water Last Value Can Vide One Element And they can check for the same condition to start episode in this world for transport a minute and they can return the result net message code main 10 gram points time 10 hua tha da co director dr and strong state video thank you
Summary Ranges
summary-ranges
You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. Each range `[a,b]` in the list should be output as: * `"a->b "` if `a != b` * `"a "` if `a == b` **Example 1:** **Input:** nums = \[0,1,2,4,5,7\] **Output:** \[ "0->2 ", "4->5 ", "7 "\] **Explanation:** The ranges are: \[0,2\] --> "0->2 " \[4,5\] --> "4->5 " \[7,7\] --> "7 " **Example 2:** **Input:** nums = \[0,2,3,4,6,8,9\] **Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\] **Explanation:** The ranges are: \[0,0\] --> "0 " \[2,4\] --> "2->4 " \[6,6\] --> "6 " \[8,9\] --> "8->9 " **Constraints:** * `0 <= nums.length <= 20` * `-231 <= nums[i] <= 231 - 1` * All the values of `nums` are **unique**. * `nums` is sorted in ascending order.
null
Array
Easy
163,352
47
hi everyone today i saw the code question called permutation 2 so given collection numbers nouns that might contain duplicates we want to return all possible unique permutations in other words permutation without duplicates in any order so see the difference between permutation one permutation two uh implementation one if you watch my previous video you will remember okay well given the noun without duplicates and when you find the permutation without duplicates so it's rather easy we just traverse the entire array append a number to pass if the lancer pass equals to the lens or nums uh we append the positive result but in this question uh the original number three might contain duplicates but we want the result the permutation without duplicates so and a straightforward approach is to assort the array and to pass any duplicates numbers so we can uh transform this permutation to back into permutation one okay so let's directly dive in the coding path okay the first as we did in previous question we have to initialize the mpt pass which means our empty array and also the results should be initially empty array and after that let's call the open function and pass in this down passing pass and the result the final return resulting function is done when operation main function where to write helper function so let's copy paste these uh parameters into the helper function and the first thing to consider if uh no nums this means we have slice the entire array and reached the end right and if that case once you have the possible result after i want to run recommendation to traverse the entire way right so there's image length nouns that's called uh self helper plus and ohms all the way from beginning to eye and all the way from uh i produce one to there and this part should add the current element on the side and the result should be six so this is basically the framework for the previous permutation but here we need to sort it rewrite so we need to add a solid function here and then if function if i greater than 0 and numbers i minus 1 equals numbers i this means we have duplicated numbers wireless so it does continue to the next integer okay now let's meet the code you see the works okay you see the time comparison invariant usage of this solution quite efficient right and i think the code is short and easy translate if you find this video helpful please like this video and subscribe to my channel i'll see you next time thank you
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
231
hey this is Topher with the lonely Dash and today we're going over lead code question 231 power of two which states given an integer n return true if it's a power of two otherwise return false if an integer N is a power of two there exists an integer X such that n is equal to 2 to the X power okay so what does this really mean it just means they're going to give us a number which will be an integer and we need to figure out if 2 to the X power could possibly equal n right and this x has to be an integer and our n also has to be an integer um and so normally what I'll do is go through these questions and say okay let's read the question let's understand it then look at the constraints but for our purposes today I'm going to look at the constraints right away which is simply stating that n or the number that they're going to give us is going to be between -2 to the 31st power and 2 to between -2 to the 31st power and 2 to between -2 to the 31st power and 2 to the 31 power minus1 so that's just really important to know right off the bat uh so that we know what we're doing so here are the examples that code gave us uh with an input where n equals 1 we know that's true because 2 to the zero with power is 1 uh if n was 16 we would also know that's true because 2 to the 4th power equals 16 but there is no power to two a power of two that can give us three so that's false so these are the things that we need to know in order to solve this problem properly we need to know and that we do know that n is an integer and how do we know that well it told us so given an integer n so n must be an integer and that means that the power that we're looking for or the x value must be between 0o and 30 right because if it's a negative number then it's not going to be an integer because it's going to be part of one so it could be like 0.25 or 66 it doesn't really matter like 0.25 or 66 it doesn't really matter like 0.25 or 66 it doesn't really matter so we know that the value we're looking for this x can't be negative right and we know how do we know that it's going to be between 0 and 30 because 2 to the 31st power is going to be greater than our constraint okay so if we know that it's going to be a Power of Two between 0 and 30 there's a couple of different ways that we can solve this and for me and for today we're going to solve it using binary search algorithm it's one of my favorites if you've not watched our video on the binary search algorithm please do that it is Elite code onto itself but for today we're just going to run through two examples and it kind of gives you an idea of what we're going to be doing right so we're going to start with our numbers 0o to 30 and we're going to start our left pointer over on the left side at zero our right pointer over on the right side at 30 and all we're going to be doing is trying to find the power here that is going to equal to n so here we'll just say that n is 26144 and for argument sake we're going to know that is 4 to the 9th power okay and the question is basically saying hey we've given you this number is this is it possible to have any number in here that is to a power oh this is four um sorry two this should be two and just for my argument sake I'm going to make sure that's actually the case so where's my calculator here's my calculator and we should always do this just to make sure so 2 to the 9th power is 512 okay so I must have been doing this uh 512 and I guess we better do 2 the 29th power over here just to make sure as well make sure that we're doing it right uh okay 2 to the 29th power is actually okay so we did this right sorry about that um okay so we know that n is 512 which to us we know is 2 to 9th but how can we figure that out well binary search if our left pointer is at zero our right pointer is at 30 the middle is left plus right divided by two which we know is 15 and we're going to ask ourselves hey is 2 to the 15th power is it equal to n if it is then we are done and we can just say true but if it's not we're going to ask ourselves okay is 2 to the 15th power greater or less than n and in this case we know that it's greater because 2 to the 15th is greater than 2 to the 9th so we're just going to take our right pointer and we're going to stick it one position left of our midp pointer and we're going to do this all over again we're going to take left pointer right pointer add them together divide by two and Bam we know our Middle Point is seven and we're going to ask ourselves hey is 2 7th power equal to n it's not is it Greater or is it less than well we know that 2 7th is less than 2 to the 9th which means it's less than n so we're going to take our left pointer and we're going to move it just to the position right of our middle position and we're going to keep doing this process over and over again so let's see 14 + 8 uh what is again so let's see 14 + 8 uh what is again so let's see 14 + 8 uh what is that is 22 / 2 is 11 so we're going to stick our 22 / 2 is 11 so we're going to stick our 22 / 2 is 11 so we're going to stick our midpoint there ask our question hey is this the answer it's not okay we know it's greaters who our right pointer moves over and we're going to do it all over again the midpoint between our left and right pointer of course is this nine and the first question we ask is hey is 2 the 9th equal to n and it is bam we're done so we know that the answer to this one is of course true that's important done true you're going to turn green hooray so that's how that's going to work same thing if we wanted to do it again with a much bigger number it's the same process over and over again so we're going to do 2 to the 29th power well we're starting our left and right pointers our midp pointer starts at 15 because that's in the middle we're going to ask is this the answer it's not it's less than our answer so our left pointer gets to move over one position and we do the calculation process again so 30 + uh 16 is 46 / 2 is 23 so there's so 30 + uh 16 is 46 / 2 is 23 so there's so 30 + uh 16 is 46 / 2 is 23 so there's our midp pointer is it greater or less than or the answer uh we know that it's less than so our left pointer moves over again and this process is going to keep going and going until bam we find the answer now this is going to end up being one of those Loop statements that is as long as our left pointer is not crossing our right pointer because it's possible that our left pointer and our midp pointer and our right pointer are all on the same spot which means it's either the answer or it's not and then our left pointer will cross our right pointer and we've reached the end of the loop and if that ever happens if our left pointer crosses our right pointer that means that the answer will end up being false but in both of these cases we know it's true so this is all we're going to be doing to solve this question today we're going to we know based on the question that n is going to be an integer which means our power is going to have to be a positive integer and what else did we need to know oh yes the power must be between 0 and 30 because our constraint has told us so I don't think in this case that there's any edge cases to consider so we're actually going to skip that and go straight to our pseudo code ahha gotcha no there's really nothing to consider for edge cases all right let's move on okay so for our pseudo code the very first thing that we need to identify or determine is uh if n the number that's given to us is less than zero then what do we know well we know that it's false so that we can just then return false right because there is going to be no power of two that will come out to having n being negative okay so that's first and foremost once we've gotten that out of the way we can kind of start with our binary search algorithm here so we need to create left and right pointers at 0 and 30 um right and because that and don't forget about the 0 and 30 and how we got to the 0 and 30 we've got those from the constraints of the actual question once we have done that then we can create our Loop right so we're going to create um a while loop that iterates um iterates until the left pointer crosses the right pointer okay so that's just going to happen over and over again until this situation happens during that time we have got a couple of things that we need to do the first is identify the midpoint right between the left and right pointers all right that's that was our M our purple m in our earlier part of the question we also need to identify um the value of the current uh Power um so we're going to use just for argument sake we're going to make it a valuable use X as a variable okay so this is just saying X is going to equal two to the midpoint and it's just going to be sitting there and holding that value and then while we're doing that we get our if statements so if n equals our value so two to the midpoint power what do we get to do well we get to return true because well we found it congratulations we're good um if not uh in that case if n is greater than x what do we move the left pointer one position to the right of the midpoint all right and otherwise and I'm going to capitalize that if cuz it's going to bother me uh if n is less than x then we need to move the right pointer one position to the left of the midpoint all right and that's just going to keep going and going until either uh our midpoint value until our Mido value points to the right power or it basically ends and if it does end if the loop completes without uh finding a match which means we didn't find any power of two that matches our n if that happens well we just return false uh because it's not a power of two at least not within our constraints and that's it that's all of the pseudo code we need and if you are a person who recognizes basic basically this algorithm you know it's binary search so let's take it move on and get coding okay here we are working in the Java area of the lead code website and the first thing we need to do is state if n is less than zero then we're going to return false so that's if n is less than zero what do we need to do well we are just going to return false f a f l e and make sure we spell everything right so we've taken care this line right away thank you very much now we need to break right into creating our left and right pointers for our uh binary search algorithm so uh our left pointer is going to start at zero and our right pointer is starting at 30 and these were taken straight from the constraints so we know that those are correct and now we get to start our Loop and that's our while loop so uh let's see while uh our left pointer is what is it less than or equal to our right pointer we're going to do some stuff in this Loop and the first thing we're going to do is identify the midpoint between our left and right pointers so we're going to make that an integer and we're going to call it m from midpoint is going to be equal to left pointer plus right pointer value and it's going to be divided by two okay so hopefully that'll make sense to everybody and then we're going to also identify the value of our current power so that's also going to be an integer uh we're going to call it X and it's going to be equal to math dot let's see the power of two and it's going to be going up to the midpoint value okay so power of two to the uh two sorry to the power of our midpoint and then we get to get into our if then statements so if in our case uh n is equal to uh our x value right because that's what we're calculating every single time then we know we found it so we can return true because it is in fact a power of two all right otherwise else if uh then let me kind of scoot down here because I'm going to have to keep reading else if n is greater than x so if n is greater than x well we've got to do something else we've got to move our pointer so if it's greater than x our left pointer is now going to equal our M plus because we're moving one position to the right uh otherwise that's just a plain old else that means our n is less than our x uh or less than our power to or power to the two so we're going to move our right pointer and it's going to be the value of M minus1 and then finally if we break outside of our loop the loop completes and we don't find anything we can just return false because we didn't find any integer value of x that would make uh um a power of two equal to n so that should be everything and I'm sure I'm going to miss something because I'm just typing this up as I go along uh hopefully not you never know oh error power of two let's see possible lossy conversion oh from double to integer let's just throw in here that it's going to be an integer and that's good to know because the math.pow will always set the power to a math.pow will always set the power to a math.pow will always set the power to a double and we said that our value was going to be an integer X so if we stick our little INT in here it should change that to an integer uh we'll hit run hopefully that should be everything okay there we go and I'm going to hit submit let's see how we did against everybody else and I'm just going to pop it over here accepted oh look at that pretty darn fast at 84.98 oh and it's telling me that it's 84.98 oh and it's telling me that it's 84.98 oh and it's telling me that it's not very good on memory uh I'm just going to hit submit again for fun just to see if we can do a little bit better maybe not but uh oh didn't do a whole lot better third time oh you attempted to run too soon well come on guys let me have some fun here would you okay getting a little bit better so for me this is a really fast way of solving this specific problem power of two because we're dealing with powers from 0 to 30 so a binary search works really well um there are certainly other ways of solving this question using Java such as doing the math where you're going to constantly divide n over and over again to make a determination whether it is um a power of two but for me getting this really fast runtime is super important that's why I liked to use the binary search algorithm when solving lead code question 231 the Power of Two
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
266
hey what's up guys new white here I do technical stuff on twitching YouTube check the description for all my information go to patreon and I do the premium Lea code solutions there and then reach out to me on discord if you want to try and respond to everyone 266 palindrome permutation got some likes we did palindrome we did the permutation one we're doing a combo now given a string determine if a permutation of the string could form a palindrome so given what is a palindrome what is a permutation first of all so a palindrome is it for example the most famous one I think is race car a palindrome is a word that is spelled the same way forward is backwards or a string so our a c e r CA r ra c e c AR r a c e c AR same way before word is backwards what the distinct properties of a palindrome are each character has a match so R and R a n a C and then except for the middle one doesn't have to be a match this is still pound room so the middle one you know it's fine if you don't have a middle one that doesn't have a match but a middle one doesn't need to have a match so that's a palindrome what is a permutation is a rearrangement of letters in a string so Co de or ODC e is a permutation or you know DCEO like anything that's a rearrangement of these letters is a permutation so we want to find out if a permutation of this string is a palindrome because obviously code is not because Co de and eDoc are different spellings forward is backwards and while we have to do is pay attention to the properties of a pound drum to figure this out we don't even really need to if you Jenner the worst way to do this is generating all the permutations and then looking for palindromes that would be so slow all we really need to do is just have a little array that keeps track of the count of each character so we're like okay we saw one see we saw one oh we saw one D and one E and if there's no Matt if there's more than one character without a match that's not a palindrome and it's not possible to be a palindrome right because only one character cannot have a match and that's the middle one so if you find you know there's only a one occurrence of you know two characters that's wrong because there has to be a match for every character except for one that can be the middle one so if we see is there's only one see them there better be two O's two DS and two E's for a palindrome you know so that's it a B is true right we see you know a has a match B doesn't but that's fine because the B would just go right here there you got powned trump so I think it's pretty self-explanatory it's pretty self-explanatory it's pretty self-explanatory pretty easy like I said we're just gonna keep an array for each character's index will call it char counts this is very popular thing I think you can do there's uppercase and lowercase because it doesn't say it's all lowercase so we're gonna use all ASCII values so we're gonna do 128 sighs under 28 we're just gonna loop through the string I less than s dog length I plus this when you initialize an array in Java this means it's all zeros so this is going to contain the count of each character in the string so what we do is we just do this char counts of STR at I this putting this a character as the index value of an array turns it into ASCII so it finds the index of the ASCII value for the current character we're looping through on the string looks it up in the array increments the count so if we see an a it'll increment the index by 1 and then if we see another a don't remind it again so it'll be two ways and we know then we know the count the number of times each character occurs so now all we have to do is we have a you know a variable called count will do for int I equals zero again I less than 128 we just got to loop through the counter ran out and the count of each character and we'll just do count plus equals char counts of I so the you know this will be the current character we're looping through each character and in each index values the count of it mod 2 because we're looking for matches so if there's two characters then that's a match if there's two of the same characters that's a match if there's four that's a match if there's six so any even number is gonna be a match that we can use in our palindrome if it's odd then we're gonna this mod two is gonna turn it into the value one which will add on to the count so in this case we just do this and if there's more than one character with out a match then count will get incremented more than once and we can just return if count is less than or equal to one that means that there's either zero characters without a match or there's one character without a match which is fine and if it's not then we return false so we return true if everything's good we return false if it's not very easy problem I think this is the fastest way to do it right this isn't really space it's only 128 that's like constant we're not we're worried about scalable space so it's no big deal and then you know you're looping through and linear scans so it's not nested for-loops or anything just linear so for-loops or anything just linear so for-loops or anything just linear so thank you guys for watching really appreciate guys you know love everyone the watches the videos I don't know what else to say I'm about to go out to eat I just saw this and I was like this is easy let's finish this really quick I don't do it so thank you for watching let me know if you have questions in the comments and I'll see you in the next one
Palindrome Permutation
palindrome-permutation
Given a string `s`, return `true` _if a permutation of the string could form a_ _**palindrome**_ _and_ `false` _otherwise_. **Example 1:** **Input:** s = "code " **Output:** false **Example 2:** **Input:** s = "aab " **Output:** true **Example 3:** **Input:** s = "carerac " **Output:** true **Constraints:** * `1 <= s.length <= 5000` * `s` consists of only lowercase English letters.
Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Hash Table,String,Bit Manipulation
Easy
5,242,267,409
504
hey everyone welcome back and today we'll be doing another lead code 504 ps7 and easy one given integer num return a string with its base summer representation so this is a an easy one you know how we used to do a binary you can say representation we just divided by two and if the remainder is 0 then we have 0 and we again divide the number by 2 for example in this case the example for example 14 binary representation of 14 we will have 7 as a quotient and 7 will leave us rewind under one if we divide it again by 2 and now 2 uh will leave us 3 is dividing two uh 7 by 2 will leave us three and we will be dividing three again it will reverse remainder 1 and just one so we will be passing it here and the binary representation of 14 will be 1 0 and the same with base 7 so if we have 100 you can see like if we divide it by 7 we will be getting the reminder of to because 7 14 is just 9 8 98 okay so like 14 here and now if we divide 7 and 4 14 by 7 will be getting a zero reminder and just a two question and now we have uh our quotient like this so we will just pass it to the very left because it is no more divisible just like the one it was here like as a question and we pass it to the very right and now we can just return the base 7 representation of 100 which is two zero two as you can see on the very left example number one so let's get started first of all we will be making our result string and taking the negative number here like indentation is messed up here okay this is good so saving a number because it can be negative and we will obviously be working on a positive integer so just taking the absolute of that num and while that first of all we will check if that num is equal to 0 we can just return in this case a string o 0 and now we will check if num is while num is greater than 0 we will go inside and reminder will be uh because we want to obviously pop from the very left and then perform all our uh operations to it and now what we'll be doing is just now I'm taking it reminder by 7 and just appending it to our result by type costing it also so reminder will be like this and after all of this we will just perform the question on it so we can get rid of the last element we just took as a reminder and that's it so if we have saved our negative number if negative number is great less than 0 if it is then obviously we are going to return a string with a negative adding it with our result and obviously reversing it and in the else case we are just going to return a simple you can say result by reversing it so that's it let's see if this works or not and this works and that's it
Base 7
base-7
Given an integer `num`, return _a string of its **base 7** representation_. **Example 1:** **Input:** num = 100 **Output:** "202" **Example 2:** **Input:** num = -7 **Output:** "-10" **Constraints:** * `-107 <= num <= 107`
null
Math
Easy
null
215
um today we'll see how to solve the gate largest element in anime so here again array without sorting and we want to indicate largest element if K is 1 means we need to find the last element in the ascending sorted array good if it's 2 we wouldn't find the element which is second from last in the ascending circles array but you have to do it without sorting the entire so let's see how we can do it here I have taken an array and these are the changes the sorted array we'll use it to get better understanding we won't use it directly with the value so we want to find the second largest element so what would be the index of the second largest element in this ordering array index of the first largest element will be the last index and index of the second largest element will be the one before that so we want to find the element at index 10 in ascending sorted array so how do we do that so the approach I used was similar to which I've chosen a pivot pure tensions so from this array from Main array choose a random index let's say I've chosen 5 and the value at that index is 3. so now I divide this array in two parts low value and high value all the elements Less Than 3 will be here all the elements greater than or equal to 3 will be high value so let's go from the start nine it's greater than three so it'll be high value 2 it's less than three similarly one less than three 3 is equal to 3 2 less than three eight regularly and one okay so these are the now indexes of these elements are 0 1 2 3 4. and next is okay so we can observe a property here all the elements between index 0 to 4 what are the elements two one so 2 1 and 2 1 will be between 0 to 4 index 0 to 4 even in the sorted array so index 0 to 4 instance from here till here see in the sorted array the elements are one and two even here the elements are one and two we split the array in such a way that the relative positions between these indices will change but these will not go out of these indices so 2 will always be in between 0 to 4. okay so from this we can infer that the elementary index 10 will not be here it will definitely be here so what we do is we again recursively do the same of the same approach okay this is the array we got now okay it's base index is five so choose a random index okay let's say it's the index is 6 and the value is also 6. so again I speak all the elements less than six will be here all the elements greater than 6 will be here okay so let's start again minus greater 6 is equals to 6 7. 3 is less four three it is so now these things are five six seven eight nine ten eleven so we know that the element at index 10 will definitely be in this okay to narrow it down again you can recursively we can do the same recursive procedure or when the number of elements are less than M some certain value you can choose M okay yeah we can directly sort it because here we have four elements so if we sort it the time complexity will be less than uh will be less than doing recursion and finding it so if I sort it the value should be six seven eight nine their indexes will be so we know the elementary index 10 is 8 and we return it okay we could have done this recursively but that takes more time so if there are very few elements what we can do we can directly sort them and find the value so now let's see the code so we are given an array and base index just to keep track and what is the index that we want to find so if the elements are less than 1000 I'm directly sorting it and finding uh finding the index okay if not I choose a random value I'm just calling it as mid value but it's random and all the elements less than Mid Valley will be sending to low all elements greater than or equal to Mid will be sending to high and if the index we want to find is greater than the indexes in low value order it is we go towards heaven if not we recursively solve the low value okay that's
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
232
for some reason this problem is very popular I guess that is because it Gorges your mental flexibility and how can you come up with new Solutions using only the existing resources this is very crucial because indeed you have to implement a q data structure using only the Stag data structure so let's see what we can do about it Hello friends welcome back to my Channel first I will explain you the problem statement and see what it means we will understand what all functions do you have to implement and then we are going to see how do you perform all of these operations we will do a side by-side operations we will do a side by-side operations we will do a side by-side comparison of a queue and how are we achieving all of the same operations using a stack after that as usual we will also do a dry off the code so that you can visualize how all of this is actually working in action without further Ado let's get started first of all let us try to make sure that we are understanding the problem statement correctly in this problem you have to implement all of the operations that you usually perform on a q data structure and the only catch is that you have to perform these operations just by using a stag data structure just to give you a quick review a standard Q looks something like this right and it follows the principle of first in first out it simply means that any element that enters the Q first it will be the first one to get out so for example if the element four enters the Q first then 8 and then a 15 now if you try to pop out an element four will be the first element to be popped out right because it entered the Q first whereas in a stag data structure if you enter four and then a eight and then a 15 now if you have to pop out elements 15 will go out first because a stack works on the principle of last in first out that is where the challenge is so using a last in first out structure you have to somehow Implement a first in first out structure and you have to implement all of these operations so push simply means that you are able to add new elements to your queue pop simply means that you are popping out a element from the queue and this will follow the first and first out policy Peak is very similar to pop it simply means that you are looking at the top element you just do not remove it from the queue and the last operation is empty just tells you hey is there any element left in the Q or not if empty will return true if your Q is completely empty otherwise it will return a false so these are all the operations that we want from our implementation let's see what we can do about it when you try to think about a solution to this problem this solution cannot come that okay I'm trying to think of a Brute Force way or what is the optimal way there is just a certain way by which you can implement it correct so let us say I have some operations let us assume that I am making four operations in my que so what we're going to do is on the left hand side over here I have a standard que so we can see how the actual operations will happen in a standard Q data structure and on the right what I have over here is I have two stack data structures one is called an input and one is called an output so we will be trying to mimic the operations of a que using our stack data structures and there is a certain way by which you can go about doing it so for example the first operation is a push operation so what you need to remember is as soon as you see a push operation just take this element and push it in your input stack this is a rule and you have to always follow it whenever you see a push operation just take the number and add it to your input stack so let us try to follow and see what happens So currently I have four operations right I am pushing an element four then A8 then a 15 and then a 16 correct if you had a q that has elements in a first and first out order then how do these elements get added to your que after these four operations your Q will end up looking something like this correct four elements have been added so now you know that if you try to pop from the Q you will get out a four right this is how your Q works and if you remember what did I say about the stack if you have any push operation just put all your elements in the input stack so over here in my input stack I will add all of these four elements 4 8 15 and then a 16 right so this is now done don't worry about it we will go ahead and implement the pop operation as well because currently if you do a pop operation 16 will come out right but that is not desired according to a q four should come out right so now that is exactly what we're going to do we now have two pop operations let us say I'm calling a pop on the queue in my queue as soon as I call a pop four will get out right but over here in my stacks if I call a pop 16 gets out this is not what we desire correct so there is a certain process and you have to look at your output stack this will determine what elements should get out when I'm using the pop operation right now my output stack is completely empty so if your stack is empty and you get a pop operation then you need to empty your entire input stack and put it in your output stack so you will keep on popping one element at a time from your input stack and then put it in your output stack let us visualize it so you pop an element and it goes in your output stack over here once again you pop an element and it goes over here you pop the next element and it goes over here and you pop the next element and it goes over here so you have done this until you're input stack is completely empty now you are ready to pop out an actual element if you notice in my output stack I have reversed the ordering correct and now whenever someone says pop from your que you left out this element correct from your Stacks you will look at your output stack and then you will pop out an element so when I pop out what do I get a four so you see we were able to mimic the same operation correct look at the next step now once again I am calling the pop function in your Q what will happen eight will get out right this is the expected operation and in your Stacks what do you look at your output stack this time it is not empty so what you need to do is just look at your stack and pop out an element when I pop out I once again get eight so once again we were able to mimic the op operation correct you might be wondering why did we have to pop out all the elements and what happens to the input stack now so to clarify this let us look at the next operation I have is push 23 so in my standard Q what will happen I will get a 23 added over here right and as per the rules whenever you get a push operation just add your element to the input stack don't think anything and just add an element so 23 gets added over here so now things are getting a little interesting both of your Stacks now have some elements what happens now so let us try to do one more pop operation as soon as you do a pop operation what will happen in the standard queue this 15 will get popped out right and now what do you do about your Stacks if you notice my output stack is not empty so once again just look at your output stack and pop an element so you see we have the same result now correct so we are able to mimic the entire functionality of a queue let us go ahead and do two more pop operations on the que so I do a pop I get out 16 and then I do pop again and I get out 23 what about the stacks for the first pop operation you will look at your output stack it has an element so I will take it and I will pop it out next you have the pop operation again and this time your output stack is once again completely empty and if you remember what did we do when your output stack was empty take all the elements from your input stack and push them on your output stack one by one so I will take up this 23 and it will go in my output stack over here now we have an element and we can safely pop it out so you see we were able to mimic all the operations of a q data structure using our two stacks if you notice I just looked at the push and pop operation the peak operation is very similar to the pop operation because in Peak you just look at the element but not pop it out so when you're implementing the peak function just look in your output stack at the top whichever element is at the top just don't pop it out and that is the solution right the last thing is empty so you know that your Q is completely empty and if you have to determine if the Q is completely empty just look at both your input stack and your output stack if both of them are empty you can say that yes your Q is empty right now so this is how you can go about implementing a q using two stacks right now let us quickly do a dry run of the code and see how it works in action on the left side of your screen you will have the complete code to implement this functionality and on the right I once again have a Q over here that is just for reference we won't be using it at all so what is the first thing that we do first of all we create two stacks the input stack and the output stack and these will come in handy whenever we do the push and pop operation right so now you have to write down that okay what does happen when you do a push operation so let us say I'm calling push four push 8 and then a push 15 so if you remember in a que what will happen four gets pushed eight gets pushed and then 15 gets pushed right but for a stack what do you simply take the input stack and push that element so if I'm pushing these three elements they get pushed like this 4 8 and a 15 correct so far so good now is the time that you actually try to pop and Peak elements if you remember Peak is very identical to pop you just look at the element you don't pop it out right so let us say I want to peek at an element so what do you will look at your output stack right it is completely empty so you have to tell me something right and that is similar to the pop operation so we will assume that we have to pop an element so my output stack is empty so what do I look up my input stack and then take out elements one by one that is exactly what I do over here in my V loop I will keep on popping until my input stack is completely empty so I will take these elements and push them in my output stack so input stack is now completely empty and if I have to Peak I will just look at this element do not pop it so I will return output. Peak so I'm just looking at this element with the Q you will just looking at this element if this is now clear to you the pop operation is very simple when you're doing a pop just do a peak so Peak will tell you that okay this is my top element and then you pop it out you do an output. pop so this element gets popped out right it is very simple and the rest is very easy once again if you have to push another element let us say I'm pushing 100 in your Q it gets pushed over here and in your Stacks it will get pushed over here so this is how things will go on and you have successfully implemented a q data structure if you want to know that hey is my Q completely empty so you just check if your input and output CU both are empty then you return a true else you will return a false talking about the time complexity now the time complexity of push operation is order of one right because you just push a new element but the worst time is taken when you're trying to pop an element so this operation happens in an order of end time because it can be possible that you keep on pushing elements in your stack right and then you call a pop operation so you will have to take down every ele M from this stack to the other one and that is going to end up taking a lot of time so the time complexity of this solution will be determined by the most expensive operation and it is order of N and same is the space complexity once again order of n because you need that extra space of your Stacks to make sure that you're able to implement this operation I hope now you perfectly understand how can you implement the Q data structure using only a stack data structure as for my final thoughts I just want to say that this problem is not very difficult and you may find it in some of the beginning level coding interviews so whenever you see such a question always make sure that you are asking your interviewer all the relevant questions for example you can ask them hey is the size of a q limited and then you can also ask hey what happens if my Q is a size 10 and then more elements start to come in do you want to exclude all the new elements or do you want to remove all the old elements So based upon that make all the changes and then come up with a solution your interviewer will be very happy with it so while going throughout the video did you face any problems or do you have any other method in Mind by which you can implement this Q data structure also can you do the opposite can you implement a stag data structure using only cues it will be very interesting so tell me everything in the comment section below and I would love to discuss all of it with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to keep bringing more such videos where I can simplify programming for you also a huge shout out to all the members who support my channel you guys really keep me going and as members you do get priority reply to your comments as well stay tuned for my next video where I explain how can you implement the stack data structure using only a cube until then see you
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
497
hello guys welcome to algorithms made easy today we will go through the day 22 problem from august coding challenge random point in non overlapping rectangles please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update given a list of non-overlapping access given a list of non-overlapping access given a list of non-overlapping access aligned rectangles write a function peck which randomly and uniformly picks an integer point in the space covered by the rectangles we are given two example examples let's first understand the question itself suppose we are given three rectangles plotting them on the graph will look like this we can see there are in total 28 points that these rectangles cover we need to randomly return one of the points when the pick function is called so by name approach we can store all the points into a list like the one shown for the rectangle first then we can pick any index between 0 and 27 and return the value seems correct but there is a catch storing all those points in a list will take up so much space that you will get a memory limit exceed error like this so now we need to find a solution where we do not need to store all the points let's walk through it coming back to the same graph we notice that the probability of a rectangular point to be selected is directly related to how big it is as we see the second rectangle has 12 points it means there are more chances of the point being from it rather than from first and third which have eight points each heading with this new information what if we store the number of total points still every rectangle in a list like a weighted array we can know the number of points in each rectangle we start with rectangle 1 and store 8. now at index 1 we store the sum of the points still first which is 20 and then 28 we now know the total number of points and the number of points till every rectangle this is the pre-processing part that we this is the pre-processing part that we this is the pre-processing part that we will do now comes the part of implementing the pick method inside the method like before we will find a random value between 0 and the total number of points suppose the random value is 19 we need to find the rectangle in which this 19th point will lie now from observation we can see that it lies in rectangle 2 but we need to find it programmatically as we know the list is sorted the best approach would be to use binary search we will see how it will work for those of you who are comfortable with binary search are good to skip this part we will take two variables low and higher point to start and end of the array we will loop till low is less than high we find the mid of the 2 and compare its value with the target as its value is less than the target we are sure that our result lies on the left part so we update the right to mid we again find the mid and this time its value is greater than the value at mid so we update the low to mid plus one as the while condition fails we come out of the loop with this search the pointer low points to the index of the rectangle which will have the target point now the question is to find a random point in this rectangle there are approaches which finds the particular target point but i use a different approach as we know the x and y coordinate of rectangle 2 we know the answer can be anywhere between 3 to 5 for x and 2 to 5 for y we find the random between the two we use this approach we will add the difference of the 2 x and 2 y into their minimum value remember the upper bound in random function is excluded that's why we have added 1 into the difference the values will look like this we can have x between 3 and 5 by adding any value between 0 to 2 in 3 same for y at the end we written x and y the algorithm for preprocessing will be just to iterate over the input array and store the total number of points till every rectangle in the list now for pick method we'll find the random point between zero and total number of points now we search for the rectangle in which the target lies we use binary search as the list is sorted now all we need to do is find the random point in this rectangle and return it the time complexity for preprocessing is often while for pip method it is log login the space complexity is often here is the actual code snippet you can also find the link to the code in the description below thanks for watching the video please like share and subscribe let me know in the comment section what you think about the video
Random Point in Non-overlapping Rectangles
random-point-in-non-overlapping-rectangles
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. **Note** that an integer point is a point that has integer coordinates. Implement the `Solution` class: * `Solution(int[][] rects)` Initializes the object with the given rectangles `rects`. * `int[] pick()` Returns a random integer point `[u, v]` inside the space covered by one of the given rectangles. **Example 1:** **Input** \[ "Solution ", "pick ", "pick ", "pick ", "pick ", "pick "\] \[\[\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, \[1, -2\], \[1, -1\], \[-1, -2\], \[-2, -2\], \[0, 0\]\] **Explanation** Solution solution = new Solution(\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]); solution.pick(); // return \[1, -2\] solution.pick(); // return \[1, -1\] solution.pick(); // return \[-1, -2\] solution.pick(); // return \[-2, -2\] solution.pick(); // return \[0, 0\] **Constraints:** * `1 <= rects.length <= 100` * `rects[i].length == 4` * `-109 <= ai < xi <= 109` * `-109 <= bi < yi <= 109` * `xi - ai <= 2000` * `yi - bi <= 2000` * All the rectangles do not overlap. * At most `104` calls will be made to `pick`.
null
null
Medium
null
1,247
hello so continuing today on this contest 161 athlete code this problem is called minimum swabs to make streams equal and so the problem says we get two shrinks s1 and s2 that are of equal length that have letters only letters x and y in them so this is important only x and y letters and that our task is to make these strings equal to each other so we can swap any two characters that belong to different strings so we can swap one character in one position from the first shrink with another character in another position from the second string and we can make as many more swaps as we want to make them equal and the goal of the function is to return the minimum number of swaps that we need to do to make s 1 and s 2 equal if we can't do that we should just return minus 1 so if we look at the example here we get xx and YY we can swap this one with the second one and basically get Y X and YX which are equal for this one we can swap first the this position this X with this Y and get X x YY and then from these two string we can swap this Y here with this X and get X Y for this one we can't swap anything because there is only one difference so whatever swaps we do you can try it on a piece of paper we will get we can't get them to be equal so we return minus 1 okay so let's see how can we solve this problem so the first thing to think about is what are the strings we have what are the possible differences is just at one position like position I for both s and s 1 and s 2 what are the possible differences right well we could have either X and then Y in the second position that's the one of the options or we could have Y for s 1 and X 4 s 2 right so this one would be one position I and this one would be 4 position to write for s 2 sorry I'm not that so basically what would happen this is s 1 this is s 2 and this is s1 and this is s2 the other cases won't be different right the other cases either xx and YY or YY right so only these four cases we can have these cases are already equal so we shouldn't worry about them right we don't need to scrap them right now let's see what these two cases what can happen so with this one either we have two of these so either we have two of these in that case if we have two of these then what should what would happen is that we would have X Y so we would have something like this X Y and then X Y right in that case what we can do is just well swap these two together and end up with Y here because we swapped and then X here and now they are equal so we only need one swap for four pair of XY right let's call them four pair of XY like this right and this doesn't even apply to just to write because if we have even if we have let's say X Y and then X Y right so if we have four or even eight any multiple of two then what can happen is that we can fix this and make it the same with one swap right and then make this one with one swap right and if we have even more or less say another pair of X Y we can also swap these with one swap and end up with three swaps right as the minimum to make them equal there is no other way to make them in to make it less than that right so you can see here what's happening is that we're RVs this is just the number of X Y / - right of X Y / - right of X Y / - right so let's call this the number of XY pairs all right so this is only for case this here that I mentioned is only for case a this one right okay so now we handled the case where we have multiple if we have multiple of so this is basically the answer so this is the answer if we have an even number of XY right this is the minimum number of swaps we can make now what if we have an odd number of XY Z right so if you had an odd number of XY then we know that we need XY divided by two this will give us the number of swap for basically the number of XY minus one that would be this right and then plus either plus there will be one left right any even any odd number can be converted into an even number and plus one right so plus one right and this one what is this one is just X Y modulo two right this would give you one for the add case right okay so let's just keep this in mind and then explore before now and see so B has the exact same pattern right so B is having Y X so if we have two Y axes what would happen so if we have two Y X then that would mean we would have Y X like this and then Y X like this so in that case what we can do is just swap this together and end up with Y X right and they are equal so we needed just one swap right and same thing as for the aks we have for a multiple of two of Y X pairs then we can do it in X then we can do it in the number of Y X's divided by two so this is still the number of YX pairs such that this fits for s 1 the value minus 1 this is the value in s 2 now in the same case if we had an odd number in the same way as the previous one if we had a number add number of y-axis then same thing we can number of y-axis then same thing we can number of y-axis then same thing we can convert it to first an even number and then plus the whatever is loved so in that case it would be the number of YX by two plus y X modulo two right okay so now we know that our solution is so let's say let's go so this would be zero in the case where it's even so we can just include it in the general formula so now we know that this is the formula let's call this part here 1 and this is for when it's this is the part for the YX pairs right so the overall result will be the final result will be just 1 plus 2 there is just one case where we can't that we need to discuss here and so basically the string that we would have would be either accompany said either combination of these here so either multiple of these and maybe none of this one or multiple of these and none of this one or a combination of both or it may have maybe something like this a case where like this where we have maybe let's say two pairs of X Y and then maybe just three pairs of X and then another like value that is um that is let's say Y X right so we can swap these two in one pair and in one swap we can make this equal in one swap but the problem is when we have only this one what can we do but there is nothing we can do right let's just take an example let's take an example where we have and just one left from XY or YX pairs let's take this where we have XY X Y so you can see here we have these two equal this can happen after we do the swap or maybe just the original string was like this but then the problem is that we would have this one left what can we do like you could try to say okay well let me just swap these two together right and in that case what would happen is that we will have X and then since we swap at this one with this X would have Y X and X here and then we'd have Y so these two are equal but then you we are back at the same problem with only this one and whatever is what we do we'll go back to the same problem so if we have one case left of this or one case left of this then we can't solve it so we didn't need to return minus one but if we have one left of a and one left of B so we would have something like this where we have x y and y x and maybe there was another thing here that we needed to swap and we did that already but if we have one left of the a case so the one left of the AKS and one left over the B case we can't solve this Y can we solve this because we can't by taking these two and swapping first this one with this one which would give us something like this where we have X Y and then X Y which would give us two pairs of X Y so that would give us the a case here when we have a pairs of X Y and we can solve this with once well we can solve this with one swap by just doing what we do for this case which is swap the first with the last of the first of s1 with the last of s2 and with this one we can make them equal right away right so when a case was so only the case where X Y modulo 2 plus y X modulo 2 so if each one of them has left let's say one so we have two in that case we can make one swap and then we can solve it right with to swaps and to swap is just the Sun but in the case where one of them is left so that means that X Y modulo so one of them is left so we'd have only one as the result then in that case we have our only either in this case or in this case in that case we can't solve the problem so in that case we needed to return -1 and so our solution is what's return -1 and so our solution is what's return -1 and so our solution is what's called this here this formula here is quality formula a right so if it's formula a the results except if the X Y modulo 2 plus y X modulo 2 is equal to 1 or ism or is ad then in that case so it's ad in that case no matter what we do we can't and can't swap so we need to return minus 1 and otherwise we can just return the formula that we calculated because that means so the formula that we calculated we have X Y and this one plus this one right and so that's basically the gist of the algorithm to solve this now let's just write the code in detail to make sure you understand this so what do what we need to do is just first have a counter for the number of XY pairs and the counter for the number of YX pairs right that's what we said earlier and now we need to just go through the strings and see how many ex-wives we have and how see how many ex-wives we have and how see how many ex-wives we have and how many YX we have so we can apply the formula right so to do that we just need to go through each character of s1 and s2 and then just check which combination which situation we are in are we in XY case or a YX case so that would mean if we are in the XY case if the character of s1 would be X the character of s2 would be Y and then in that case we need to increase the count of XY or as if we are in the case of YX and that means the character of s 1 is y and the character of s 2 is X in that case we need to increase the count of YX and now we need to do to apply this basically the exact same thing right so we need to check once we are done we need to check is the count of modular 2 + y X modulo 2 is that odd modular 2 + y X modulo 2 is that odd modular 2 + y X modulo 2 is that odd which means there is um which means there is one that will be left from one or the other in that case as we said we can't solve it so many traits and minus 1 because we would be either in this case or this case and we there is no swap that would make them equal so in that case we can return -1 or we are not that case we can return -1 or we are not that case we can return -1 or we are not and then in that case we can just apply the formula that we just done that we just explained which is just returned return the number of swaps for the pair the even pairs of XY plus the number of swaps needed for the pairs of YX + so if swaps needed for the pairs of YX + so if swaps needed for the pairs of YX + so if we get here that means we have either 0 left of each or we have one left of each right because if there is one left of one and not of the other we would have already entered this case and so that means that we would have + YX sorry Y X okay because this would be a the zero plus zero and then that case where we have a only an even number of both all we have one of each and in that case we are in this case here and we can solve it with two swabs and two swabs is just one plus one right and now that's pretty much the result so let's type this into lead code and see if it passes okay so I type it the solution that we just saw in the lead code so zip here would make sure that we take only a portion of each that like each character time of each and then we calculate the number of XY and YX pairs we check if there is an odd one an odd number then there is one left of either one in that case we can't solve it so two minus one otherwise there is either zero left after each one is paired with V with the other of each or there is zero left of each and in the case where there is one left of each it's to all the case that is zero left for each is zero and then we could just use the number of swaps required which are one swap for each pair of XY for each two pairs of XY and one swap for each two pairs of YX and that's pretty much it so let's run this and submit okay so that passes um late code solution here and the time complexity of this is we are traversing like each one of them once right so it would be the length of the smaller one right so it's kind of and they saw of min of n 1 &amp; 2 kind of and they saw of min of n 1 &amp; 2 kind of and they saw of min of n 1 &amp; 2 if we say that N 1 is the length of s 1 and this one is a public service - and this one is a public service - and this one is a public service - and the space complexity is constant yep and that's pretty much it for this solution thanks for watching and see you next time bye
Minimum Swaps to Make Strings Equal
decrease-elements-to-make-array-zigzag
You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`. Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so. **Example 1:** **Input:** s1 = "xx ", s2 = "yy " **Output:** 1 **Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ". **Example 2:** **Input:** s1 = "xy ", s2 = "yx " **Output:** 2 **Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ". Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ". Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings. **Example 3:** **Input:** s1 = "xx ", s2 = "xy " **Output:** -1 **Constraints:** * `1 <= s1.length, s2.length <= 1000` * `s1.length == s2.length` * `s1, s2` only contain `'x'` or `'y'`.
Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors.
Array,Greedy
Medium
null
1,675
hello everyone welcome today we are looking at another lead code question which is minimum deviation in array now in this question we are given another nums and it has n positive integers and we can perform two types of operations one if the element is even then divided by two for example one two three four where four is even i can divide by two make it two and the other odd and we can odd number can be multiplied by two now what we need to find is the maximum deviation between the two elements in the array right now this question is a hard category question in lead code and uh is kind of tricky in the sense as to how you're going to approach it because in this place you might have to look at maximum minimum values in the area and then see what operation needs to be performed and then kind of bring it to the minimum and by bringing that difference to the minimum obviously you need to kind of try to reduce the maximum number and bring it very close to the minimum number which i have right so this is uh and in order to do that we have either two operations either i can divide everything by two or multiply by two now multiply by two i is something which i can only do with the minimum numbers because idea is again to bring the maximum and minimum as close to each other as possible so to approach this right uh what we will do right uh we will go through this array and we'll first uh multiply all odd numbers to even so idea being that right is i need to find the difference anyways right and even number uh will be even number which is present in the area will anyways be highest right because that is sorry even number which is already there in the error will always be the highest and it's only going to reduce right so why not have addition to the uh odd numbers uh in the first go itself right the moment we do that right we have everything in one plane format as in everything is even in my array because odd multiplied by 2 will always be an even and then once i have even all i know is i need to reduce the numbers and i can perform that operation to make it simply in other words i am trying to simplify the problem in uh to kind of uh do only one operation or the two which is mentioned here right so with that right uh what would be the algo will be so in a way i will first step will be to multiply all odd by 2 to make it even second is find min and max post uh multiplication of what numbers now everything being now considering my even number whatever will be the highest rate based on difference reduce the maximum number at a given time in the array until we get the final results right when i'm saying final results that means that even max is now odd right what i mean by that right if you look at this example if i look at this example so i have this example with me now if i multiply this right i have 1 3 4 5 2 20 right this is my first step now second step is to add it into a list or you can say sorted dictionary or min he maxi whatever of data object data or data structure you want to follow or sets because that will ensure you don't have duplicates right and once i have it uh casting it is ordered i'll also do uh in addition to multiplication right off now in my set or in my dictionary on my list whatsoever you want to call it i'll have numbers 2 4 being the same 10 20. now this is what i have right now this is my list which i'm going to work on now i'll see what is the difference between the minimum maximum if is 18 right now can i reduce is my last number still even yes it is even i can reduce it i'll make it 2 4 10 and 10 right f is now eight last number is still even yes and trusting these two are already uh duplicate together even if i don't have it doesn't really matter so uh again i have the difference uh this is still even what my next step is uh say this is first this is second step now say whatever next iteration will be now this will be 2 4 and this will be say 10 and this will be 5 right but if you sort it then this will again be two four ten five and ten and this will again be changed to two four five considering i have i had considering i had only one ten that time right now if i look at it right now this is odd now if i look at the difference is 3 i cannot reduce this any further right and if i now look at the results answer to that is 3 right this is what we are looking for right to solve this problem uh i use uh considering we are doing sorting as well and to ensure there is no duplicate i am kind of going for your sorted uh set which is another data structure which is present in uh c as a language but uh if you are kind of uh working on java or you can working on python obviously you can go for min and min hit max uh many mac shape or sorted dictionary as an options uh i think we have a concept of set in java as well so you can always go and explore the options right once i have this right or this now must now i have a dictionary now i need to do is i need to go through all the variable in which is nums and if the value is even odd i need to add it to the num set as multiplied by true right num step dot add i'll say okay if num is for let's make it simple if num percentage 2 is double equal to 0 i'll say num set dot add num because it's an even number as i'll say num set dot add num into 2 right now with this i have my set which is having all even numbers i have i'm not using the indentation okay now i have this now once i have this right i'll say okay what is my uh current difference so my result if will be numset dot max minus num set dot min right this will anyways be the highest possible difference which is going to be there in the array right now what i'm going to do is right as we just discussed right once i'll iterate through this array or in this case my num set until unless my num dots the maximum value is still even right now once i have this even what i'll do is okay what is my last element in this one will be uh num set dot max this is just to simplify the problem i'll if you see i need to replace this 20 with this 10 right so i'll take this number divide by 2 and i'll add it back right so or i can just say num set dot remove num set or you can say last head instead of numser.max or i'll say okay instead of numser.max or i'll say okay instead of numser.max or i'll say okay num set dot add my whatever my last value okay you can use this but in this case once you removed it right you cannot add it any further right now once i have this i'll say okay what is my updated result difference will be whatever the minimum of those two will be okay math dot min what my current difference what is my current difference is and what is my new difference will be num set dot max minus num set dot min right once everything is i think sorted i'll ultimately return this i hope this should do the trick and let's run this okay i got one let's submit it nice it got accepted so uh i hope you would have understood the approach and how to resolve this in case you have any doubts any problems please go ahead and write in the comment section i'll be very happy i'll be very happily going to uh see those and try to resolve them if i'm aware in case you like the approach you like the solution please go ahead and like and subscribe and see you next time thank you thanks a lot
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
455
Hello everyone, my name is Ayush Mishra and Education Course, today we are going to talk about the product of Aasan on Play List, the problem is very sweet, here we will see two approaches, if the first approach, I will call you here. I will tell you and give other ideas which will make you understand something. After reading the question, what do I have to say, Azim, that you are a very good parent and you want to give something to your children. Who does not want to give any printer to the children? In the video, if you can see any one child, then it means that these people will be lucky to have children in their plate while roaming around, so now there are children, so for them, it is that you can see any one child and the thing is difficult. She says to the problem that you are an option parent, you have to drag your children to satisfy their desires and tell them that you can only give them to one most one, an adult. Okay, now everyone. The side that has appointed hatred, this appointment was told by a child that do the minimum that the boy will need so that he can fill his stomach as per his wish. Okay and you have one more, this is the list because the name of Jo That is by this name, have you understood that if the one who is telling us that what I have will not be charged in one minute or the country in which I will go, then that is its size because what should be the size, okay where do we have this thing? In which there will be a list with this name, it will tell at the time of its loss, what is the different expression on it at that particular moment of time, then its size is fine. Well, now if we consider any child and say give me a friend. According to people, please give me my computer that people have appointed me on life, Papa, otherwise it will not happen, so he is asking for two kilos, match one, that people do not have the mind and I did not do this, then I have to say that. Young children and subscribe means from home so we are appointed to subscribe here maximum number of children and we can give you list play list children's subscribe images here that 123 such children special to give you There is no need, there will be a second list, here is the creed of those children of the grid, see it here, read it here, there is a list of kheer for you, if you don't give me a third list, then Andheri if it is three, it means there will be three children, then subscribe. Didn't understand the need to do this, okay for this I have to say that if you have Yudh Quick and how many children are subscribed to it, then tell me how to do it, look, it is logical, look, I want 3 hearts, okay, but these people don't have it. So all this wo n't be possible. Well, if he wants dry food, then look, I don't have 2 kilos of it. I wo n't be able to get that too. He needs one kilo of sweets. I want one and a half kilos of sweets. Okay, so how many children did I have in total who were on the side, so mine is There was a child, that's why it is being made from France, okay, the next one, you see the example, here one is my child, what kind of father, I have one, okay, click on the pan and do one with me, the ghee present, subscribe that the question in the war, subscribe this. You can ask for things, after this, after all, which can be maximized, now you have to distribute it in some way, maximize it, subscribe and subscirbe, press the subscribe button quickly and 1234 were posted here, then do this festival effect in your case. On a good occasion, how much is the school fee for a girl? It is ₹ 10. much is the school fee for a girl? It is ₹ 10. much is the school fee for a girl? It is ₹ 10. And so what is the size of my ₹ 3. Well, size of my ₹ 3. Well, size of my ₹ 3. Well, you tell me, where did I go, first I put it here and I was sitting here. That I am Raju bhai, okay, I have come here, brother, father, I need one kilo, so I said, I am here to check Shalu, take it because it is here, Manish Sisodia said, let's run from here, okay, so take the clock from here. If a child is like this, then if it ends up on the father 's side, then soon in this way you had placed him on top of the other, here 1234 will look into it and make arrangements Dalip Singh Think that till the skip, people will give paper lace to each other, okay Okay this is so subscribe to this that I am here okay so this is what I am saying that pull which is seen here as the scenario for I am simply the karma which is read gun ghee I said which is the greed of these boys I will first sort it out and soften it, so what will go in small to big hotel, we will know who has so much greed, how many kilos of items does he need, how many kilos of sugar, I will know, after this I will know how many things I have. Let's see how this is the list of how many kilos of kilos it is good for him to run to Meghnad. It is good for you to have a disgusting first child, this will give the company at least 15 back terrorism. What happened to these three children here, something like this has not reached, so if you If you are interested then see what you will do, I told you to give me Creed and some attention to these two, then I will follow the index and list both of them, the index number of both is zero, now the laptop is calling the children from Caroline, from here we children. Roy is calling me, Roy is echoing from here, so first I shift my grid and my class position playlist. Okay, so here we are at 1453. I left it at 145 and I have written here and subscribe that I have written here subscribe 0 here it is great that the index of the first list is pointing to it for whatever it is and if there is something else then what is it doing then point to the index of the second list. Who are we responsible for this? Here, the first child said, I want it, so I said, as long as the rear is less, then subscribe, which means now we have not missed the other one, Rukha, whatever is there, now how will I pull it at all. Ghr went okay here and if the people have finished subscribing then the children have got the condition that they cannot do so, then you people are asking that how much space will you take to log in here and post it, now its 19 It may be okay, it may be okay because it will take you time, but you will take end space, such that I have element having cover for common more family, we have done grill to children from treatment, she said okay and drag my pass 106 Folk songs, the simple way should be that you should subscribe to both of them and you can subscribe to others. Okay, this can be done by anyone from home, this can be subscribed. Meghnad has the biggest question, I am the first person to write this. Don't know if it's yours, that's why it will work, then no one will come to you on this, cut off the printer for the problem, it will be found above in the comment, so I hope you have understood any problem on your side, grinding the sign or it is a mistake. was a trap
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
1,704
Everyone welcome back in the video and in this video we will see string based problem so this is an easy question of lead code so let us directly see the example and understand then in this problem we will be given a string, suppose the first string given to us is let. From the book and whatever the length of the string will be, it will be and, so you can see here, there is zero, one, three, so whatever its length is, that is the string, so we can divide it into equal parts like if we divide it into two parts. If we divide then the first word will be BO and the second word will be OK Right and we have to check how many things have to be done in the first word that comes, as you can see in the example, here book is what is the true return, so let's go to the second one. Let's take an example in which we have to count, text book, we are indexing it, zero one, three, four, five, six, seven, length, what is our second, which will be equal to four, meaning this is the fourth index, our second world is starting, right now the first word. is text and the second word is book, in the first word we have to count the vowels, what are ours, once we write them, we have to consider both, the small case ones and the capital ones, we also write AI I O U and capital letters. A I O you right and here we also see a little bit, so we will maintain two variables here account van equal tu zero which is the voice of the first word account tu equal tu zero and two variables which will run from zero and Secondly, what will we keep the value of J and J, what will be the character, we will get it, okay, first of all, if it is not there, then it will be from the value of count, then what will happen, we have to get i0 and what is K, what is four plus zero, what is four, so If it is ours on four index then we will also check B. If it is in AU then the answer is no because this is also not oil, then the account will remain as SIM of both, then come here, if we increase it, then we will not do anything to the account. Let us check. OK, here we have By one mistake, you cannot be zero, there will be only one van, what will happen after the van, so friends, it is a very simple program, we try to code it, so first of all we take a variable in which we will find the length and Here whose value will be kept n / 2 whose value will be kept n / 2 whose value will be kept n / 2 and let's take the variable count van equal and 2 and let's take the variable count van equal tu zero and count tu equal tu zero correct and let's take a string vowels in which Similarly we will take out the character tu bhi nikal lenge and here what It will happen as we discussed that if we check on k plus i then we will check wow index off. This is the correct way. Here you understand and here it seems ch1 is not equal tu minus van so what will we do count van plus -1 return. Will do if suppose had come here had come -1 return. Will do if suppose had come here had come -1 return. Will do if suppose had come here had come if it has character index -1 not if it has character index -1 not if it has character index -1 not character count if mine's one then do n't count it thoughts the same see have not equal thou mine's van anything which is not equal thou mine's one and see have thou count it Right put another if and sim will copy and friends, if not equal then it will false then let's run and see so sample test cases are passing in next video.
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
1,614
hello everyone welcome to harsha lectures in this lecture i am going to explain you about maximum net nesting depth of the parenthesis so here a string is a valid parenthesis string if it meets one of the following so here what they mentioned is we need to find out maximum nesting depth of the parenthesis for example here in this example one they given here one here they given this input so here it is having three open parenthesis and three closed parenthesis so the number of maximum parenthesis is available for this eight only so we need to show the output three parentheses are the highest here the explanation is digit 8 is inside of three nested parenthesis in the string so we need to find out the maximum national parenthesis which is having in that string okay and here in this example two also for this we are having three parenthesis three nested parenthesis so here the count is also output is also three so in this way we need to show the output okay so for this question i will implement one logic first i'm mentioning in result variable equal to zero and current equal to zero actually i created two variables and for the two variables i allocated the value with zero and here i will mention for in i equal to zero and i less than s dot length and i increment okay in this i will mention if s dot characteristic of i if it is equal to open parenthesis then i will mention here result equal to math dot max and in this i will mention result comma reincrement current and here also i will make pre-increment i okay i will make pre-increment i okay i will make pre-increment i okay and here if s dot character h of i is equal to close parenthesis then here i will mention result equal not result here i will mention current decrement so here i will written result so this is the logic so we check whether this will be execute or not yeah accepted so i will explain clearly once again i just created two variables one is result and current i just allocated zero value for those two variables and here in this for loop i just uh mentioned i equal to 0 and here i just iterate the first position to lost position in the given string in that given string i start comparing with asteroth character at i position what is happening from first position to last question i will check if that every element is equal to parenthesis open parenthesis or not if that having if it is find out the open parenthesis then i am storing in the result and again i wish to find out the maximum number of nested parents is i mentioned math.max so with parents is i mentioned math.max so with parents is i mentioned math.max so with the help of this logic i am going to find out maximum number of nested paranthesis so by implementing in this logic we can able to find out the output so this is the logic behind it now i will submit this code yeah success so what i'm saying is if you have any queries you can mention your doubts in commentary session and please do like and subscribe for more videos thank you
Maximum Nesting Depth of the Parentheses
maximum-nesting-depth-of-the-parentheses
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or * It can be written as `(A)`, where `A` is a **VPS**. We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`. * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s. * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**. For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s. Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`. **Example 1:** **Input:** s = "(1+(2\*3)+((8)/4))+1 " **Output:** 3 **Explanation:** Digit 8 is inside of 3 nested parentheses in the string. **Example 2:** **Input:** s = "(1)+((2))+(((3))) " **Output:** 3 **Constraints:** * `1 <= s.length <= 100` * `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`. * It is guaranteed that parentheses expression `s` is a **VPS**.
null
null
Easy
null
872
long time the reason being we have already solved most of the questions that come in Daily de code problem today I found an portunity this question I haven't solved it in the past rest all those that have been coming along guys do check out coding decoded YouTube channel you'll find them there if not then I promise I'll definitely come that day and solve that question today's lead code problem is leave similar trees here in this question what do you want to what do you have to do you given the root of two trees and you need to identify the leaf nodes of both these trees you need to store them in the form of a list and then you have to compare those list up if those lists are equal you need to return true otherwise you need to return false this is the Crux of the question it's an easy level question and I believe my subscribers would be able to solve this question by themselves for those who are new this video is for them the first three as this one this is the same example that was specified this is the second tree that is given to us what do you need to identify the leaf nodes that exist in this entire tree what are those Leaf nodes six is a leaf node seven is a leaf node four is a leaf node nine is a leaf node and eight is a leaf node you have to store them in an array uh you can use a list for this purpose and let's do that what kind of traversal would be appropriate any traversal uh BFS postorder pre-order any traversal uh BFS postorder pre-order any traversal uh BFS postorder pre-order DFS you can use any traval of your choice what do you need to do you just need to store all the leaves that are there in the Tree in an form of an array and let's simply use a pre-order and let's simply use a pre-order and let's simply use a pre-order traversal when I say pre-order what kind traversal when I say pre-order what kind traversal when I say pre-order what kind of traversal that would be info left and right so first of all you will go and check the value at the root if it is leaf or not if it is not a leaf you will move toward its left child if it and then you'll move toward Its Right child if it is a leaf node then what you're going to do you'll store it and an array and you will pass that array to the uh in the incoming helper method uh you'll do a similar kind of thing for this particular area as well and what will you have after the iteration in that helper method it will be something like this you will have the elements as 6 7 4 9 8 similarly here as well 6 7 4 98 and once you have stored the result in an array for both these trees what you're going to do a simple comparison between these two list as you can see all the elements in these two lists are equal and you will go one by one iterating over each and every element across these two list and 6 is equal to 6 7 is equal to 7 4 is equal to 4 9 is equal to 9 and 8 is equal to 8 since we have successfully checked that these two lists are equal in nature we will say it's a happy case and return true had it there been a case where any of these element would have been missing or different then in those cases we would have returned false to conclude the question further let's quickly walk through the coding section and I'll exactly follow the same steps as I have just talked here list one and list two I have passed this list one as part of in invoking my helper method find leav I pass in the root of the first binary tree that I have and the second parameter is the list where I'm going to store the leaf notes similarly I do a similar kind of thing for the second tree and my second list and once I have iterated over uh find leaves method over both these trees what do I check whether the size of list 1 is equal to list two or not if those are unequal then up front I can say that it's a negative case I'll return false in those cases otherwise I iterate over my list one I check whether each element of my list one is part of list two if it is not at the same index if it is not then I say false otherwise if this false condition is never met what do I say I return true it's a happy case so in case the false is never returned across these two return statements that means we have successfully identified a positive case and I'll return true in those cases now the problem lies in how do you write the fin leav method so it's really simple we are using a pre-ordered reversal you can are using a pre-ordered reversal you can are using a pre-ordered reversal you can use a postorder reversal in ordit reversal or BFS if you want and uh in case my root is null I abought the process otherwise I check if my root happens to be a leaf node what is a leaf node how do you define it both the children of the leaf node happens to be null and in case it is I add it to my list and moving ahead I iterate over my left child and then my right child pretty simple and straightforward let's submit this up accepted and it beats 77% people uh up accepted and it beats 77% people uh up accepted and it beats 77% people uh in terms of time complexity which is pretty good also the credit of this solution goes to s of he submitted the solution an hour back I reviewed his PR and I merged it into coding decoded get repo similarly the solution for C++ the credit for the solution in C++ C++ the credit for the solution in C++ C++ the credit for the solution in C++ goes to msv Gupta uh so he is also an active subscriber of coding decoded who regularly submits Solutions onto coding decoded GitHub repo the third person I would like to name is Sarang he's also a very active developer who solves daily lead code problems and is very active on coding coded telegram group gooders to you guys keep up the good work apart from this if you also want to build the same level of consistency that I have then what you should do you should solve daily lead code problem and once you are done with the solution you should raise a poll request on coding coded GitHub repo I'll review it from interview's perspective and once I find it appropriate I'll merge it into Master it's going to help all the young Engineers out there who aspire to build strong DSA foundation and I hope to see you see your poll request very soon take care I'll see you tomorrow with a fresh question if it's a new one and have a great day H goodbye
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
979
Hello Hi Guys Welcome To My Channel Beauty Parlor Doing So In This Video Will Do Some List Co Problems And Also Be Doing A Dynamic Programming Problems Will Complete Directly Robot Tyou Edit Co Problems And Whose Turnover Is Not Hearing Date Sheet For A Third Bell Icon Posts 216 Tasty Certain Problems Aa A Solid Problem And What Is The First Co Latest Distributor Points In Early Trade Root Of Binary Tree With Not Valid Node Industry Is Not Well Number And 19 Number Nine Total Notes In How Chilli Use 2% Notes And Move Want From another not know what is the distance from parent child and Use 2% Notes And Move Want From another not know what is the distance from parent child and parent should not be eliminated from root will not be written minimum number required to make every not have exactly one that your soft for later written down what is given to find a improve and No dinner and join us what is the answer objective it snowed suggestion one coin receiver objective see that a not only 10 world to minimum number and investment and return minimum of mood correct you slept jagdish singh sir given and how can they transfer one account to Another point is country from parent child and skin vikram website pay rent to avoid transfer point note requests for a notice defeated and electronic ok so let's see how this work on jhal solidification example owner that 3013 well 0km what will oo will move how Many points this is not needed for all how to get read of records which needs this festival in notes quality and fog 2012 a plus half loot valley of twenty nod to hai aapse youtube me in this oil explain why I salute in another example of This only but just remember food value fennel liquid not review nor do you need one plus one will give oo this software telecoms like this is not live without oo ok 200 isko apne lip par share and also address given in the problem statement from parents Spirit And E Was A Child And The Girl Child Died From Parent Child From Child 2030 Something Like This Me 120 Distributor Daily 1512 Servi Weakness 0210 A Here Totally Free Mode From Sweater Side To Good To Parents Idea Music A Start Listening To This Vihar To Go From Parent Child of Venus Travels and Tours of Compound 10 Minutes No One Cold Well Be Completely On 108 Something Similar To Lacker Defects Problem Correct They Need To Search On Every Possibility Connected To Back Particular Development Parents Sexual It Is The River Water Left Side Right side is that this child and parents only in a relationship like you can give from side to paint child it's better to check the children first vikas vihar and traversal total postorder traversal news poster traversal preorder traversal subscribe video like share and end Get To Know What Is Happening In Our Children Will Strive For What Is The Benefits Will Get To Know What Is Happening For A Day And Child Needs Points And Immovable Gifts For Endorsement System Strong We Can Understand One Thing They Can Do Postorder Traversal Latest Example 9 And See How They Can Do Poster Traversal So Let's Check The Tree Something Like This Is But Tears One And Mrs Normal Note Clearly Number Of Roadies 6 And Number For Access Oil 206 Developed Number 222 Problem Latest Post Traversal Must Subscribe To A Fight Welcome Back Cover Fear and Requires No Left Right Left with Nothing Will Happen in Fool Yudhishthir Water 600 Currently They Are Too Correct Where to Our Current Notes Value Greater Than One Who Did n't Give Me Gave Only Transferred Into What We Will Do Subscribe Coil - 151 - 1384 Current Values ​​Greater Than Coil - 151 - 1384 Current Values ​​Greater Than Coil - 151 - 1384 Current Values ​​Greater Than One And Half Inch Extra Oil Hai That Chali Number Current Value - Current Location To You Will Chali Number Current Value - Current Location To You Will Chali Number Current Value - Current Location To You Will Increase The Number Of Moon Will Increase In Inke Switch On This Video Subscribe To Channel Not Only One What We Can Do Is Our Present Were Willing Prevented By This Much And Will Account The Number Of Malls Number One Extra For A Third Year And Don't Forget To Subscribe Where Does It How Lottery What Will Happen If You Want To Know Where Oil Change All Things In This World And You Should Be Taken Care Of And Easy To 9 Points 1199 Subscribe 09 2012 Current Quiz That Garlic One Correct Answer For A Valid Points From Transfer Current 12321 Liquid Important Question Liquid Number Of Mid-day Mills Subscribe to Video Transfer into Someone Video subscribe to Transfer to the Other Notes But in this case Worker April 2015 But this person Possibility to certain extent of current mode on Subscribe to this video channel Not Know What Will You Need You With Current Parents Front Value Will Reduce The Number Of Moon Will Be Easy Who Invented By How Much You Will Need Fennel Military Change Nau Strengthen Saave Tree Currently Suhawal Change Explosion Morning Evening Nav Ten 200 Comes From Parents Subscribe And Give The Child Not Concentrate Notifications Contract killer is I this particular latest concentrate on a for this particular not what is the parents this what is the current values ​​in parents this what is the current values ​​in parents this what is the current values ​​in maximum fuel in at least some will take water from the rest parents normal soil change 2000 not dheno deficit completely from this post At river flood lights subscribe now to 9 and your values ​​are subject to hello how is the richest quite clear they will take 202 so a particular note sudhir what happened now they know what is not the volume to with which will give oo no value - 151 Will Not Have A Main - 151 Will Not Have A Main - 151 Will Not Have A Main Saj ​​Dhaj Gori Review Board Parent Saj ​​Dhaj Gori Review Board Parent Saj ​​Dhaj Gori Review Board Parent Child And Sky Deck Child Not Where Great Receiver Current Water Retention Icon Its Eyes Are Considering All Will Power Child A Greater Than One Number For Intense Extra Points To The Number Of Very Much Needed is simple this volume is used in writing about the is telling about traditional weight lose weight come to needed for acid oneplus united value of the present value subscribe to understand what is this ayush suggests you to take the example it you can take you will get A How To Type Of Speech By Taking This Example Aur Main Bhi Aur Mein Bhi Devotional Song 1 Hai To Wire Giving Bhi Iss Example Se Smell Bhi Darmiyan Instances Where Particular Note Value Option Negative It Means Loot Mist Number For X Minus One And Plus For Normality Plus One Who Knows - Plus For Normality Plus One Who Knows - Plus For Normality Plus One Who Knows - Two Not Made That One Knows - To Back To Give Two Not Made That One Knows - To Back To Give Two Not Made That One Knows - To Back To Give Friends Number For A Widowed Mother Will Be Plus Minus Two Right to Minute Account of Number of Most Corrupt or Available Chord Account Readily Available Account It is Heroine for Poisonous Blackness Right the Function Cold Answer Know the Parameter is the Answer Function Abhi Taking AC Vinit Praveen Meet Paint Nodes Pet Child Notes and Need Na account according kind of updates to initially parents and child kid also angry initially e a picture with don't know this parents fruit parenthood zoom face to face only and contacts pass detailed thing and service from this function with these to return account anti for anything and senior notice Right our answer function for the parameters and parents are loot achha health and number of mujre hai main to fail ho phone par temple ki agar current not so always work current note will be child world records where not following order poster roy poster wicket liye subscribe ki Building This Channel It's Final Product Like Poster First Go To Subscribe Particular Change The Current Child Will Change Bluetooth Of The Day Come That Positive Like This Is 200 Sapoch 1230 K Initial Parents And Child Bottle 135 Quote 2 A Patient Will Become The Child and child will become what the child left subscribe to the Page if you liked The Video This is child will become child left Students by giving this only to parents child and subscribe left thing for right side Video give child stars then and now child will become Easy The Right The Current Child Right A Okay Wait Come To Posters Edit Nav Want The Africa Hours Registry Na Vrat Karenge Mode Switch On 900 Current Means That Channel Subscribe Value Is Great Dane Extra Coin Is Equal To How Many Extra Points The What Is The Value Of The Notice - Proceeding Latest Change Child Will Give You Have Not Been Upgraded It's To Know The Giver Paint Will Be The 13th President Value Vikram Parents Plus Six Payment Voucher Struck Him On 58th Update Our Account Of Move Quantum On This Will Be Extra Number Is the formula you want to see you can right leg child welfare and 1 - that child while selecting a relationship with him in this no child development but there should not be decreased by the number of rich person - is equal to need a that and account will Increment by whom I don't thing which give the answer latest si hai arabi sum silave mistake hai ya swarna i don't know on karo jhal just giving a correct answer and assist you for the problem and evocative visible to understand and you can write there on According with his work he problem is three different approach inside of rooms at every 90 number for a total number of all the number for a total number of the number of no problem ok sweater for this video I hope you enjoy this please like button Click Hello Friends Till Now Possible subscribe The Channel Let Will Really Motivate Beam And Under The Next Video Entry System Difference Of Water And Connected Specific Tune O Jhaal
Distribute Coins in Binary Tree
di-string-match
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
Array,Math,Two Pointers,String,Greedy
Easy
null
438
hello everyone today's questions is find all anagrams in a string given a string s and a non empty string P find all the start indices of piece anagram in s first we will understand these questions and then we will move to the solution part so what we have to do according to our questions we have to find all start index of piece anagram in s so okay this is a string and it's possible anagram is we check a B or B is present in a string or not if it is present then we will return the start index so this is our result we check this is equal to yes this is equals to so we will return the start index that is zero and now the window now we again check please Anna come match with this window yes this is match so start index that is 1 again this window so matched with this window yes this is matched so we will return the start index so now zero one two is our answer I hope you understood these questions now we will move to the solution part so now we will solve this problem using the same example so first we count the value count the character in P so is one time B is one time and C is one time okay so now iteratively we check each character in s and basically wait basically we take three sequence and check with this P so now our first three sequences this and we check this is match to it P yes this is matched with P then we will return the starting character index that is zero again we will check next three and now our next three is B is BAE this is matched with P no again this would now again we will check this three a and B and this will matched with is anagram no this is not match to it again now we'll check this three EB is matched with a sonogram no again we will check this three be a be matched with P and a gram no so again we will check the this is matched with P and a gram no again this now will check B AC this is matched with peas and a cramp yes this is match to it cause there is 1a 1b 1c so we add the starting index so that is 6 so now we again take a C now we check a C and D this 3 so this is match to each piece and akram no this is not matched finally it's the end of this string so we just return the written our answer is result equals to 0 and 6 I hope you understood this solution so how we implement it so we will take a dick study will take a dictionary and start from zero index is 0 I 0 and now check this is present index I didn't know so we simply add it in dictionary as a value 1 so now with shake B so now we add it in dictionary again this is not match with peas anagram no so again we check this and editing dictionary so we check this is matched with peas and in from yes this is matched with then we will add the start index that is 0 so now our I is 3 so when we reached greater than Elian P minus 1 means when our eyes greater than L me NP is 3 minus 1 that is 2 when our I 2 then we will check to condition that is we will reduce the last element value from the dictionary so that is our last element is C so if this is greater then we reduce now our C is so first we sorry first we will add e first we will add and then we check our eyes 3 is greater than 2 so we reduce C minus 1 and now C is 0 C 0 now we check another condition if the dictionary value is 0 so we will simply remove this from our dictionary so now our window is pointing this and this so now we check BAE is equals to P zarok RAM no this is not so now we again know our I is finding to four is four then we add be the again now our B is 2 so which again is greater than 2 yes I is greater than 2 so our last value is B's our last value so we reduce minus 1 so I current I is 2 so 2 minus 1 that is now B is 1 so as B is not equal to 0 so we will not remove be from our dictionary so now our current window value is a EB is equals to ABC no so I is 5 so we add so now our last element is a we removed a form of a dictionary so that is now our dictionary a is 1 now our dictionary value is BAE so we check equals to ABC no so again this value so now our window is pointing to these three B a B so a new value is B so we add B and our last value is e so we reduce e so now E is 0 so we will simply remove this from Dick's not some from dictionary so now our B is to is one to time be again increase our so we will increase our I value that is six and that is seven and now pointing to this 3 a da and thus value is B we reduce B minus 1 now our B is 1 and a is so we check B a is matched with a sonogram no BA is not matched with peas and akram so now we again move to the next value so that is 8 so now our current window value is B AC so we reduce e and now our is or is this and now we add si spun and now we check this is matched with peas and Akram yes this is matched with peace anagram it's a nice treat peace anagram so now we will add the start in it and if that is B AC so we add us starting index so now we move to the next now this is 9 index I equals to 9 and now we forget the 6 we reduce - first we add D forget the 6 we reduce - first we add D forget the 6 we reduce - first we add D ad b equals to 1 and reduce C be sorry B that is a so now because to 0 so we remove it for dictionary our current window value is a c d su d is equals to P is anagram no so finally what is the end of this string so we simply written our answer you understood this solution now we will move to the implementation part first we will count the piece value using counter collection dot counter and next we'll take a result list and then a dictionary is where we count up is fell and iteratively we visit each element each character in s and then we check if is I in dictionary then we will increase the dictionary value by one and if it is not present then we'll assign this character as a key value as one else assign this character in disarray as a key and value as 1 and now which is greater than NP minus 1 and then we will reduce the last added value the stated character value that is I - le n p le NP cause value that is I - le n p le NP cause value that is I - le n p le NP cause here our window size is Ln P minus 1 so now we check dicks is - le NP it takes now we check dicks is - le NP it takes now we check dicks is - le NP it takes element I minus s I - alien P is equals element I minus s I - alien P is equals element I minus s I - alien P is equals to 0 then simply we remove it to equals to 0 then simply we remove it for medicinal I mean if the character value is 0 then we will remove it from a dictionary as we already explained it in our explanation so now we check Oh wah dicks P is equals chuckles - Oh wah dicks P is equals chuckles - Oh wah dicks P is equals chuckles - dicks s means pees anagram is masked with dicks s so will it is equal then will I paint the index in our result list and with a pin the starting index so we take starting index I - alien P so we take starting index I - alien P so we take starting index I - alien P minus one starting index so we return our aureus it's at this erase you store the index now we'll check working or not okay this is dicks capital S yeah so we check so working or not yes and now we will submit it you have got accepted I hope you understood this solution if you liked this video please give me a thumbs up if you're new to the channel please consider subscribe and don't forget to be double like and thank you for watching this video
Find All Anagrams in a String
find-all-anagrams-in-a-string
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may 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:** s = "cbaebabacd ", p = "abc " **Output:** \[0,6\] **Explanation:** The substring with start index = 0 is "cba ", which is an anagram of "abc ". The substring with start index = 6 is "bac ", which is an anagram of "abc ". **Example 2:** **Input:** s = "abab ", p = "ab " **Output:** \[0,1,2\] **Explanation:** The substring with start index = 0 is "ab ", which is an anagram of "ab ". The substring with start index = 1 is "ba ", which is an anagram of "ab ". The substring with start index = 2 is "ab ", which is an anagram of "ab ". **Constraints:** * `1 <= s.length, p.length <= 3 * 104` * `s` and `p` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Medium
242,567
1,171
hello everyone welcome to my youth programming club today we will be solving another daily Le code problem and the problem's name is remove zero some consecutive notes from link list so let me describe this problem statement in my own words so what you will be given is you will be given a singly link list okay so let's say the link list given to you is this particular one and let me uh write it in the form of that you can visualize it how everything is going on so two is connected to two then this two is connected to another minus 2 and then this one is connected to one then this one is connected to minus one and this then this one is connected to another minus one that is there okay so what you have to do is you have to pick the consecutive Parts in this particular link list which are adding up to zero and remove them okay so if You observe that these what will be these parts okay uh these parts will be these 2 and minus 2 are summing up to zero okay so if you do something like this so it will add up to zero and this one also is summing up to zero so 1 + -1 will be is summing up to zero so 1 + -1 will be is summing up to zero so 1 + -1 will be 0o so you have to remove this much portion okay and join the rest so your return uh the link list that you will be returning is 2 and minus one okay so this is what you have to do in this particular problem okay and let's have a look at the constants also before talking about approach of solving it so the number of notes between given link list is between 1 to 1,000 and each node in the link 1 to 1,000 and each node in the link 1 to 1,000 and each node in the link list is having values betweenus th000 and 1,000 okay so now the question and 1,000 okay so now the question and 1,000 okay so now the question arises how we are going to solve it so first of all before discussing our approach I would like to introduce a topic uh for those of you who are not familiar with it uh prefix sum okay so let's take the previous example uh 2 - 2 1 - 1 - 1 okay so 2 example uh 2 - 2 1 - 1 - 1 okay so 2 example uh 2 - 2 1 - 1 - 1 okay so 2 - 2 1 - 1 - 1 - 2 1 - 1 - 1 - 2 1 - 1 - 1 okay so this is the link list that is given to you and if you have a variable uh let's call this prefix sum and initialize it to zero and you are traversing this list from left to right direction and whenever you are visiting a single node you are adding it to the prefix sum its value to the prefix sum so when you will be visiting this node prefix some values uh will be two and then uh prefix some previous value was two and uh current note that you are visiting is two as of now so it will be four so then you will adding this one also to the previous prefix some value and then it will be two and then you will be adding one so it will become three then you will be adding again minus one so it will become two and then again minus one so it will become one okay so these are different prefix some values at different instances when you are visiting different nodes in the given link list from left to right direction okay so uh this is what prefix sum is okay prefix sum is uh nothing but running sum okay if You observe carefully whenever you are seeing that uh certain segment of Link list will is uh adding up to zero then before that segment what ever was the value of prefix sum is same uh and uh as the value of prefix sum after that segment okay so what I mean by this is or at the end of this segment you can say so you can see that this two is again repeated prefix some value two is again repeated because you know why we why it is being repeated uh here the value was two and this whole thing will add up to uh what zero so 2 + 0 will be 2 only to uh what zero so 2 + 0 will be 2 only to uh what zero so 2 + 0 will be 2 only so that's why we are getting uh 2 here so that's why this piix some value is being repeated repetition here so this particular observation that whenever the uh value of a segment is adding up to zero and uh the repetition of prefix some value will be there so this particular observation will pave the way uh to you know uh build up the solution okay uh you can observe a similar effect here also here you can see that this particular segment will be adding up to zero and this particular value of prefix sum is being again repeated okay so these value are again repeated like let me change color here so you as you can see this value is repeated again okay so there is repetition again so whenever this kind of repetition happens what you will do you will get the hold of the value of prefix sum just before the segment okay so what was the value of prefix some just before this segment it was this okay so you will get hold of that node at which uh this particular value of prefix some was there okay so it was indeed this node okay so you will what you will do you will change the next pointer of this particular node let's call this previous anchor okay and you will change the value of next of this particular node I mean you will be uh cutting this uh or deleting this link and adding it to and pointing it to this particular node at the end of the segment okay so once you uh do this portion will be automatically deleted okay this portion will be no more because you when you will be visiting this link list from head to tail you will not visit this portion because next of two is now pointing to one instead of this particular node okay so this is the whole logic here and to you know get hold of this particular node just before the section you will use hashing okay so you will use hashing for each value of prefix sum you will keep updating what is the node at which this value of prefix some was there okay so there will be a map will be containing value of prefix Su uh so it will be a integer data type and then uh against that uh key you can consider it as a key there will be a value which will be the reference of the node at which that particular prefix somewhere value was there okay prefix some value noes reference okay so this is the whole logic that we will be using to solve this particular problem and uh there are certain edge cases that will be needed to taken care of other than that this is the whole Crux of the problem okay and there might be certain cases when we have to take care of uh certain things so for example you see that this particular portion is adding up to zero okay but if let's say you decided to put every value of prefix sum uh that was there uh in this particular portion while you are you know traversing your link list from left to right then after deletion of this particular segment you will still be having these values in your map so you should handle this case that you should be deleting these values otherwise when you will be seeing this six again you will see that uh your map is having uh you have seen this particular prefix some value before okay so what I mean by this particular thing I will be explaining in the implementation part so now without further delay let's move towards the implementation part okay so let's zoom out a little bit so that a larger portion of code is visible to us I think now it should be fine yeah so first of all this will be your running sum okay you will be initializing it to Zero running some more say prefix some then this one is the map that will be used to get hold of node previous to the uh zero segmenting segment that is summing up to zero this map will be used to get hold of the node just before the segment that is adding up to zero okay so the whole logic I will again say is that somehow if let's say this is the segment that is adding up to Z so you will you have to somehow get hold of this node and change its next pointer to the next node of the segment okay so these two nodes when join together will anyways remove this particular segment from the link list so this is the whole logic so this map is playing a crucial role here so then we will be having a dummy head what we what this dummy head will do this dummy head will be in front of the head okay so you can call this dummy head okay and it will be pointing to the Head okay and initially if let's say uh we have to put zero sum also in the map because you no when we are starting if let's say there is a value zero then you have to this particular logic only works when you have seen this uh rep when you are seeing this repetition in the previous some values okay so this repetition should be there so what repetition this repetition I am talking about as you can see this is the repetition so for this approach to work there should be a repetition so if let's say there are no other values summing up to zero so you should introduce a zero value by your own and you will uh make the node at which that uh this zero value will occur uh to dummy head so that's the whole logic of having this dummy head okay so then you will be just doing a linear traversal of this link list okay so this is just a Traverse of Link list uh and you will be forming the different values of prefix sum at different nodes okay so adding the current value current nodes value to prefix sum okay then you will check whether you have seen this particular value previously or prefix some values previously or not so what we are doing here is essentially that whenever we are seeing a value of prefix some that is already uh seen by us so we will uh come to know that there is a repetition and whenever there is a repetition that is for sure that we are having a segment which is adding up to zero okay so this will indicate that there is a segment that is adding up to zero okay so you know and if there is a segment that is adding up to zero what about the values of the prefix sum that you have already added for that segment so you have to remove those uh prefix some values because you know this segment will no longer be there so you cannot have these values in your map so in order to remove them this particular logic is implemented okay so what you will be doing is uh let me change color here so you will be having a pointer let's call this pre uh previous anchor and this is the current node that you will be at when you will see the repetition in prefix some value so this was the prefix some value which was one and it was uh seen previously so that's why uh you will stop here and till your previous anchors value reaches to your current node you will keep adding the prefix some uh so this was the prefix some 1 so you will keep adding the values of these node so it will 1 + 3 will be 4 then 1 + uh 4 + it will 1 + 3 will be 4 then 1 + uh 4 + it will 1 + 3 will be 4 then 1 + uh 4 + 2 will be 6 and then three and then uh comes the one so these values will be deleted okay so that is what we are doing here in this whole logic okay now once we are done with it we have to just you know make this next of this particular node to uh this node so somehow getting hold of the node just previous to the segment and making it to point the node just next to the segment so in order to delete that segment okay so this is we getting hold of node previous to the segment that is adding up to zero and making it to point to the node next to the segment okay so this is what we are doing here and then we will simply if uh so we will not again push the prefix uh some zero values so if let's say at a certain point prefix some value is zero so we will not be pushing it again and again instead of that uh if that is not the case then we will up update the prefix some value uh with the corresponding nodes value okay so we are was saying that okay uh this particular six value occurred at this particular node okay so this is prefix some value and it occurred at which node so address of this node there will be certain address of this node okay so this is just a reference of this node okay so this is what we are doing here and then we will simply return dumy head do next why dumy head do next because we are making dumy head to point to the Head okay so that is how we will be solving this particular problem and if you ask what will be the space and time complexities here uh you can very well observe that as far as time complexity is concerned we are doing a linear traversal of this list so time complexity will be order of n where N is a number of nodes okay and if you talk about what will be the space complexity since you are storing different values of prefix some at different instances so it will also be order of n because of use of hash map or the map you can say that we are using to get hold of those nodes okay so these will be the complexities if you are still having any doubts or any queries in general then you may ask them in the comment section thank you for watching have a great Daye
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
559
hey everyone welcome back and today we will be doing another lead code problem 559 maximum depth of an erratri an easy one given an anarch tree find its maximum depth the maximum depth is the number of nodes along the longest pass from root node down to the further as Leaf node the an array input serialization is represented in their level or traversal so this is just a level order traversal and yes it is a level of retroversal and each group of children is represented by the null values see the examples uh yes this is a level order traversal yes so what they want us to do is first of all we have given an array tree so this is not a binary tree whenever we have a binary tree uh node can have two children but this is an narratory which means the node can have more than two children in uh in that tree so we will be taking the example too because this is just more easy not easy but this by taking this we will be understanding things more easier so here you can see like a node can have uh four children more than four or whatever the case is but if it was a binary tree for example if there was not a four node like this four node was not here then this would have been a binary tree because there would have been two and no more than two nodes uh having the same children as having the same parent yes they have the same parent yes okay this is good now so what they want us to do is just return the maximum depth of an narratory we have already done the binary tree depth which was an easy one because we just go to the left go to the right check but is the maximum and just return it and that was easy but in this problem we have to do it on an array tree so here you can see the maximum depth is going to be one three seven eleven fourteen so this is how we can just see and tell things so what we can do is to solve this problem by two uh by two methods obviously like the breakfast search and the depth first search so the breadth first search will be just going level by level so each level we will have our level incremented so that's how the breadth first search was and breadth versus usually is applied when we want to go left to right so this is how we want to do things in our level ordered reversal like if you know how what a level or traversal is a just going level by level and appending the nodes in our input uh you know in our input in our list and now we can just use the breadth first search to find the maximum height what was it height or the depth maximum depth yes so that's it and otherwise if you do not want to do this by breakfast search is much easier though but if you do not want to do this by breath first search what we can do is just apply depth first search which is just going to the further us you can say Leaf node and coming back again and going down again and put coming back again and going down for example one will hit two and then three will go down to six and the maximum at that point is being updated so 1 2 3 7 11 14 this is how we can get the maximum and now we can go uh further but the maximum is not going to be updated but what we are doing is traversing to every node so it is a linear time solution and of n so that's it so let's get started first of all we will be doing the depth first search Let me just comment it down like okay so this is the depth first solution in ways so how do we use that first search we know that we make a stack append it to our stack if there is a route to begin with we will just append it to our stack dot append it without so a double will be having a root and alongside the level so the root have the level one so we'll be taking this example root has the level one and now what we'll be doing is taking the depth which will be our result and which we are going to return you can see while there is something in the stack we will say if there is something in the stack we just want to remove that Tuple uh basically pop that Tuple so how we are going to do this just stack dot pop and after popping it we can just put the node in node uh yes the node in node and the level in level and now what we will be doing is increasing our depth or checking our depth basically so the depth will be depth and alongside the level because level can be increased and now what we'll be doing is checking for every child in no dot children and yes I forgot to say this that in binary search we have a left and right node but in an array tree we have not in a binary search in a binary tree we have a left and right children but in the narratory we are we have just a children list so this is how we are going to do things like appending all of the children in uh in a tuple form obviously so children will have alongside level plus one because whenever we go to the child and child of a child we are going deeper and want to increase our level plus one at each step so what we'll be doing after that is just return the depth so this looks good let's see if this works or not this works and let's submit it okay so this was our breadth depth first search so in which we used our stack and did things with the stack so this is let me just copy it and that's it now we will be doing things with breadth first search so okay so how breakfast search works is just a level by level this was just using a stack appending going down to the very uh left you can say and then going down deeper and deeper in depth first search top to bottom approach and this is just uh depth first search is just right to left or level by level you can say a traversal so what we'll be doing is making our Q and if the root is valid then we will just append it to our queue so Q oh Dot append with again with a tuple alongside the level which will be one and now we will be making our depth so this part is the similar so then every node in every node alongside its level so every node alongside this level which is just a tuple n q what we want to do is just update our depth by the certain level and for every child of a node children what we want to do is um append it to our queue so Q q u q what was the spelling of Q okay so Q dot a band alongside the child itself and the level plus one and after doing that we can just return the depth and that's it let's see if this works and then I will explain how these two both algorithms are working step by step so this works and let's submit it so we are going through every list uh every node so this is an off and both are o of n so first we will be taking a look at the stack uh for stack I said the depth first search stack solution so uh first of all we'll be making a stack just for explanation this is just explanation the code is done and the depth we have a variable depth which will be equal to zero so we do have something in our root because we are passed down some root then what we will be doing is just appending it to our stack now we want to see if there is something in our stack here yeah there is something in our stack what we want to do is just pop that Tuple so this was a tuple I didn't use parenthesis just like these are in the forms like okay up there you can say so the Tuple has a node and the levels a node and its level so it is Bob it is pop now we can just update our maximum because we have a level one and now for every children of one we will append it to our stack so two has the level of 2 because the previous level was one and it is being incremented by one so two three by two four by two and five by two now we will pop from the stack and this is how uh pop in the stack works it removes the last element so 5 2 is removed and now we will append it with uh but before that we want to update our depth so depth is increased by again the maximum level was two depth is being increased and now for every child uh yes for every children we will add the children of five which are nine and ten and the level of five was two so the nine and ten will have the level three one increase like here level plus one so this is how things works so the level is three tenth level is three again looping again while the stack is not empty yes it is not empty popping this does not have a you can say uh a child node 10 does not have a child node so what you'll be doing is the depth will be increased by three and now what we'll be doing is again looping and again what we'll be doing is just popping the nine but and increasing our depth but the level was same ten and nine on the around the same range so the maximum will be the same and now appending with our 13 and 4 so the 13 is on the fourth level because the 9 is its parent and the parent level was three so the one increase and now we'd see that 13 does not have its own left or right not left or right a children basically so we will be just popping it and now we have four two we will just pop it so we have a node reference and a level and again appending eight by three and now again looping and because eight by three is are on the same level so 13 was yes I forgot to update my maximum in a hurry to just pop it but the depth has been increased when it was on 13 so 13 has the level four so at in a previous step like before air the depth was increased so now 8383 is popped and now we have 12 and 4 so it does not have a child node so we will be just popping it again now we are at uh three at level two so now what we'll be doing is just popping three and it's this double and we have a level we have a node we will be going down and just a pending and also the maximum is not going to be updated because it is um 4 is just the maximum the level is 2 so we are coming back you can say the like back tracking up so that's it and now what we'll be doing is just appending six with the levels three and seven with the level three popping seven and now we have a seven reference adding its child Eleven by four level four popping this because uh taking the Tuple and popping this now we have 14 with the level five because the children of that 11 was added appended in our stack and now the level has been increased by five now when we pop this we are going to uh you can say increment not increment but take the maximum to our depth so the depth is being increased by 5 as you can see here and now what we'll be doing like six three does not have its children so we'll be popping It 2 does not have its children we will be popping it maximum depth is not affected so the stack is empty we are done we will be uh just making out of the loop and returning the tab so this is how the depth first search work in this solution and this will be the BFS the breadth first search BFS okay so now what we will be doing just making a queue like just for explanation so this is our Q this is our depth and yes depth is 0 Q is empty there the root was valid root was not null we will be appending the root so the root was 1 and 1 as a tuple so these are Tuple I didn't just use the parenthesis for I don't know why I just I didn't like to use parenthesis here for just for explanation otherwise it will give an error if we actually use them in the code but uh let's get started now for the breakfast search appended to our queue now for every node in no for every Tuple into so the first Tuple in queue what we want to do is update our length with level so the level was one and now we want to up add its children so the two uh level is increased like this is just the same but with a q and a level by level approach so four two and five uh five two yes five two now this is done one we have Traverse now the queue is not empty the queue does have two so we will be appending the children of two does not have any children so two is just basically the node and two on the other hand is just basically the level so that's it and three uh if you see that three does have its left and uh basically children left and right yes you can say but I am trying to avoid the left and right because these are just used for binary tree and this is an energy so we'll be using a children word which is more you can say specific to narratory and six with the level of um what was the level three because it's its parent level was two so now what we'll be doing is seven by three yeah seven by three and now what we'll be doing is just checking the next node so four by two four and two so four heads it's eight by three and now what we'll be doing is just it's the turn of five so let's make a pointer so it can be more easier so let's say this is this C is our current pointer yes okay we are done here we are just going to our whole queue traversing through the whole queue so these are again I am saying these are in the pair of like tuples these are like uh let me just these are in the form of like this in the form of tuples so I just didn't make it I don't know why so now we are at eight three yes eight three now we are at five so now we will update our pointer to five which was already there so now we will add like nine with the level of 3 because it's the level of its parents was two and we added one to eight now the level becomes three again with ten and three ten does have uh 10 will be three like it is the you can say a brother of nine they are on the same level so it will have the same level now the pointer is being updated to 6 and now we have No Children of six nothing is being appended seven has an eleven so Eleven will be appended by 11 will be appended and the level is being increased again the pointer is increased again and now there is no pointer by the way this is just we are keeping track of things like 8 and 8 does have a 12 with again the level is being increased by one and now we are traversing to 9 and 9 does have a 13 so we'll be adding 13 to our q and this is a queue I yes we are using a queue I think I said stack many times while explaining this solution but this is a queue and now what we'll be doing is just going to the 10 does have no 10 does not have its own children so appending nothing and while we are doing all of this the length of the length which will be the second portion is being increased in case so far we have increased our length to 4 so the depth will be 4. so far and now what we'll be doing this was just going uh step by step so at first it was to then when we reached here like at the sixth portion at the six like when the pointer was here I just forgot to just do it simultaneously I was so focused on the Queue so it was like three and then it became at 11 it became four and now it is still not the max so we are at 11 I think we are at 11 yes we already Traverse that yes we are at 11 what we will be seeing is at 11 we have a children node which will be 14 with the level of 5 because it's parents level was 4 and now it is being the depth is being incremented uh because the depth is equal to the level and level is 5 and now the 12 has nothing in its you can say as a children 13 has nothing as a children 14 has nothing as a chair as a child or the level is still not going to beat the level we have already in our depth and this is how we are going to just return the depth because we already Traverse to the whole queue for every character for every Tuple in queue so this is will be going out of bounds and then we are done so that's it this is how you do depth search and breakfast search in an array tree and if you have any kind of questions you can ask them in the comments that's it
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
784
hello and welcome to devflix I hope you guys are doing great so today we are gonna see problem number 784 letter case permutation so let's get started given a string yes you can transform every letter individually to be a lowercase or uppercase to create another string written a list of all possible strings we could create written the output in any order so we have given a string an input string s equals to A1 B2 and so all are small letters and we have some couple of uh numeric characters one and two and we have the two alphabets A and B so we have to form combinations and written in an array uh where uh we have to form combinations using small and capital uh later so here in this combination if you see uh all our A and B are small and uh one and two are there in this they have used A1 B2 so B is capital and a small here A is capital and B is small and here both are capital and in this second example also there is only one alphabet for that uh one uh it will be small and when it will be uh Capital later so yeah so uh we can see uh how uh we are uh so we can uh solve these problems so uh let's uh head over to whiteboard and uh here we can see how to solve these problems so if you see uh there are two things happening here so first is uh we have to form the combinations and uh there are two possibilities for alphabets one uh so for suppose this a is there so for that we can take either uh capital A or small a right and for one and two there are only single possibility that we can directly take that number again for this B we can take either small or Capital so we can make use of this logic uh to solve this problem so we have A1 B2 A1 P2 and for a so we are considering a at this point a for a we have small a or capital a right we can take small a or capital A so we are at I equals to zero that is a right so we can take small a or capital A okay so let's uh increment I to 1 equals to 1. oh sorry I equals to 1 so for I equals to 1 what is the later at I equals to 1 it is 1 right so it will be a 1 or A1 only these two combinations are possible because one can neither be capitalized and we can't take the even small letter of one so it's a numeric character so for uh alphabets we have two possibilities and for numerics we have only one possibility right foreign go to the next character so we go to I equals to 2 right so for this uh so this is A1 B right B so for B again we have two possibilities and here also we have two possibilities so it is a one B it is a one capital B it is a 1 small B and it is a one okay capital B so for one for uh small B one per capital B right so you got the point right for characters we have two branches for numbers we have one branch correct so uh so we are not done yet uh because uh we have another character called two so we have our string is A1 B2 so we are at B so we have to solve for 2 again so for 2 again it's a numeric so we'll have only one branches right so it will be a one B two a one capital b 2 it is A1 small B2 and it will be A1 capital b 2 okay so uh we are done with the problem uh because uh if you see uh we have solved the combinations and uh at this point uh we have I equals to three which is less than the length of the input string right okay so this is our base case because here we have solved our problem correct so these are the combinations we want so we written we have to written this combinations in N result array okay so uh anyhow uh we have to store this uh single uh entries or single combinations into one temporary array and we have to push that into the this outer resultant array okay so that's how we have to do this okay so let's talk about the space and time complexities so if you see uh we for each character we have to uh possibilities okay so here we will have two here we will have four if we have another like uh we will have a bigger string then we will have eight combinations because we are just splitting out the branches so this is 2 4 8 so it shows that the time complexity will be 2 to the power n and for each character we have that tree right so for a we have this tree for B we have this tree correct ah so for small we have a this tree and for Capital we have this tree right so for each we have to do this so we have to multiply this combinations by using uh by uh the length of string that is end so it depends upon the length of string so suppose if we have another two characters here so we will have two more uh trees so that's because uh we have to multiply by n so this is time complexity for space complexity it is same for each uh character we have to uh we have uh like um we have to store the output to uh 2 to the power n times and for each character we have to create that tree so space complexity will again be uh 2 to the power uh n into n okay so let's head over to the uh code editor and we'll solve this problem Okay so here we have to return an array so we'll create a temporary result array which will be initially empty and we will return after this uh okay so uh this is a very common type of problem uh this is called whenever you have to solve trees like this so it will be mostly uh recursion and backtracking problem because we have to go and undo the changes and go into this tree so this is this will be a typical backtracking problem so just uh Master this pattern of problems and we will be able to solve a big a variety of problems in lead code okay so uh so we'll call this function so the function we haven't created it so we'll take one empty uh output array and uh the index initial index should be zero so because we are going to start from the very starting of that string input string that is s okay so we'll create that function backtrack okay the uh temporary uh out the temporary output array uh we'll call it as output and the index will be I okay and then what is the base case so whenever we are uh writing one uh any recursive function we have to first think about the base case so as uh we have seen the base case is when I is equal to the length of the input string okay so that will be the base case so if I is greater than equal to s dot length then we have to return from this function okay and uh the next operation we have to do is we have to push the temporary output into the resultant array but uh as you can see in the sample result they have seen they have given uh we have to uh show the output in the form of string n naught and array but the output we have is an array so to convert uh an array into a string we have the join method so we can do that and this is yeah so we are done with this okay so uh there are two cases uh if you carefully see this tree so if we have the character if you have the character we have two possibilities one is one for small and one for that is for one for lower case later and one for uppercase letter but if we have any numeric character that is one or two we only we have only one branch right because we cannot transform it into lower case or uppercase so we have to handle this case in code so I will have another if condition and uh one else block so in if uh we'll try to check uh if the character is numeric or not so we have is integer method and we'll test this character so let's grab that character into care s of I okay but the character will be string so I'll convert it into number because uh is integer method uh will work on that number okay and here we have to do some operations for lower case we have to solve the tree so for that we'll transform the output dot push and what you have to push we have to push the character in lower case as we have seen in the tree okay so this is the lower case and we have to solve the tree using a backtracking recursive call uh will pass this output and we have to go to next character so for that uh we'll pass index plus 1 and will pop out of that uh will pop that uh added character from this list so why we have to do this I'll tell you in just a minute yeah okay so why we added the lowercase character and then backtracked and then popped it out so there is a reason behind this so suppose uh you have added this B okay this B you have added this B so once you have added this P you have to go to a combination where you have to be uh you have capital B right this capital B so if you don't uh remove this uh small B and the next uh recursive call the output will be this but this is not the correct case right so for that we have to add small B and then while going back to this Branch you have to pop this out and you have to remove the small B and add again capital B and for going to uh next Branch you have to pop this small capital B and you have to add the next character so that's how uh we have to do for that we have popped it out after pushing and backtracking and uh so now we have to handle the uppercase upper case uh condition in the same fashion so I will I'll just copy this code because it is very similar uh except this method so we have to use two uppercase here okay and rest of the things will be same and so this will be for a correct on a non-numeric character for a correct on a non-numeric character for a correct on a non-numeric character for numeric character we don't have to uh do uppercase or lower case because we can't do this uh with any correct numeric character okay so output dot push care and then we backtracked and we popped out the result okay so this will be uh for numeric case correct okay and this will be for alphabets okay so I think we are uh done with this uh problem so let's test this okay so uh all the cases are formed uh and they are passed so let's submit this result yeah so uh our solution is accepted uh and it uh beats uh like 77 uh yeah of the solutions so yeah I think that's it for this problem and if you find any difficulty in this you can comment it out and make sure you subscribe to udaflex thank you
Letter Case Permutation
insert-into-a-binary-search-tree
Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string. Return _a list of all possible strings we could create_. Return the output in **any order**. **Example 1:** **Input:** s = "a1b2 " **Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\] **Example 2:** **Input:** s = "3z4 " **Output:** \[ "3z4 ", "3Z4 "\] **Constraints:** * `1 <= s.length <= 12` * `s` consists of lowercase English letters, uppercase English letters, and digits.
null
Tree,Binary Search Tree,Binary Tree
Medium
783
72
given two strings word one and word two return the minimum number of operations required to convert word one to word two you have the following three options permitted on a word insert a character deletes a character and replace a character so our objective is to get from word one to word two with some number of operations for example uh we have horse and we want to turn it into this word Ros so the first step is to replace H with r second step we're getting closer to delete this middle word middle letter and get the rows and the last step is to delete in the final letter we get to the destination and our operations are insert into word one replace a character in word one and delete character from word one and we count our objective is to find the number of apps to get from word one two word two so the second example uh intention to execution we would need to take five steps including several places a removal and an insertion and let's introduce something called us let's consider the suffixes of each word so word one word two it can be different lengths it's okay and the suffix uh this is a suffix and it's if you know python it's word one that uh colon Something Like This and we have another suffix and let's define a function l i j l is for the inventor of this algorithm and uh it's this is the edit distance between the suffix word one I were to J we can actually do it with prefixes and that actually might be the more common way but with the suffixes I think the in this indexing is easier so I'll do I'll demonstrate the suffix method for this algorithm uh it's a should be uh introduced in CS courses in school so you know this is more uh I guess a standard implementation I suppose so let's redraw those figures I J consider so what is the value of r l i j our objective is actually to find L 0 that's the edit distance of the suffix the whole string you know so if word one I is equal to word to J we actually don't need to we if these two are equal we can just consider the rest of the strings what's the edit distance for those and that's the edit distance so let's say l i plus one J plus one and if they are not equal else we need to make an edit so we plus one we do it we must use an operation and we can draw terrible pictures uh J well our first option is we can delete and the character uh loop from word one so we can delete this character and just match the rest of the string I starting at I plus one with j uh Delete let's say and this would be l i plus one J we can also insert in which case um we would let's say set we inserted the character here to satisfy this J this is satisfied so we can just consider the rest of the string here as well as you know the original eye it's more of an inclusive thing but you can we can do uh J plus one we inserted the character in word one to satisfy uh word twos J and we can also replace in which case we spent this operation we're doing the operation in any case so we just replace these that's an operation and now we can just consider the rest of the string now same in the above case so it's l I plus 1 J plus one so the recursion looks something like this or the recurrence relation let's say is l i plus 1 J plus LED if the characters at the indices are equal else it's we need to do an operation plus one and since we're trying to find the minimum number of operations we find the minimum of delete uh let's do uh replace and insert and this would be Arrow I plus 1 J l i plus 1 G plus one and l i j plus one and you know part of the difficulty is also considering the base cases so if we were hap we were to have a table of l i j this would be a 2d Matrix 2D Vector let's say and we would have something like this and let's say I'm gonna have something like this let's say word one was horse and were two here and we also for the base cases we can consider the empty string so you know if the indices are out of bounds like at the end of the word we're going to consider the empty string and fill out that to calculate so we can consider what means something to us so here's the base cases and let's consider uh let's say uh word one is length L1 where two is length L2 and what's the edit distance to get from let's say the empty string uh in the word two to get to the empty string from horse so horse to empty string and this would be um so we would need to spend for the whole suffix we would need to delete five characters or out or uh for the for this suffix we need to delete four characters three two one so uh let's say I yes that's the variable we used is equal to let's see well it's equal to L1 minus i l one L1 is 5. which is a zero five this is the added distance to get from the suffix or the whole word and the suffixes to empty string and let's also do the same thing for this dimension for the other the final base cases so the base case is to get uh well from zero to r o s and the edit distance well we're starting out with uh well the law suffix let's say is L1 and the variables J and we would need to insert three letters here or to get to s Ros to get to this suffix the entire word so three to one so we would have something like L2 minus J so with that we can iterate backwards through the Matrix applying these rules and uh and our result would be L 0 which is just comparing the whole words the edit distance and yes so let's jump into the code so let's waste no time get into the actual code call my function l i j suffix is the edit distance of the suffix of word one looking at I the suffix of 2 starting at J and recall that if one I to J and we can just consider the rest of the word equal to plus one else it's equal to one plus the minimum of well we can do three operations insert delete replace this would be what's the minimum of well it is in search well we would insert something to satisfy the J requirements so i j plus one delete uh and replace and the base case base cases well let's say we want to transform the null spring into uh where twos suffixes and let's say a little length of uh word one M length to add let's save uh oh what's it uh so we start from the no string and the null suffixes corresponds to the final uh index the character after the final index which is actually the left so l m j is equal to well we would need to yeah this is just a length of the suffix which is and transform suffixes into the null and again this is also uh just a length of the suffix so with that we can just dive into the code l get the length first and since we have in index we need to have space for the null string which is the final Index this index so an imaginary index let's say but will be to add extra space for that extra row let's say correspondingly an extra column plus one its default initializes zero so just leave it like that and the base cases or if J equals zero J less than n okay plus L edit distance between the edit distance is and correspondingly m Plus equals let's see just a length of the suffix that we need to uh we need to transform from or to you know in the other case now the base cases so working back through the stream we need to calculate the later indices first the smaller suffixes or the later indices so we'll iterate from the back um let's say M plus one squared equal to zero foreign in which case and we can just take the added distance of the rest of the string in other in the other case we would either need to do a deletion which would be a line plus one J because we get rid of character at index I just compared to you know the same suffix in the other string correspondingly we do a uh insertion and replacement this time doesn't come for free like in the uh and in the if statement foreign in the end we just wrote the return the result for the whole string let's see if it works it looks like it does seed for the other one intention it's how to turn the intention into execution and it looks like you know maybe we can maybe it's a work properly I've done it before so hope I didn't up uh okay speed and so now uh I guess for extra credits you know some if you got asked this question you are able to somehow implement it from scratch somehow recall how to implement it since it's usually I don't really know of anyone who can really come up with such things you know from scratch except you know that scientists who did it a long time ago as a PhD dissertation perhaps uh they might ask you they since you implemented this they may ask you to actually print the steps of how to get from word one to word two so let's just do that right now and basically we'll just we since we have the Matrix uh will be since we have the Matrix of the edit distances and let we have like the optimal choices to make at each step so let's say we have the cells here and whichever one is the maximum or the minimum corresponds to which decision we need to take so this one would be I plus 1 J would be delete so if this one were the minimum we would need we would print out Delete and we would have let's say let's have two pointers iterating through the Matrix let's say let's have uh I guess score one equal to zero or two zero and while her one is less than M and two less than n well the first case is if they are equal corresponding to this one the indices are equal let's do word one two then we just want to increment the two we don't have to do any steps so we don't have to print anything to plus let's do the other case thank you the steps are let's just copy paste this and replace uh probably should maybe I should just use should have just used the same iteration variables but you know that really doesn't matter to and let's do thank you let's do the choice we've corresponds to the minimum of these so we would want to take the minimum which one has a minimum edit distance let's replace and if choice is equal to well choice is equal to delete we would want to delete character index at uh we would want to delete the character delete Cur the uh character one in world one so let's use this print function delete uh maybe this one is a better choice delete air character uh let's see word one add index number one and also want to increment per one to continue iterating through the possible uh to decision paths let's say else the choice is equal to insert care word one or we would want to insert the character from where two in order to turn it toward two and index number one look at it also add a line break here and move appropriately through the Matrix and else it's a replace here word one with here we're to add index foreign follow the appropriate decision path and at the end actually we actually might have to such as this case we might actually have to delete characters from the end or insert characters at the end so one of these is you know not zero and one of these is zeros a while or one is less than n then we need to delete characters there's excess characters so uh let's say delete care word one from the end of the word and similarly we may need to insert there may be extra characters in the other word say well her2 is less than n and we can do something similar insert and we would need to get uh air power two at the end of the word 32 plus let's do it run it for intention execution and we get a series of steps here um if you follow them you will actually get execution but I will do that here and I actually will submit it here since the login to the console will just you know slow it down and already submitted it before so I hope to somehow helped you and have a good night foreign
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
987
hey everybody this is larry this is day seven of the august leeco daily challenge uh hit the like button hit the subscribe button and join me on discord and let's get started in today's forum vertical order traversal of a binary tree given a binary tree we turn the vertical order towards of his node value okay so three and 15 is that uh i'll drain 15 at the same level okay how do i want to do this um there's a couple of ways to do i mean they're all going to be recursion in some way i mean i guess you could do things on the queue as well but yeah i think actually maybe i would do that i think generally i would just do it with a recursion like it was a contest just because it's really quick you have a list of you know look up values or something like that uh and then that's it um and here i'm to do the same thing but with a q yeah so 5 comes first because 5 is smaller oh wait let's see the two notes have the same position and the value of the notice we that is reported versus the right that is smaller okay so maybe i do have to think about because that is a little bit of an edge case um but yeah but i think conceptually this is not that hard um but there may be some edge cases that i have to think about and they even tell you really how to go about it the only thing tricky is about uh the same position place which is here five and six what is a good way to do that i mean so there are a couple of ways that i'm thinking about now uh one of them is just going through the thing and then sort later and then the other one um but the thing that i was trying to think about is just trying to do it live which i mean i guess you could do it like a multi-set like a tree set type thing multi-set like a tree set type thing multi-set like a tree set type thing depending on your language um or tree map or tree multi set maybe um but i think all that is just uh will give you a better complexity but i'm just going to do a lot of sorting i think that's uh where my head's at and with that um maybe i won't do it with the queue i would just do it i think i'm just gonna do that for search generate all the coordinates sort and then bucket them together i think that makes it straight more straightforward to just get it right so yeah so now let's just do uh let's just do i guess in order for so it doesn't really matter as long as it's recursive and then we have a list of oops and then we have to buy some stuff okay so yeah so if note is none return uh and we actually wanted to keep an x y value otherwise and so that append x y uh node well it's by height so we or by column so we actually want to do y first oh wait which one is x which one's why well we don't have to use their definition in any case um so we'll yeah we'll keep track of it this way uh and then the on the left node we want to do also this is not in order anymore i just do pre-order let's call it i just do pre-order let's call it i just do pre-order let's call it pre-order uh node.left uh node.left uh node.left and then was it x minus one y plus one uh preorder note that y x plus one y plus one right uh why is this going why does this go down i don't know why they do it that way but this notation is a little bit weird uh but maybe not um yeah and then now we just have to buck it by so now we want to sort how do we sort it right um well first of all we could just do a sword and then now we want to do we want to and we don't even have to do it this way per se yeah i mean there are a lot of ways to do it that's why i'm thinking about which way is the easiest to explain but i'll just have a look up table uh so yeah so we'll just have a hash table um and now for car which is x y uh node and hash in answer what do we do well we do something like this that append uh no right and the node so that's the height because we want to go from top to bottom i believe right yeah from top to bottom so that's how we'll do it and then here we'll just yeah and usually i would use a default list but i just want it to be a little bit clear in hash table let's do x as you go to a list and now we can just well for x in hash table dot keys we sort it let's sort um actually maybe here we want to actually um do the value instead of the node because that's okay uh we sort um so that would give us the smaller y first and then type break by the value when they have the same and then now we just have to put it back to uh to the return results i guess i could actually just do it here so we sorted and then now for yeah table x um so we have the y column and then the value for oh we just do the right and then we append a list version of this and i think this should be okay maybe hopefully we'll see well yeah i just i think logistically this is okay this is just um should be straightforward but of course i didn't call the pre-order at all that's pre-order at all that's pre-order at all that's why so we want to pre-order uh why so we want to pre-order uh why so we want to pre-order uh zero we always forget that but it's easy to fix uh okay so this seems mostly way i mean the things are happening in the same place but they're obviously not sorted correctly um i misunderstood it i think i misunderstood some it's part of this problem to be honest uh no we go four so why is that this should be on x is equal to zero um maybe the keys are not sorted so let's okay so yeah just the keys will not sort it so now let's try an empty array just because of one item minimal test cases there would that would probably do someone performance but it should be okay uh looks good that submit yeah i wonder if there's a live version of this uh but for the most part um it should be okay i think this only has can you prove that this only has two keys because the one is coming from the left and the other one's coming from the right or does it i don't know actually but in either case uh so the pre-processing step is gonna be linear pre-processing step is gonna be linear pre-processing step is gonna be linear and linear space um and for n is equal to a thousand that's way more than uh better than enough uh the only thing that's a little bit uncertain is the sorting and at the worst case it's just gonna be certain entire things so just really n log n so you could probably do some tighter bound if you do the math but yeah uh a little bit annoying but uh seems okay it just depends on how you want to do it so let me know how you did it uh let me know what you think uh hit the like button hit subscribe and i'll see you tomorrow bye
Vertical Order Traversal of a Binary Tree
reveal-cards-in-increasing-order
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Array,Queue,Sorting,Simulation
Medium
null
1,027
Hai gas welcome you me youtube video today we are going to daily need per challenge and today problem name is this longest arithmetic sub statement so d problem statement of integers return d length of d longest arithmetic sub sequence in lamps what have we been told question is and we Longest alphabetical sequence you have to return what is the distance of elements which date should be from but which de configured players of elements you know what is it is nothing it is date can be driven from original think some Of D elements Okay, now we talk about the first piece, so see 9 - Again three So now see the difference of the consecutive air of elements is from that and its species in itself, this is the health answer, on this we have the maximum length written. Have to do 10 - 3 Sorry, I can make some maximum element, so there is only one element and the maximum length of arithmetic request in it will also be the same. Okay, next of no, I have till this index, what is 20 - 19. Yes it is ok - if it is 19 what is 20 - 19. Yes it is ok - if it is 19 what is 20 - 19. Yes it is ok - if it is 19 then it will say what is the maximum you can return with an absolute arithmetic difference of -19 say what is the maximum you can return with an absolute arithmetic difference of -19 then 20 will say anything can actually be done 15 - 14 is ok then it will ask what is the maximum arithmetic request you can return then it is Maximum 1 + 1 2 will become 15 - 20 - 5 - I will return, ok - 12 is the difference, that is minus 12, so what is the maximum length arrangement that the substitute can make? He said, I can make the band's one, seriously. If he sits then 1 + 2 will seriously. If he sits then 1 + 2 will seriously. If he sits then 1 + 2 will only ask versus three minus one if you have length, you are looking for stability. 3 - 2 then 2 in length, the inspector will go to maximum -5, this is 15 and do a little fox in it. go to maximum -5, this is 15 and do a little fox in it. go to maximum -5, this is 15 and do a little fox in it. You are important if I have. Beyond 50, he will ask, if there is a difference in the apps itself, if it is -5, then how much is the difference in the apps itself, if it is -5, then how much is the difference in the apps itself, if it is -5, then how much is the longest net you can make. Is it returning? Tell me, okay, you guys can make 2 and if I also get added to it, then my Pass tu late ho jaayegi tu plus one three ho jaayegi oneplus one bill b tu will similarly return 21 on 20 - 10 - 10 one plus one will similarly return 21 on 20 - 10 - 10 one plus one will similarly return 21 on 20 - 10 - 10 one plus one bill b tu after longest subscribers banna ho mein kar karta hoon 3 + 1 bill b 5 - 3 / 2 hai to tu mein if I have the request then 2 + 1 bill b three you request then 2 + 1 bill b three you request then 2 + 1 bill b three you can also side one three and five is d subsidy having d arithmetics displacement tu after that if you ask 15 then 15 5 - 15 - 10 after that if you ask 15 then 15 5 - 15 - 10 after that if you ask 15 then 15 5 - 15 - 10 15 - 10 will be made so one pay I add 15 - 10 will be made so one pay I add 15 - 10 will be made so one pay I add then they get the bill you will similarly ask one so 5 - 4 so 4p how much will I get, ask one so 5 - 4 so 4p how much will I get, ask one so 5 - 4 so 4p how much will I get, what will I get even for 20 in which one will be returning I will add So, the 15 on the bill gate - I will add So, the 15 on the bill gate - I will add So, the 15 on the bill gate - 15 is making one, so I will print 8 in it, here I am getting 15 10, this is what is happening, now see, I had this element to try the formula and all these are my I am setting it late, any one is a jet element, this is what it means, take it from zero, I have to return it, what is the power, the complete logic has come to me, this is the state of DP, which you can give it. Have to do it but there is an issue here, if you see postpaid, for the value of Namas, the date is from zero to five hundred, now Adam is doing it, the terms have come, that was zero with me and this is 500 with me since late, so that. R getting zero minus five hundred S - 500 and whatever is -500 is hundred S - 500 and whatever is -500 is hundred S - 500 and whatever is -500 is not a valid index. In IPL I have 500, if caste is there and if GP is caste then 500 -0 bill get 500 is the argument. Second index which I have is of BP state. Its value is mine 500 tu plus 500 is very tax power but mine can't do five hundred so just make it a valid index what do I add 500 on both side so now I will get valid index what will I get? -500 plus 500 will be given, now the range will -500 plus 500 will be given, now the range will -500 plus 500 will be given, now the range will be zero to thousand and this is a valid range with me, this is one meaning but cannot do negative value, now I will have a new DP, see the valid index plus 500 in one. I am doing it inside, okay it will be zero, I will strengthen these, from here I will start expanding the DP space, but basically what will happen is that I will band all the volumes of zero that I have, okay and ideally I mean whatever I have here. Those who have not got this, I can also make them one by default. Sir, your observation is enough, I think no way, the called parameter will be in the range of ₹ 1000. For zero, I have all the values ​​one. Where does it For zero, I have all the values ​​one. Where does it start and it should be less than I so I - I gave ₹ 5 to make zero five mines, what will happen, we know DP of K com the plus one, this is done, we have discussed what is DP But let's take its value already maximum already its information so this is a simple word on this particular day after tomorrow if you like tutorial and please subscribe to my YouTube channel like this video and if you have any other query and recommendation please date me on this Dr in D Comments Action Thank You
Longest Arithmetic Subsequence
sum-of-even-numbers-after-queries
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`). **Example 1:** **Input:** nums = \[3,6,9,12\] **Output:** 4 **Explanation: ** The whole array is an arithmetic sequence with steps of length = 3. **Example 2:** **Input:** nums = \[9,4,7,2,10\] **Output:** 3 **Explanation: ** The longest arithmetic subsequence is \[4,7,10\]. **Example 3:** **Input:** nums = \[20,1,15,3,10,5,8\] **Output:** 4 **Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\]. **Constraints:** * `2 <= nums.length <= 1000` * `0 <= nums[i] <= 500`
null
Array,Simulation
Medium
null
337
Ajay Ko Hello friends calling on dynasty sites and in today's video we will solve a problem named House Robin Thicke so first let us understand this problem and then we will see how to normalize it. Okay now so I have an example. Point becomes this, now see a proper is happening, I have a thief who is fine, what is he doing to him, no one point, the structure of the houses like this, means that a house is here, this house is here, and this house is this house. With other and adjacent hole houses and there is one he who has one he has one on his fasting Hansait his reason is 5 so I call it like this there is only one berth 01 his filling $5 wants to be made again one berth 01 his filling $5 wants to be made again one berth 01 his filling $5 wants to be made again so one is his thing There will be a to-do so one is his thing There will be a to-do so one is his thing There will be a to-do logic, it is toilet even with his intelligence, then he can put 51912 below it, then do it like this, inside the house there is an effective from, there is the President, now it is okay, he has to do it, he has to steal, but he has to do this show, why the maximum amount? He is not able to steal in one go, he does maximum heroism and if he goes to do this then what will be seen, now the constraint in front of him is that if we assume that he has switched on the phone inside this house, then he does more after coming to this house. These are connected only to each other, so he will not be able to commit robbery here because if he commits robbery here and goes to do whatever he wants here, then this person will call the police within that time and he will also be caught doing the same here. What will happen if he is caught, that if he works in this house, then it is not allowed to be sick in this house, you can do it in this house, there is no light in this house, it is okay, so it means that if If there is theft on a note then I cannot leave it at these three places. Stealing is not allowed here, I cannot do it here and there, I cannot do it here only, sir also I cannot do it here, if only you people do it. There is no allowance to be made even on these devices, that is, it is connected, only we cannot do that inside it. Basically, now let us see how its maximum is generated. If you want to set the maximum, then you can come to the biggest house. You will get married, secondly you will steal here, then what will you do, after this you cannot leave it because I stole Indore hospital, so it is not allowed here, so you will not be able to do it here, but here you can steal, right? Inside the one, if you steal here, then you cannot steal on two and on them, now then I have stolen the file and have stolen in and now it looks like I steal above the level of alternator auditor here. Spent money till seeing that you did not steal here, did not steal on the plans but stole to laugh at the loved one, then inside level-2 there was then inside level-2 there was then inside level-2 there was no theft on both the plates, quite level limited 3 hours, went to this and stole but it is not old. The concept of end applied is not correct, if we assume that the tree is there, if this cream was not like this, then if I change this trick slightly and make it such that the end here would be nineteen instead of airtel, then you would have used it. They steal here, wherever they steal, I will kill them with my own hands, here they will steal at this place, I cannot steal from this, but I will not steal on the file, if I steal on the file then I won't be able to do it in these and will have to come and stay somewhere else, so not five plus one, I can do Total in Noida and On, but if I don't steal the office and invest, then I am more relaxed, so I will steal here, not on the team. So now look, if the Alternate Level Officer goes wrong here, then which Audit Lulva goes here to the Dalits, apart from this, there is a way to adjust the letters and inside which also if we travel and see, then I make a bundle until I find such a way. Maybe this letter is the elixir of history, where would I like to steal, I would like to operate it here, if I open it here, there is no light at home, we are texting wherever the patient is I will kill and come back here that if I commit robbery at these two places then I will lose them. Don't know the huge amount, what will I do, I would like to do rotary at this place, this will also have to be paid for. If I leave these things, then I left these things together. Now let's look at this example, if I click here, I can't do it here. I click here, I ca n't do it here. I left these things together. If you leave all three then here you have the option that now you cannot say here that I have reached the maximum amount because I would like to go and repeat that wherever you get the maximum, do it there also, it would be wrong to say this because This may be a trick, if a lot of notes and small value adapters are sold in a big rally, this is also possible, then on whose basis should we decide, where to employ Ruby and where not to employ, it is very simple to do. For you, we will do the included technical goods, so that I live here two things like I have Pimpri, accept this thing, here is a note, loot, here is some egg cloth and this collect child has and who has his own all this time Kshatriya could have adopted his journey near him, could have adopted him near him, this is something like this Sir brother, I again sacrificed on the element also, do n't give me belly button, if I steal from you then what is the maximum amount I can generate if I too Okay, and if I did n't steal on you, if I did n't commit robbery over there, what was the maximum volume I could mute? So how much is the rebellion grease staged? Here's two. The valley will be big, I will have to get two wellingtons, one with robbery, what is the maximum amount I have generated and the second rally is without robbery, how much is the maximum amount I have generated, so I did not decide to steal here, I said, so what to do now, I do n't even steal anything. Let's leave it for you, so if I leave it for now then how much maximum can I generate and if I steal at all then how much maximum can I generate Same for See I did the same thing here too That if I commit robbery on C, then how much maximum will be generated? If I don't, then how much maximum option will be generated? It is up to A, Abe, why what is the answer, now it is decided that if I commit robbery on A, I will get a Muslim. This is on A. If you don't want to steal, you will get the message, how will it be decided now, if in case I want to steal on one U, then I am calling it left or this recipe left side, so I give some name to these two values, this is P and this is Because I take it, this is my peer, why is this mine, okay, now look, here comes the paper, now here comes one, I have to rob here, now I want to rob one of you, so how can I do it, so with robbery on loot image Dot rebellion means then do it as much as Greece, why but if you want to use it then how will you be able to do it now, if you want to do it on you too then you will not have to work on more seats, meaning you will get that value from Vivo C, BOC inside it. Proper grease must not have been done, meaning the thief had not stolen the BDO CO. What was the maximum amount he had generated at that time? You will order it from Baiju, know that I will say here why left in palace, right don't in cube plus, root dot data is here. If I want to do a job on one level, then I can set this maximum and if I want to do without robbery then I am saying that I do not want to do robbery here, I refuse to do it here also, then how many messengers can I give on top of one? Did the trick, if you refused to do it even on one U, are you not doing the necessary paper, then what would you have to see, max m1 inside B and C, in which they were removed, on doing the above ruby, the message was getting net, this is not whatever. It was bound to happen when it was reached and if the lesson was learned then Laxman ji had broken it and if not then half of it was broken. So what will I do here? I will get the max here. Who got the Magsaysay Award for robbing on the left? This is robbing on the loop. Maximize what you don't want to do. Here in A Plus, whatever money you earned, on the right side in Plus, how much money is less than yours, because these two are related to each other, it is okay, but I have not stolen, even then do not take it among yourself. -No, there is even then do not take it among yourself. -No, there is even then do not take it among yourself. -No, there is no point with BBC, so how much maximum can I generate in the week above the daily B on the beaches, that is, how much maximum can I generate by stealing and without stealing and matching it with it, that I can earn right off the back above? I can generate and if I do n't do the story, what is the maximum I can generate? The Constitution of these two is not created but the President is on. Now among these two, the one who will get the maximum result in the Yudh Brigade Rally in Indore will be my answer, so how do I know about the whole. You will feel how much maximum can be generated for this, stomach, look once again what I said about my left and right side, left right or tell me one thing that I steal on you, how much maximum can I set, stone up. If I don't steal then how much wo n't be given to me? Team said to my light guy, friend, you tell me, if I steal on you then how much maximum will I get, if I do n't steal then how much will the mixer get. Return some information between these two and decide the curry leaves. What Nano Pimples Whatever I wanted to do, I want to steal on this house, it means if I want to steal on 1 house, then I will not have to steal on the house and the marginal one, then without robbery, what is the maximum generated plus for both of them? How much tax do I have to pay and I want to do a house number in Airtel only in theft, then what will I say, how much tax was levied on you for doing ruby ​​or not say, how much tax was levied on you for doing ruby ​​or not say, how much tax was levied on you for doing ruby ​​or not and in between you have the option of doing patient or not. If you don't do it then return me the value of how much maximum was set and then I will decide about the total of maximum and how much was generated within the entire penis so that I too do not rob myself of injuries. Well, now this is the same thing here. Let's see, all the trailers of the house inside this tree have been painted. What is going on, then we will also get affected by the dry color. First of all, I will do triple riding on it. Now see, from here it is 2 billion, if you use the C pipe. Above the subjective, if I do n't mature at all, what will be the maximum amount, then above them, if you have written the first here with job and the second one will be without, okay, then there is one above, if I or Neetu, if I steal. I am the maximum you will get, you will not be broke, I don't steal from you, nothing will be charged from you, please inform 500 rupees here, put ₹500 rupees here, put ₹500 rupees here, put ₹500 minimum, talk to 25 Dher Shades here, $11 and zero develop, Shiv's money goes here, $11 and zero develop, Shiv's money goes here, $11 and zero develop, Shiv's money goes to me. There are two ways, I can either get the same done, then if I do that only at this house at that time, then what is the maximum amount that I can get only from here only because if you do Ruby at house number 6 So you won't be able to do it even on high flame, they don't do it even on high flame, what is the maximum that can be achieved, then I would say that we are not doing Ruby on this number 66, so you see whether you can do Ruby on house number 55 with or without Robbery. How much maximum were the planets generating, then 520 were in Kama What will you do, if you have a choice on intake, then it is whether you want to do robbery on intake or not. August had said that don't rob me, do this, my accused, do it first. If he had not committed robbery on me, then he had maximized a little Jio phone and secured it. If he had not committed robbery, the messenger had broken sixteen and how much did the Muslim toe assembly total become for doing oil on me, and he forgets 2030. So if I If I do the same near this, then I have generated maximum, can you TP? Now, if I do not do robbery on the seventh house, how many Muslims will be found here, then he is the mechanic of zero in the place of maximum extend. Generate ATM in 68th, i.e. extend. Generate ATM in 68th, i.e. extend. Generate ATM in 68th, i.e. robbery on the seventh house. I have to do fiber, I see, there is only benefit in doing Ruby, where else is the audio? Wife is eleven and there is audio jack at seven place, so five plus 11:00, audio jack at seven place, so five plus 11:00, audio jack at seven place, so five plus 11:00, how much difference is there between 6 and 7 2013 in these 3 hours. Now I will move ahead ah. Kuselan went and why will you do it, how much benefit is there in doing that, if you do the same then you will do four, if not then you will do 080. Let's see the advantage or disadvantage in doing it. If I click on add new, I will get this much, it is swift and if I do not rob on the add. If I am there, how much support will I get, because after the light, there is nothing, now I have come to the type, you are deciding your life in this way, Asaf was, how much will be the benefit if you put ruby ​​on it, applying it on the face how much will be the benefit if you put ruby ​​on it, applying it on the face how much will be the benefit if you put ruby ​​on it, applying it on the face means that you have used the right one. But do not want robbery. Benefits of A+ 4 Pimple to 9. want robbery. Benefits of A+ 4 Pimple to 9. want robbery. Benefits of A+ 4 Pimple to 9. And if I do not do robbery on the side, then it means that you must have passed more than 8:00 then it means that you must have passed more than 8:00 then it means that you must have passed more than 8:00 or if you had not done it then how much maximum would have been got then 19 collection, how much is the fit. So that means it means that you were trapped in robbing here, now it is on you, now you decide for yourself whether he is going to get any profit or not, so you see how much benefit I will get if I do robbing on myself. So using means you have not logged in to this website. If you do not do it means you will not pay 10 rupees, then I will get respect at Indore. If you do Agri, you will get two dollars and if you do not do 503, then you will get a Bluetooth in Arts College. Turn and templar's pet is returning from here so intimate now next if I don't do tu ke vyapar then how much maximum do I get, the meaning of not doing is Kunti 318's in Maths Plus I am not in Maths of Nok Might Pimple 223 Plus A Ripple 232 So let us generate the total amount here thirty-two i.e. the thirty-two i.e. the thirty-two i.e. the benefit of dividing all these cords which we have spaced is our answer. Now let's try vitamin for this once and here I can say this. I am sure that on the suspicion of such theft, someone will come to the difference, it will work exactly as it was before, but after frying with the phone, let's see, 14 wala babu, on doing the survey, you get chart work on all four, hero deluxe of not doing it. Even if you prevent naughty accidents, you get 90 because if you will never be able to do so, then the cost is done and if you do not commit robbery on the nighty ones, how much will you get? Max off and forced to make benefits of five. Why would you do five? What is the meaning of doing? That if you do roli on the face, you will not be able to do it even on nineteen, then how much tax award was you getting for not doing patient in nighty, if you do not do robi on physical 2945, then you will like to do ruby ​​on nighty and maximum of 9828, let's then you will like to do ruby ​​on nighty and maximum of 9828, let's then you will like to do ruby ​​on nighty and maximum of 9828, let's see whether you will like it or not. If I click on duty, there was no restriction on intake, that too, I made a mixed amount of Paytm of ₹ 2 and there is made a mixed amount of Paytm of ₹ 2 and there is made a mixed amount of Paytm of ₹ 2 and there is no Herobrine on the face, because if you don't do it, how much salary does he get, the job and you, it goes to your husband. By the way, Ankita Samet here, if you click on continue, then you do not commit robbery on two because you are a Muslim, you are Tehri and the team has max, that is, if you have got 80 free A+ in ninth maths, you have got 80 free A+ in ninth maths, you have got 80 free A+ in ninth maths, then it will be 1962. Your photo, how much maximum are you getting, if you don't even stop here, make it positive, that is where you must have stolen pipeline 1749, then add it on Infosys, even if you get the maximum, then you will get everything inside it. It has to be said that here you can steal, you can't do it, if you do then how much maximum will you get, if you don't do then how much will be the Muslim-free fort, you have to do it yourself, hence, Muslim-free fort, you have to do it yourself, hence, Muslim-free fort, you have to do it yourself, hence, test teenagers on the internet, this will tell us how this idol of Idols is going to work. Childhood is removed, this thing is not send me, main phase is kept, it keeps these and look here, if you steal the curly beauty, you will get it emphasized here too, 600, now there is benefit on robbing the pan part. It will happen if we use tempered glass ruby, then friends, when we come, if we don't do it, then how much will it be useful? Max is more than Rs 100, if you pay Rs 10,000 for this, Rs 10,000 if you don't pay Rs 10,000 for Rs 10, if you do 10,000 for this, Rs 10,000 if you don't pay Rs 10,000 for Rs 10, if you do n't pay Rs 10,000 for this, and sandals, now this one is the n't pay Rs 10,000 for this, and sandals, now this one is the n't pay Rs 10,000 for this, and sandals, now this one is the second one. The chemical is on the side, whatever should be done, if I rob this one, then how much will I earn, but if this one is on my side, then it is on me, I will have celebrations, I will not have to do the accidents of these two times, then anti-Islam in 10 plus. If you don't have to do it then anti-Islam in 10 plus. If you don't have to do it then anti-Islam in 10 plus. If you don't have to do it then even at ₹ 10, if someone doesn't do even 10.10, then even at ₹ 10, if someone doesn't do even 10.10, then even at ₹ 10, if someone doesn't do even 10.10, then immediately doctor, that is, how much have you earned by romancing us in this, if you do n't decide to do ₹ 1000 at home at 90, n't decide to do ₹ 1000 at home at 90, n't decide to do ₹ 1000 at home at 90, then how much you have earned, so don't even look towards it. It means that you have less if there are tented hostel mates and if you don't do that then you can try to do tan and map of Ujjain in OnePlus. This is the match of 90's that you have accommodated, it is okay from now on here. But here also he had the power, here also 302 opulence will be there for him too, for you, if you grease, you will not press, you will earn a role in this house, now you will decide whether you should have it on me too or not. If I open on excesses twice, how much do I earn? If I open on the frontal Shiv Ji Road and Khud Karoge, there is no slope on doing it and on the right one, on 90. Basically, I have developed Ankara Thousand for here. If I do this twice, it is not necessary. So max of 3000 any t-20 match fennel 125 definitely Ujjain so t-20 match fennel 125 definitely Ujjain so t-20 match fennel 125 definitely Ujjain so basically t-20 said now there are two, basically t-20 said now there are two, basically t-20 said now there are two, how much pressure on doing ruby ​​on that one that you are the one, how much pressure on doing ruby ​​on that one that you are the one, how much pressure on doing ruby ​​on that one that you are the one, doing it on that also means that this one is on that one, you have If you do n't do it, then you believe in him, Hussain, basically, if you don't rob him of your time, then you are his own, how much can you earn by robbing him, and how much can you earn if you don't, then how much can we earn? Doctor, I am earning right now 12-12-12 means I ca I am earning right now 12-12-12 means I ca I am earning right now 12-12-12 means I ca n't stop Tan and Tu, so how much did I earn for not robbing the house with net, Justice forces him to commit robbery, 30 more on the right side But how much did I earn for Twenty-20, I don't do it necessary, I earn for Twenty-20, I don't do it necessary, I earn for Twenty-20, I don't do it necessary, how much do I earn, mostly from 10 plus Mitthu, this one is the change, if you have come Chikram, then it means this one, we will have to click on this. It is difficult on this house, on that house, on this house, and on this water house, it is difficult, if we roll on that, then we will be able to generate maximum. Okay, so we have understood any pain that every time we have to think about two things. Still think about whether there is any benefit in doing it or not, you should have quoted, now first of all, what am I making here, the class is exactly like the one we are going to use in volunteer police station pen, here we are going to use public traffic A class and this will go to my house after house. But there will be two things, first of all, how much did Vidroh Giri earn, then how much am I earning in the job and tell us Robbery as much as we can, now here we will write the same thing like this, add inside it, this is the return on that, if my There is a need to give a note, if this happens, then I would have done it from here, the son looted the new house, had 100 A similar tow serial in the month, was on it in the left key and how did I call Sarovar along with Pushp, will you give me the information that my On clicking on the left side, how many maximums are opened and on not doing so, how many Muslims are generated. So with whom will we do the root left and the same work, it is with Rice and I will get some information from the right that we came here or Now what we will do after coming here, first of all let us see that if I am in my How To Purchase President, if I steal there and click here, then how much maximum will be generated, so for this I will have to create that But one take my answer is on new house so if maya answer start with robbery how much ceremony is that how much am I enjoying that it will go left with no if it was how much difference were entered in left milk torch bull plus right posture sacrifice It happened that it happened without Tuesday, if I want to make a promise, let us see that it happened without me, I was bowling without Beck in the left and Virat Kohli in the right, how much fun it was, now if I don't want to rob myself, then I What should I see Left you tell me the rebellion in yours Greece was so dark and without robbery how much it was supposed to be Dry you tell me how much Dubai was happening That is how dark it was in Vidro So here we will see My Ansal start that without robbery that how much you Theirs were it will depend maths dot maths of I was left this robbery was in and left was without if how much you were doing that without movie was disposal the time of both of these was alphabets we will do the same work for right and also here Same work will be done if we right click and finally we will return from here, we have got everything from this, now here we will order our house as per right, want to hello how Sarovar Ki A passes the route to him, Punjab returns. When the turn comes to do it, what will we return, why would you root inside the max thing Puri? If I do it, I get the benefit or if I do n't do it, I was bought, so I am here, the result is without robbery, the result revolt fell on me, in which I have priority, so this is ours The code is already done, what should we do on the net, first of all I asked the net lady and either tell me that you have fiber for committing robbery, she did not give that too, there is benefit in not doing that, strike, then tell me what is the maximum amount to be paid for committing robbery. And how much salary will I get if I do it in Dubai only, then I was thinking about myself, I am also worried about this note, how much profit do I generate by doing robbery on this note, that too, that is, if I am doing this then do that too. If I want, I am left and right only, it is directly connected, why do those, otherwise I will not do them, if you do not bring, then you father is generating maximum in the place of your sisters and if I do not want to do that at my house, it means. I can open left to right or not, how much maximum do I get if I don't do it, how much time do I get if I do, then tell the net man, friend, tell me how many maximums he is setting, but should I do it patiently or not? If I do it, then tell me how much you get if you do Ruby, how much you get if you don't do Robin. The combination of both of you will be the difference in this factory, meaning my trick will be the answer to the one who is necessary below me. Similarly, this track will be the answer. But if there is curry then it will decide as per its own whim that how much grocery will be got if without then how much will be got finally from here onwards if we return then we will fold it so here we have class scorpio horoscope friends then I will tell you Let me show this question in another way by coding it inside which we will fold it without creating any class. Okay, so there is some time here, let's check once on the tap house that this spelling is wrong, the spelling of foot is Piya Yaar and so. There is no mistake that it happened in between, it happened, okay, this Tilak and ours are going on, now I will show you this question by solving it in another way, in this way, this question should be given to us in a fair manner, if I ask this question. I want to do it with like feet without like, if you don't make me but then how do I do what do I do here I would make a career 1212 size deep two size deep means I return 12 size here now I will get benefit from this, after two sizes, I have to do 2nd test, so for installation, you are making the entire foot of class, without painkiller, this war can be done and let's see how it will happen, I will give two information here. I am storing my two sizes deep, first do this with him, that distance, maximum amount, how much doubt occurred and without increase, maximum amount, I get well so soon, bro, how much maximum did you set and without, how much did you generate maximum amount, this Except two information I have all the patients on the index without hoagie point then two believe my love from the side also the penis is left take two size retained it is 0 inside the are kept rebellion brick itna maximum zdnet kartaa without hoagi howa maximum If it generates, then I would have created my result, it will go to my mother that this worldly thing is a new intention toe size shayari and I return from here, what would have been kept in the unit two size caribbean deposit, would have kept the video, now how will you make your friends my Answer of zero is equal to two i.e. how much maximum can I generate 20 robberies, i.e. how much maximum can I generate 20 robberies, i.e. how much maximum can I generate 20 robberies, then how much messenger can I send in rebellion for free, on what will it depend, can I send seed roli message, it will depend on the left leg, do n't robery, I will have to do more. If it is not necessary to do wife in, then how much of the maximum amount did I get for not committing robbery on the left and right, that is, how much Magsaysay Award did I get for not committing robbery on the left leg and for not committing robbery on the right leg. Plus, I can add my valley here. I will do the daily root dot value and I will give the answer of one index that what is being stored, if I do not do any through on this particular, then what will be the maximum net, if I do not commit robbery, what will be the maximum donation, this is the max of maths dot. Match of left of that thrill left of OnePlus I in maths dot mac should right now do this fort of ours so that this work can also be done right click so finally done from here we have set the anklet in here If you come, what will you get here? If you get 12 size deep, then you will have to get the result, then here the result is free and here you will get your result and you will get it easily if you convert its sentence into sentence was all words wife. I have written more or less than this, but this is the code which I have commented, to understand that these are the ones who are going to buy more, many horses are more labeled Aghor, so this one should always be used in the chord because it is DD1 but only then You are giving a test that you can give this type of quote on anyone whose pictures are happening at that time. You can give this type of quote within the test. It will work if you care about the results but if you are doing it while sitting in an interview. And if you ask yourself a question in the interview, then I will never give any side effect to this one, I will always call this one as Prince Kumar because the code is more wearable, only dimples are acceptable, let's remember once and see that this discovery has been accepted anywhere. What has not been done is that once you see it is running, even after submitting the code, you should see that it should run. The secret has worked. Okay, so our code will be put in the front in both the ways. I have shown you this method as well and I also showed you the method with a note in the code. If you are doing it in a test, if you have two lines in this test, then you can use this method. If you are sitting in an interview, then you should also double quote. I hope you liked the video and learned the intermediate points from it. If so, then like this video, subscribe to this channel as much as you can and also share it as much as you can so that You share this so that your friends come to know that Calling on War requests some channel which is uploading content for free, which is solving your questions for free and is now giving the address of Sarthak Hotel, so let those people know. Please share the video as much as you can. If you are coming here for the first time then please subscribe and like it. Life exists, don't just like it. See you in the next video.
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
299
hello welcome to something called today we are going to saw the day 10 of september equal challenge today's problem name is bulls and cows okay so let's try to understand the problems statement first then we will try to see the given example then we will try to design one solution for the same okay so what they are saying suppose you and your friend is playing one game name bulls and cow so what is the game here so basically uh you will write down your number one number in a paper diets probably so suppose you write you wrote one number call one eight zero seven in your paper so it's your number or you can say it as a secret number okay after that you will ask your friend to guess any number of the given size right so if you write down a four digit number your friend will only gets a four digit number right suppose your phone your friend is guessed seven eight one zero so now we need to match each and every position of the two number guessed number and secret number and we need to return the bool value and count value so what is pool value and covalent here suppose if you found any number is matching with its digits and its value then that in that case we are going to increment our bull counter so you can see that here 8 and 8 is matching right so we are going to increment our bull counter so our bull value will be 1 but if you check the other value right so one and seven i can see one and seven is not matching right but you can see or seven is not valid but you can see that seven is already there right its position is wrong probably but seven is present in our secret number right so that means we are going to implement our cow value but suppose if suppose that 7 is not there in a secret then we are not going to increment our cow value okay so again we already matched 8 so i know that it will be considered as bull again i will check for one right again i will see that this one is not present in the third position but one is present in the first position right so again it can be a cow right so we are going to increment our cow again we will move forward and we will check for zero again for zero it's not matching with the last digit but it's matching with the third digit right so again we are going to increment our cow so our cow will be three and bull will be one so once we are done we need to just return it right one a so here where are you will denotes the number of bolts and threes b so where b will do next number of curve okay so at the end we need to return this answer so let's quickly check the second example also for better understanding again we can see i will start try to match with zero and one i can see zero is for the first position it's not matching right but i will check zero is present in other position node right so again it will not increment it will not consider as cow value right i will move for forward and i will check for the second one here i can see it's matching with the position itself right so we can see we can say that our bull value will be plus one it's matching right now again i will check for this one here i can see it's not matching right with 2 but this number is present in the first position so we can increment our curve value as 1 now i will move forward i will check the last digit 1 and 3 here it's not again matching but it there is no more possible position for this one also right because we already consider this one and this one so again this will not be considered as cow so our cow will remain one and boo will remain one so we are going to return one a and one b ok so this is the problem statement let us try to solve the same using java so how we can solve it so we have two goals right one is we need to count total number of bull and second is we need to count total number of cow so counting the bool is very easy right so we can iterate through these two number and we can check the equal digit with equal position right and if i found that i am going to increment my bold side right now how we can count the number of cows so the tricks is there only right so because we not only we need to check the position and value but we need to check that particular number seven is present in the other uh in the actual shifted number or not in other position right so that is trick so how we can do that so we can one nav approach can be that we can pick any number and if it is not matching then we can again scan through the secret number once again and we can uh check that whether the particular number is present in the other position or not but that will cause for that we need to use two nested for loop and that will time complexity will be in that case order of n square so can we solve it in a linear time i think we can solve it in linear time right so somehow we can if we can reduce the time complexity order of n so that will be our optimized solution right so how we can do that so probably we are going to take two added right so one probably you can name it as guess added and one can be secret array so here our area size is six right because we are dealing with numbers or digits right so it should be zero to nine so our address size will be zero to 9 and total size will be 10 right so now what i will do if the number is matching right position and the value is matching then we are going to increment the bool and if it is not matching suppose if you check this example right 7 and 1. so this is not matching right so what i will do i will so this is our secret value this is our guess value so i will go to my secret value secret array and i am going to put this particular index i am going to increment my value initially it will all 0 and it will be plus 1 right again i similarly for this uh guess i will go guess array and i am going to find the seventh position and going to increment that okay so it should be eight seven so it should be again plus one now for the second number it's already matching we don't need to do anything so again i will come to the third digits again here it's one and here it's zero right so again what i will do i will again update the corresponding value right so again it's for zero it will be plus one again for one it will be plus one right so using this way now later we can again when once we are done with the iteration of these two numbers then we can again iterate through these two array and we can identify the minimum value and we using that we can count the total number of cows but why we are doing is that so that's the question right so basically we are just taking the minimum value right so why so suppose i increment the seven i pick the seven and i increment seven value as one here right what that means we have one number in our guess number that's number of frequencies one so now i will again whenever i will iterate through my secret array in the end i will check for the seventh position is there any number so if it is matching right one that means we can pick one right so suppose if i found that in our actual secret array there are two sevens so it will frequency be two right in that case i can only consider one so for that reason i am going to take the minimum value so this will be the logic so let's write the code quickly using java that will much that will give you much better clear understanding so let's write that after that we will try to analyze the time and space complexity okay so what i will do i am going to take two add a right integer address of size 10 so let us name it as secret and or s and again its size will be new into 10 okay since we are dealing with decision only rights similarly i am going to declare another array probably in g for guess numbers and again it will be new in 10 okay so now what next need to take two counter right so one is for bull counter to calculate the number of bulls initially it will be zero and again i need another counter to calculate the total number of cows right so again it will be z now what next so now i can run one for loop so for int i equals to zero and our for loop will run till our whatever our secret so in this case that length of secret or guess will be cement will be same right so we can consider any of the ones so it can be dot length so since its length so we need to call the length method and it will run till i plus ok now what i will do i will declare two more character probably so care so probably let us name it a cs and i am going to pick the particular character for comparison right we need to do comparison right so get cs and let us take it as secret at first we are going to consider the secret one care at for using carrot i am going to pick the particular number right so let us it will be like this right similarly we will do for character of guess number right so it should be cg probably and let us name it as guess dot care at and again we are going to ah it will we will face the a value so what we are doing here so we are picking one number at a time right so we will start with zero index and we will iterate till end right so now after picking the numbers so we need to check the equality right so let us do that so if cs equals to cg means position and value both are matching right so we are going to increment our bull what next now and if it is not matching else then we are going to update our these two frequency added right so i am going to update this array so it should be s and whatever my character cs so since its a character we need to convert into integer diet because adding addict only contains integer index okay so it should be cs minus 0 and whatever the initial it will be 0 since it's an integer adder we are going to increment the frequency similarly we will do for the second number also for our guess so again it will be cg minus zero so we are incrementing the frequency right so this for loop will populate both these two added right or frequency adder now i will run through this or i try through these two array and i will go to take the minimum value okay so let us do this so how we can do this so again i need to run one for loop so again it will start from int i equals to 0 and again it should be run till i so both added size is 10 right so it can we can take either s or g so let's take g this time so it should be less than 10 right it's fixed right actually and it should be i plus now what i will do i will take the minimum value right so we already declare one variable called cow so let's reuse that quickly so should be cow and again whatever my cow value counter value i am going to take the minimum value of this 2 right suppose if we are checking for zero i will check the zero position for the two array ah to add a secret array and guess array and i am going to take the minimum value right so it should be math dot min again it will be s i or g i okay and once we are done we can directly return it right so it should be written so it should be in total number of bool plus for boolean it return a again before for cow also we need to append the cow so cow will counter the total number of cows and plus it should be b right so i think that will be our answer let's quickly run our code and check how whether this code is compiling or not okay so there are size slide spelling mistake let's quickly fix that quickly okay so it should be i think g only it was wrong so let's now run our code and i think it's giving us the expected answer so now let's quickly submit our answer and check whether it's accepted or not okay yeah i think our solution is accepted so let's try to quickly analyze the time and space complexity here right so we can see that we are iterating through the secret or whatever or guest array only once so again so time commission will be order of n where n is the size of our secret or guess number okay and this case you can see the second for loop we are running it in constant time right so in this case we are going to consider this time capacity also only right order of n since whatever the size of our input string length it will run only for 10 times only right because it's always 10 0 to 9 so again so for time comparison will be order of n and for the space one again we are using constant space i think because uh every time it stands the size is 10 right irrespective of the input size so we can solve it using it in constant space right so time completes space composition will be constant i think you understand this we understand the logic if you still have some doubt you can ask me in the comment section thanks for watching 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
1
hi guys in this video we look at to some problem so let's see what the problem is so we're given an array of integers and in that we need to find indices of two number such that they add up to a specific target so let's see what the assumptions that we can take so there is one only one possible solution and we cannot use the same element twice so let's see the examples so let's say if our array is one two five thirteen and the target that we are given is seven so we know that 2 plus 5 is 7 so we need to return indices 1 &amp; 2 because 2 is at return indices 1 &amp; 2 because 2 is at return indices 1 &amp; 2 because 2 is at index 1 &amp; 5 is at index 2 let's look at index 1 &amp; 5 is at index 2 let's look at index 1 &amp; 5 is at index 2 let's look at one more example so we're given an array 1 6 12 13 3 8 15 16 and our target is 20 so we know that 12 plus 8 is equal to 20 and the indices that we need to return are 2 &amp; 5 so that's the problem so let's are 2 &amp; 5 so that's the problem so let's are 2 &amp; 5 so that's the problem so let's go to the whiteboard let's look at different approaches and then we'll come back and look at the final code so how to solve this twosome problem we'll take this array which is 1 3 6 8 12 13 15 16 and we'll take target as 20 and then we'll see how we have different approaches to solve this problem and how each approach fares against each other in time complexity and space complexity wise so the different approaches that we are going to take a look at are brute force algorithm binary search two-pointer and algorithm binary search two-pointer and algorithm binary search two-pointer and the last one is map and dictionary okay so in brute-force it's a straightforward so in brute-force it's a straightforward so in brute-force it's a straightforward approach what we'll do is we'll take one number and we'll compare it with rest of the numbers or we add it with rest of the numbers and we'll see if the target is 20 or not so we'll take one and then add with three check if it's 20 or not one and with six check which 20 or not and similarly 1 plus 8 1 plus 12 1 plus 13 and keep going and if you don't find it then move on to next number 3 again check with rest of the numbers 3 + 6 3 + 8 3 + 12 rest of the numbers 3 + 6 3 + 8 3 + 12 rest of the numbers 3 + 6 3 + 8 3 + 12 and keep going if we don't find 20 move to next number and keep on doing so the code for this brute force is also straight forward we just run a for loop I of I equal to 0 to thumbs length and then J equal to I plus 1 which is whatever the outer loop is inner loop starts from the next number and then we add two numbers of I plus J if its target then we return those two indices so straightforward with them and since we are running to loot for till numbers of lengths the time complexity of this algorithm would be O of n square okay so next approach that will take a look at would be binary search so in binary search approach what we will do is again we'll pick one number which is let's say 1 and then we'll see how much do we need to make it to target 20 so we say we need 19 if 19 was there we can do 1 plus 19 equal to 20 so what we'll do is since this array is sorted what we can do is we can look up 19 in binary search array so simple binary search look in the middle compared with the number if it's the number that we're looking on greater then look in the right side of the array if the number is smaller than we are looking for then you look in the left part of the array so the advantage is we are not scanning the whole array we're just looking at particular elements and then we are deciding the half of the array so the algorithm would be again straightforward we run a loop for of I of 0 two numbers in length and then what we do is we calculate the required value which target - number 5 so 20 minus 1 which target - number 5 so 20 minus 1 which target - number 5 so 20 minus 1 which will be 1 and then let's assume there is some binary search method which is doing this not going to details so just assume this binary search returns the index of that number if it's find it if it doesn't find it returns -1 so we pass the find it returns -1 so we pass the find it returns -1 so we pass the array we say start looking from the next number and till the complete array and look for this required number and if it finds the number then J is not -1 and finds the number then J is not -1 and finds the number then J is not -1 and then we simply return those 2 in taxes so again simple approach to borrow them and since we are doing binary search and the time complexity of binary search is log n like if I have eight elements in array to search element in binary search weight I will take four blue cups or for comparison to tell you whether that number is there or not if there are sixteen numbers then we file the cups or search if there are 32 numbers there'll be six lookup search so it's not linear it's logarithmic so the time complexity for binary search algorithm would be n log n ok so the next approach that we'll look at would be 2.0 so this is really good approach be 2.0 so this is really good approach be 2.0 so this is really good approach because we'll be using this in lot of other problems as well so let's see how this works so what we'll do is we'll have two pointers in this array called left and right so left will start with the 0th index and right we'll start with the last number and what we'll do is we'll add up the two numbers and those pointers and we'll check if the target is 20 or not so 16 plus 1 which is 17 so it's not 20 so it's less than 20 and since this array is sorted so what we'll do is if it target or if the sum is less than 20 we keep moving left to the right so that we get bigger numbers but if the sum goes more than target we'll move right to the left so that we get smaller sums ok so let's say 1 plus 16 which is 17 so there's so we'll move the left to three 16 plus three 19 which is still less than 20 so we'll move left to 6 16 plus 6 22 which is more than 20 so now we move the right pointer 16 plus 5 still greater than 21 so we move the right pointer 13 plus 6 19 less than 20 so we move the left pointer 30 plus 8 21 greater than 20 so we move the right pointer and while we keep doing that eventually we will get our two numbers whose sum is 20 so left and right point to a 1012 and that's the sound require so again the code or algorithm is simple we start with L 0 RS n minus 1 which is mass number keep doing that while left is less and right sum of the two numbers if sum is less than target then n plus thus move left to right if sum is greater than target I all right - - and if sum is equal to all right - - and if sum is equal to all right - - and if sum is equal to target then you just return the values so that simple algorithm however since we are doing this linearly like if you come to iterations there'll be like a Direction plus would be like L would be 4 times and I'll be 4 times so we're going linearly so the time complexity of this problem sorry time complexity of this problem would be o n so if you look at the time complexity 2.0 algorithm is better than brute force 2.0 algorithm is better than brute force 2.0 algorithm is better than brute force and binary search however if you notice to solve these two problems we need the array to be sorted so now in the next approach we'll see an interesting part where if the array is not sorted and how do you solve the same problem okay so now let's see if this what happens when this is not sorted so it's the same money or same numbers but in unsorted manner or random manner so now we cannot apply binary search or two-pointer apply binary search or two-pointer apply binary search or two-pointer because they need array to be sorted and we can definitely apply boot force but we know that's a slow process so for like larger is so what we do is we look at the data structure called map or dictionary and we'll see how we can use that to solve the problem so what we'll do is then we will start with a number and whenever we come to a number we'll see what is the required number to make to target or what is the complement of that number for the target and we'll add it to dictionary and then when we keep moving for each number we'll look up at the dictionary and we'll see if anybody needs that number or is it anybody's compliment so let's see how it works basically so when we say one we'll say the compliment needed is 19 and we'll look up in the dictionary is definitely obviously it's the first element there's no so we'll add 19 in the dictionary and we'll say number at 0th index is looking for you and we go on so we are look at me come at 6 the complement is 14 and we say index as 1 we come to 12 we are 8 index is 2 we come to 13 we had 7 and X 3 we come to 3 we had 17 and index 4 and now when we come to 8 will do the are check of looking up at the dictionary and we'll see yes it is there and number that index 2 is looking for 8 so we'll say ok number 2 that's 12 so 8 plus 12 is equal to 20 that's our target and indices are this and this so 2 and 5 indices that we are looking for so that's our dictionary map approach to solve to some problem for unsorted array the time complexity of this problem would be a orphan but there is a space complexity as well since we are using dictionary so the space complexity for this problem organization would be orphan since in worst case we would end up storing all the numbers in the dictionary okay so that's the put and now that will actually code this approach and we'll submit and then see what happens okay so this is our final code I have the same array that we just discussed on the white board and then calling to someone that arrived in target as 20 and in this to some metal arm we are looping through 30 and then we are checking if the number is there in the map or not if the number is found in map then we return both the indices if number is not there in the map then we calculate the complement and then we put the complement in the dictionary along with the index of that number so pretty easy and straightforward or code so let's run it and I've put a print statement to see what happening so as we expect when we are at number one we add 19 at index 0 when we are at number 6 we add 14 at index 1 and likewise when we come at 12 we add 8 at index 2 and 13 and then 3 and then next number is 8 so when we loop through 8 we find that 8 in dictionary and then we return indices 2 and 5 so that's the whole flow of the code so there you go if you guys liked the video if you guys learn something new give me thumbs up any feedback any suggestion let me know in comments and then subscribe for more videos
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
1,528
welcome comrades to this video we're going to do a lee code challenge in python this one is called the shuffle string i'm going to skip the description because i'm going to explain it through the explanation so if you're doing this problem it's good to read through that but first i'll do the explanation of how it works then i will explain how to solve it and then we'll do the code for the problem so let's go through the example so we can make sense of this all right so they're going to give us a string here this one is an example of code lead which they have here at the top of the picture then they have the indices in which they are positioned or they want us to reposition them from so in this case 45670213 and what they want us to do is shuffle that to a new set of string in this case we're just going to start at zero and go all the way to the end so 0 1 2 3 4 and we're going to fill in the blanks here so let's draw that out so you can kind of get an idea so they give us this code lead is our string then they give us the indices four five six seven zero two one and three they're shuffling rearranging one and two to confuse us all right so this is our in disease uh make sure i'm spelling that right indices yes all right and then we're going to take a new string so we're just going to draw the into c index here 2 3 4 five six and seven and what they're going to want us to do is have this be our answer or our new string so what we're going to do is we're going to pair this up so what we could do is start here we're going to do a for loop through this here this indices here and grab the letter so for example 4 is our first one so we're going to take 4. we're gonna grab c and move it down to here to this position four and put c then we're gonna take five we're gonna move o down here move it there then we're gonna take six and move d down here then we're going to take 7 move e down here then we're going to go keep going we're going to take 0 which is l we're going to move it over here then we're going to take 2 which is e and we're going to move it right there then we're going to take 1 which is e and we're going to move it right there then we're going to take 3 or t from 3 and then we're going to move it right there and so that is our answer lead code all right hopefully that makes sense on how you solve it so let's code that and see how that looks all right so first we're going to just going to store or create an empty string which is this one right here and i'm just going to call it answer then we're going to create our for loop which is here and we're going to loop through this indices so that looks like this for i and range and we're going to do the entire length of indices okay and now what we're going to do is we're going to build this answer here and how we're going to do that is by just kind of like i showed you here in this process so what that looks like is answer we're going to store it in answer and we're going to append or add it to each time we for loop through this and we're going to bring in s which is the code letter here we're going to bring it down so that's and how we grab that is do indices and then dot index at position i okay so what that means is we're going to take the index of the indices so whichever position so four we're going to take that one of this one here we're going to grab the s here and then we're going to store it in answer string all right so that's really the key line right there hopefully that makes sense and then all we got to do is return results and that will give us back that new array that we just built so let's go ahead and run that on all test cases make sure i have everything correct and oh i don't want result i want answer i want to make sure i'm all right let's go and it works correctly all right well hopefully that'll make sense if you have any questions leave those in the comments and hopefully i can get to them i try to get to as many as i can and thank you for watching this video and i hope to see in the next one
Shuffle String
kids-with-the-greatest-number-of-candies
You are given a string `s` and an integer array `indices` of the **same length**. The string `s` will be shuffled such that the character at the `ith` position moves to `indices[i]` in the shuffled string. Return _the shuffled string_. **Example 1:** **Input:** s = "codeleet ", `indices` = \[4,5,6,7,0,2,1,3\] **Output:** "leetcode " **Explanation:** As shown, "codeleet " becomes "leetcode " after shuffling. **Example 2:** **Input:** s = "abc ", `indices` = \[0,1,2\] **Output:** "abc " **Explanation:** After shuffling, each character remains in its position. **Constraints:** * `s.length == indices.length == n` * `1 <= n <= 100` * `s` consists of only lowercase English letters. * `0 <= indices[i] < n` * All values of `indices` are **unique**.
Use greedy approach. For each kid check if candies[i] + extraCandies ≥ maximum in Candies[i].
Array
Easy
null
1,976
hello welcome today I try to solve another difficult problem 1976 number of ways to arrive at destination so we are just giving a graph structure so this road means from not U to not way with a cost of seven so this seven means time and this n is the total number of nods we just need to calculate how many SS pass from the not zero to not n minus one so for this example from not 0 to not 6 how many s is pass so we can find there are four Sol Parts yeah we need to calculate how many of them and the results to be modular to 10 to the power of 9 + 7 so modular to 10 to the power of 9 + 7 so modular to 10 to the power of 9 + 7 so this means yeah we cannot count the pass one by one we have to use some memories to record the pass yeah let me first explain it in the Whiteboard and then go to the code Editor to finish the coding uh for this problem we're going to use the D Sol this pass to solve it so for example if we have a some no so this is a like another zero maybe go to another one two three and there would be another no for example this is no four and yeah we want to calculate from no zero to n four what is the SED path and how many of them so for example this is just one this is just a two yeah for Simplicity we want to calculate the distance from 0 to four and how many of them so the S part is three and how many of them as we can count it is like this is one this is two and this is three so in total there are three parts but inside the D programming yeah inside the algorithm how should we calculate it so this is from the beginning while we go to this one we're going to have a record so we're going to record of WS or we can get yeah we can have a record of way so for while 02 this not one so there's only one way and 02 this not two so the SED path uh there's still one way and while it goes to not three it is still one way yeah because for Z to three what is the sorted path it is one and how many ways it is only one yeah and similar for others now we will go to node four so while we go to node four so from node one we can go directly to node four with a distance with a time of two so the total time will be three and how many ways so it will be this value one yeah it should be equal to this value no matter what value is currently it is it can be five or six but currently we're going to C it as one yeah and with a distance of three now while we are checking this not two from 02 to 4 the SED part is still three yeah so that means we will not update it we're going to count it yeah it is a three we're going to count it another one so from not two there's another one so 1 + 1 currently it is two now we are so 1 + 1 currently it is two now we are so 1 + 1 currently it is two now we are checking this not three so for this three is there is a number of ways how many ways it is one and with a distance 1 + 2 it is a still three so we're going 1 + 2 it is a still three so we're going 1 + 2 it is a still three so we're going to C it plus another one so it going to be three so this going to be the result yeah so for example if this is distance is one what we going to do because this is three and the right side is also three but in the middle it is a two so we're going to update it yeah while we updated it we're going to use this one and we're going to record only this one because this is the soter so we're going to count it only as one so everything here and here is inside the that plus algorithm we're going to calculate just yeah inside the algorithm we do not need to calculate uh another time we just calculate inside of the algorithm yeah now let's just go to the code Editor to finish the coding yeah let me first prepare a graph because I going to use it later so it going to be uh default D inside it going to be list now I'm going to prepare the graph so for uvt inside the load because it is undirected so I'm going to prepare a undirected graph so it going to be g. append inside it going to be way with this time and similarly d v to the dot append it should be U and T so this is the preparation for the graph now I going to prepare the dist array so the D array will be infinite times n yeah I also need to prepare another array I going to prepare uh it as pass how many pass yeah so the pass array is going to be starting from zero times basically this pass is to calculate how many passs from no 0 to n minus one so for the n minus one we just need to return the plus minus one it's the final result now for the dist zero and pass zero we can initiate the values the this to zero as we know in that algorithm and the distance zero should be starting from yeah should be zero because the distance the cost from the first no it going to always be zero yeah because we didn't go if we go from zero to four it have a cost of five but at the moment we're going to prepare the this zero to zero but for the pass zero because we're going to use it to calculate yeah we're going to prepare it as one otherwise it going to never increase so this is the pass now I'm going to prepare a PQ so this is the priority Q inside it going to be the time for the first node from the beginning the time is zero and the node is zero so inside it is the time and no now I'm going to sex priority q y PQ I going to pop out yeah while PQ exist I going to pop out the time and no U so be hip poop with this PQ now I'm going to check his neighbors so for V because inside the neighbors it can be V and time yeah so for here I'm going to use uh another variable say and the new time is also a cost yeah so for V say in g u in this no yeah so my new time would be this t plus this C so this is the B algorithm because we need this kind of T So this means from some no to this no U and then from some U from not U to not V it has a cost of C it has a time of C so this t plus C basically we need to check this time so if this time is less than the distance array inside it going to be the V it's neighbor it's neighboring no yeah if it is less than that so we can update the distance array so the this way so be equal to the time and we can also update the W so the W of way should be equal to it's coming from where it's coming from the n u so it's equal to w u uh I'm not going to use the W I'm going to use the pass so let me copy uh the pass yeah now we need to put something inside the priority CU we're going to use the hit proof yeah so the hit P should be a priority Q with the new time and the new nod it should be n b yeah and there's also another case so if the time equal to the distance of this way yeah so this means there's another nod if it is equal so for this no if it is less than and then let me go back to the Jo yeah it means for example for this no one we find a distance if this is two and if we find another one it is equal yeah in the middle and at this side there's another one it is equal we're going to plus it so here this pass so the plus the pass so here the pass way should plus the pass here where it's coming from and finally we just need to return the pass with minus one because minus one is a to this last nod yeah basically this is the entire code you can see that is not so easy and that is not yeah that is not so difficult I mean if you know the D TR algorithm and you can write the that algorithm so the hard part is about this area how should you check the path and here also here yeah just increase the one L of code add another two lines of code and you can calculate the result but this going to be hard you have to yeah totally understand what's the meaning of dat algorithm yeah it's similar like the dynamic programming yeah you have a record of the previous pass so the pass this pass aray is just a record of the previous ways so for example for this not four how many ways to this not three and how many ways to this not five and finally we just need to calculate yeah if it is equal we're going to accumulate and we can accumulate from here if it is not equal so we're going to update a new yeah a new value we're going to put it inside the priority Q and uh finally we just needed to return the final result now let me just run it oh here is something wrong uh let me check yeah let me delete this areas yeah there still something wrong let me check the last one so this means I didn't use the modular yeah basically I also need to prepare a modular this is given by the question it is a 10 to the^ of 9 + 7 and finally we is a 10 to the^ of 9 + 7 and finally we is a 10 to the^ of 9 + 7 and finally we need to modular this mod now let me just run it to chech again as you can say it works now let me submit it yeah as you can see it works and it's pretty fast basically it is just like 20 lines of code and most of the code is a Data Trust template we just need to analyze how to calculate the PA how to calculate the Ws and now let's analyze the time complexity so for the time complexity we're going to use the number of the node is 200 yeah so we I will not analyze this areas because this areas will not increase the time complexity for D algorithm basically for the D algorithm it is a uh yeah it is a e log V it is the E log v e is the number of edges why because for here for this uh uh yeah for here we're going to check how many edges so for this way it is connected to you and we basically check how many edges and for the hip push we're going to check yeah how many vertices so the time complexity for the HP push it going to be log V and here for this for Loop it going to be um e so the time complexity will be e log V so for E it is n Square so it is n sare time log n so that is for the final time complex complexity if you think this is helpful please like And subscribe see you next time
Number of Ways to Arrive at Destination
splitting-a-string-into-descending-consecutive-values
You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer `n` and a 2D integer array `roads` where `roads[i] = [ui, vi, timei]` means that there is a road between intersections `ui` and `vi` that takes `timei` minutes to travel. You want to know in how many ways you can travel from intersection `0` to intersection `n - 1` in the **shortest amount of time**. Return _the **number of ways** you can arrive at your destination in the **shortest amount of time**_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 7, roads = \[\[0,6,7\],\[0,1,2\],\[1,2,3\],\[1,3,3\],\[6,3,3\],\[3,5,1\],\[6,5,1\],\[2,5,1\],\[0,4,5\],\[4,6,2\]\] **Output:** 4 **Explanation:** The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes. The four ways to get there in 7 minutes are: - 0 ➝ 6 - 0 ➝ 4 ➝ 6 - 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6 - 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6 **Example 2:** **Input:** n = 2, roads = \[\[1,0,10\]\] **Output:** 1 **Explanation:** There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes. **Constraints:** * `1 <= n <= 200` * `n - 1 <= roads.length <= n * (n - 1) / 2` * `roads[i].length == 3` * `0 <= ui, vi <= n - 1` * `1 <= timei <= 109` * `ui != vi` * There is at most one road connecting any two intersections. * You can reach any intersection from any other intersection.
One solution is to try all possible splits using backtrack Look out for trailing zeros in string
String,Backtracking
Medium
null
414
welcome back everyone to another video here in the unknown code YouTube channel today we have another Elite code problem this time 414 third maximum number this one is a little bit simpler one and it should be a lot easier to explain than the last episode and this problem states that we're given an integer array called nums and we want to return the third distinct maximum number in this array this one isn't too crazy and if the third maximum does not exist then we want to go ahead and return the maximum number instead what does it mean by Third maximum number let's go ahead and hop down below to some examples so I can show you all so for example number one we're going to be given an array called nums which has three two and one and in this array the first largest number is three the second largest is two and the third largest is equal to one so logically what would return is one because it's the third largest number in the array let's take a look at the second one the second example we're given in numbers array equal to one and two here the first largest number is equal to two the second largest is equal to one and the third largest does not exist so in this case it says to return the largest number which would be two so that's how we get two for that output let's take a look at the final example they give us an example number three they're going to give us a nums array equal to two three and one so in this case the largest value is three the second largest is equal to two and the third largest is equal to one notice that we have two twos it doesn't matter because it is going to count as the same one so once again the third largest value is one and we'll go ahead and return that let's go ahead and hop back up to the constraints to see if we can pick out any more information before we try to solve this back to the problem our first constraint is one is less than equal nums that length is less than equal to 10 to the four so this one's very simple this one's just saying the length of nums is between one and one thousand they're not going to trick you or anything they're not going to give you an array of zero or there's no maximum whatsoever so that's nice to know the next one is pretty important the next one is stating that negative two to the three is less than or equal to the numbers of I is less than equal to 2 to 31 minus one basically what this is saying is that the values in so I'm gnome can be the max value and Min value of integer which kind of foils a lot of people's plans when they do this because normally whenever you're going to find a max value you need to set that max value to some very small number to start out you can't use integer.min because out you can't use integer.min because out you can't use integer.min because technically there could be a value that's equal to that and break everything so I do have a workaround for that don't worry so once again our goal is going to be go through the array and going to keep track of the top three elements as we go and we'll go ahead and return that third largest and this one is a very simple problem to solve all we really have to do is Loop through the array once manage variables for one two and three and then go ahead and return that third one the only thing we have to deal with is the possibility there being a value equal to the minimum value of an integer so to get around that we can actually choose Longs instead and then cast them back to inches at the end so let's go ahead and take a look at our pseudo code and then some example walkthroughs let's get started with the pseudo code so we're going to start out with saying let first second and third equal to negative two raised to the 64. this has been basically setting all of these values to the smallest number that you can set along to then we want to say for each element in nums we want to check if num is greater than first if this is the case we're going to shift all the max values down one we're going to check if num is greater than second but also less than first if this is the case we're going to go and shift second and third down one and finally we're going to check to see if num is greater than third but less than the others if this is the case we're just going to set third then finally we'll return third or first and of course that's going to depend on whether or not we have a third greatest or not but like I said this one is a very simple problem let's go ahead and take a look at one of our more complicated examples and we'll hop on delete code and take a look at how we can do this for example we're going to go with nums equal to 2 3 and 1. so like I said before we're going to go and set to first second and third equal to negative two to the 64. then we're going to go ahead and start looping so for I equal to zero numbers of I is equal to 2 and now two is greater than first so go ahead and set everything set third equal to second is that second equal to first then set first equal to two we can move on so I equal to one nums of I is equal to two again so here we already have two in here so we're just gonna go and Skip or I equal to two numbers of I is equal to three so now three is even greater than first so go ahead and swap everything so we'll set third to Second we'll go ahead and set second equal to two and we'll go ahead and set first equal to three then for I equal to three we got numbers of I equal to one is less than first and second but greater than third so one is greater than third so we'll set third to one and now we have first equal to three second equal to two and third equal to one so now since we have third we're at the in the loop we wanna go ahead and return third which of course is one so like I said nice and simple algorithm let's go ahead and hop on leak code and get this coded out we're gonna start out with three variables first one is gonna be a long first equal to Long dot Min value then we're gonna have a long second also equal to Long dot menu value then we'll have a long third equal to Long dot Min value then we're actually going to use an enhanced for Loop because for some reason it's faster for final and num and nums and we'll go ahead and say if our num is greater than first if this is the case we're going to set third equal a second set second equal to First and set first equal num otherwise else if our first is greater than num and our num is greater than second then we want to set third equal to second we want to set second equal to num and then else if our second is greater than num and our num is greater than third then we just want to go ahead and set third and then that is it then outside of the for loop at the end we want to go ahead and return third equal to Long dot Min value so if we're still equal to Min value we want to go ahead and return first as an INT otherwise we want to return third as an INT let's go and submit and see if I type out anything and there we go we get zero millisecond run time if you do this for loop with a regular I with a regular iterative for Loop it actually gives you one millisecond I found that up here which is interesting but if you found this valuable or you learned something please be sure to like comment and subscribe as always I'm Ethan encoder I hope you have a great day and I'll see you in the next episode
Third Maximum Number
third-maximum-number
Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_. **Example 1:** **Input:** nums = \[3,2,1\] **Output:** 1 **Explanation:** The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. **Example 2:** **Input:** nums = \[1,2\] **Output:** 2 **Explanation:** The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. **Example 3:** **Input:** nums = \[2,2,3,1\] **Output:** 1 **Explanation:** The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Can you find an `O(n)` solution?
null
Array,Sorting
Easy
215
82
Hello Guys Welcome To My Interesting Video 10 Leaves Of Coding School Remove Duplicate From Haunted Place Were Given All In Places In All Value Certificate For Example In Real Consistency 314 Advances Money 1282 Digit Drum And A Trident Nariman In English Suvichar English Saving Element 1215 Tunic High Job Morgan 122 Written in the Final List So Let's Start Coding This to Understand This App Better Says Stuart Little Bit Students Research Visible Better and All ISRO's Word to First Weekend Tourism and Asked Her Not to Be Considered as Nariman Point and Doing Worship Can Check Is Note David Nalbandian Just Want To Head OK Know What We Can Do That Can Check Or Draft In China Which A Gifted The First Limit Like And Quiz The Giver In This Is Not Given Person The First Element Straight Note Required The Best Food For the first day of the week and let's get started 2a so in this case and declaring and shadow vegetables suggestion list note staff and CDO is equal to new list android automatically the value of 101 more grand give relief To Here a Word Can Attach This To-Do relief To Here a Word Can Attach This To-Do relief To Here a Word Can Attach This To-Do List Start Star Utsav Movies All Elements and Check Again Play List Starr ITR-2 The Element and the First No ITR-2 The Element and the First No Later in Latest Writing Code Phando Suvatiya Ko Into Witch Will Have to Check Airtel 2G case will have to check this variable value or notes of items next that this person is equal to two years star next earn extra person graduation value robin also same not done in this world and tourism place value asim they can keep updating m so 19 We Check This And Room For Doing This You Can Give Very Look Swill Lighter 4 Next Key Value Is Equal To Migrant Idolators Next And Next Star Value In That Case Was Taken Decide Candidates For Editing And In Elementor Simple Code This Item Star Next Is Equal To Hydrated Star Next Pure School Will Be Able To Delete The Element Okay So Let's Example This Is My Element To Subscribe Now To Do Subscribe Button To Ka Tractor Subscribe Will Avoid During His Good Deleted Net Means This Link And Spring And To attach tani chap deleted note that was presented 9 middle sweden note and senior so if done that using no previous note ok member concept office and now what hinduism he gives one example doob check itself from this is working properly or not morning previous if I have To take this example it's ok sir poses during this website to delete bodhvyam free app to read n1 flu ruk i finally mat puri don't see for this working properly so initially I will start with som this is it is the avengers us amazed when you are Visitor No's Slices Unbroken This Decided Lleyton Hewitt And This Next Person Self Delete Using Arduino Code Eastern Side Of Solid And Have Moved Over Again Why Give The Check Dion Check Is Form Tester Next Spent Is Equal To How Did Star Next Royal Look S Well as for in this case sutriya is not equal to for even no term digit avoid medicines in various languages ​​and to my next value the languages ​​and to my next value the languages ​​and to my next value the initial administrator in the survey is this but this course will not work because we need you also need to delete all the currency Of Tree Conditions Sow In This Case Is Not Have Been Able To Delete History For Browsers Urine And Fennel Avoiding Its Spot Weekend Tourism Can Give In To Variable Year Can Not Take Place Value Suite Is Equal To Hydrated Star Next Oil NRHM Giver Condition Hair In The Morning And condition inside of this they can give this side latest or extra oil ok what is this is equal to available ladies hunters equal to that value it will keep visiting elements there civil work and you will be able to delete all the currency of the element ok No Injustice Will Also Have To Give Condition Check Vibrator Don't Next Is Not Equal To Null Will Have To Give Perspective Developed Hybrid Star Next Is Equal To Null Day Not Only Mode Setting Null But Will Not Have Any Valuable American And Destined To Execute His Life In Solitude And Basically After 10 Acid Can Give Wealth Tax K Rate Or Just Also Idolators Worldwide Twitter Next 9 Wicket Shesh Tower Hydrate A Okay Love You Have To Give While Condition Is That Is Not Given Solar Water Heater Condition CID Latest And Next9 Also Nal No Veer Vidya Ko Acid Loop Condition Subscribe Tester Subscribe And We Can Do Kunwar Su Everything Is Given On Spelling Mistake It's A The Correct Spelling Mistake And Electronic Udan 500 600 Golden And Semi collar serpent and other interested also find no that this sweet spineless all social media censorship walking dead hua tha switch fine thank you for being patiently sunny please like these all
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,2,3,3,4,4,5\] **Output:** \[1,2,5\] **Example 2:** **Input:** head = \[1,1,1,2,3\] **Output:** \[2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List,Two Pointers
Medium
83,1982
77
So hello gas welcome tu de new video so in this video we are going to talk about let code 77 number problem which is its combinations so this problem also we are going to do with back tracking so why am I going to do with back tracking simple c The thing is, I came and saw the constant, okay, the constraint is very low, that is, it has been said, equal to 20, so whenever you see a very low stand, give like and less, equal to 30, etc., then you guys first 30, etc., then you guys first 30, etc., then you guys first think about back tracking, okay. And the second thing is back tracking, what does it mean that you have to do all the possible combinations to design the solution, so look here, you can also see the keyword that is all possible combinations, so I am going to apply tracking, so understand the question. Let's take it like in the question it is given that for and k = 2 so what to actually do is that we get = 2 so what to actually do is that we get = 2 so what to actually do is that we get 1 2 n so van tu n means 1 2 3 4 so 34 like this I have a number I take why I have 1234 So, using these numbers, I have to divide them into two sizes, like here the value of pe k is tu, so I have to get combinations of two sizes each. So you all must be seeing here that the first combination is van kama tu, the second combination is 13. After this, Van can be combined with Four, along with this, Van will have no other option, then my Tu can be combined with Delay and along with Tu Four, this is also available in two sizes. After this, there is no more pause belt, after this, actually we got three with four, how then I noticed one thing, if this 0 index is given, then this is 2 and this three is okay, so when the index of zero will combine with its index, okay. After this, when zero will combine with tu, in the same way, now all the options are over, then my story started from van, in the same way, van will also be combined with all its subsequent indexes and then finally tu will also be combined with three. Three will not be able to do it with anyone because now I have only one element left, so you guys are able to understand that till now we have seen the pattern either for loop or normal P K note pick, what have we done? Okay, so the same thing has to be done in this also, after zero, we have to explore all the indexes, just one next one is okay, so if I called recognition on zero, then after doing plus one, I called plus, then what? If there is a van with zero then it will visit the index. See, it will be seeing you here too. Now if there is a van with zero, the index will benefit. See, you got 2 meter van and you and after that there will be detergent. So when the van index will call you second in index. So I will get three, in the same way second one will get third, after this he will not be able to do but wait, what has happened is that we are simply traversing all the numbers, but after zero, here the content is given in seven forms. We have to upload only two numbers, which is clearly given here that we need only K = 2, like I have we need only K = 2, like I have we need only K = 2, like I have in my vector, whatever vector I have taken, if two elements come in it, immediately you get returned, you are fine. There is no need to store, the problem has become very simple, we simply apply the same formula which we have learned till now, so we do not need to call after two sizes, that means we have to make all the calls below. There is no need, why is it not simple because we will impose conditions, I have written the code, I did not write any big thing, I said that this is done, perform the operation, what operation do we have to perform, you have to identify three things and one Records C call just for the next index and one thing happened that when you are back tracking then you have to delete the current one and explore for the next thing. If the condition of back tracking is fine then the same thing happened, this is our zero first year. Second and this third index is ok I know the answer what will be its answer 1 2 1 3 1 4 after this 2 3 2 4 and after this 34 ok this is so much possibility I have the answer to be included so if I talked about That I have made 0% call, if I talked about That I have made 0% call, if I talked about That I have made 0% call, okay then what will happen, as soon as I have taken a vector here whose name I have also taken, okay this is a vector in which I am storing the answer, so here inside my brother A will go van ok then what happened then he said the record is zero why because I am starting to upload so what will be the value of idea here it will be zero initially for i = 0 this again and zero initially for i = 0 this again and zero initially for i = 0 this again and again till then its base case is not What is the base case? So when B.Com came back, What is the base case? So when B.Com came back, What is the base case? So when B.Com came back, well, why did I put I because I know what I had till now, I used to have some elements in it, okay, there would have been some elements in it now. They have elements, okay, I am starting from the van, it will tower on everything, that's why I have written here, so I have taken a, here I have van a, after this the next call will be made, okay, this one, so the next call too, so we are below, so I See, van for zero, as you all must have seen in the example, for zero, van was to go first. See here, for zero, van went to. In this, again it was put inside the vector, then van is the answer. After this, what do we have to do? Now after zero, after van, now after zero, we have to go directly to you. After zero, van and you do not go, we have to go back to AK, so I understand that here What will be the basis of payment, because dot size = this, as soon as my answer returns, I will see this statement, then when I am tracking from here, if I see this statement, then I will pop it will come out because when I track this You had come on pe, how did I see the vector earlier, that is why this van tu has been updated, it should become again van because now it has to come on three, okay this call has returned, so when I called 0 index again. It came here = First of all it was van, it was you, it was came here = First of all it was van, it was you, it was came here = First of all it was van, it was you, it was three, van for zero, you could have gone for three, okay for zero, however, van pe goes for van, then it was for you, but we already broke. We did it because we need only two sizes, okay, we did not come down, still we will get our answer, why is it because if we come down, then this vector of ours is temporary factor, this vector, its size will keep increasing, one is three, which we do not want. We only need the size, that's why we will not come down, what will we do, we will break us and there is no problem in our answer by not coming down, here we get the answer, why is it wrong, why will we always get the answer because you are already Here you can see like here you guys see 2 3 4 So see this further explore further for index or 2 we will scroll here now so once we will get the answer from here then if we go down and hope This must have been clear to you, so now when his call is completed, here we see the van. Now search the combination for van. Okay, so for van, he will go to three because now he cannot answer the touch anymore, so when he goes to three. Come again here, push one and three, then our base condition is hit, okay maybe one more equal, you are equal, so we further stored it in our 2D answer and returned. When someone returned again, what did we get on ? When we got again back, ? When we got again back, ? When we got again back, what did we do? Taking out these three, we could explore here like the next cork, he saw the van again and he made the next call. Again van four is ok van four so after doing this my point for zero is over all the calls so now it is over for zero will come on van ok then this will come on here my point now you What will happen if the van index wants to go to you and three, then here I am looking at this, then which will come, if you store three and three, then you will store 2. Here, I am still seeing you in the temporary vector of this. After again for visit, here 24 will be the answer, then it will come back, then my pointer will be picked up from here and will come here, then three four will come in my answer. In the same way, when my pointer will come back from here to the backtracker, it will be three here but from three. If he moves ahead then he will also take out the three in the same manner. Okay, in the back time, here he Okay, in the back time, here he Okay, in the back time, here he saw the MP factor, then what did he do again? He came back to the bio, he broke it again, there is nothing next after this. So this condition call of ours is also not saved, so when it comes back, then see that it will become vector again and all the calls are finished i0123 I have towered all of them, now here you will be seeing the power of 2. N our time complexity cannot be there, why would it be less than that, see what will happen in the first case also, you people know when it happens when we have to come out with the first combination, everything is dependent on this cap, right now the call seems to be for zero. Na look at this van and you explore, then it doesn't stop after you, it doesn't have a base seat because its value is allowed up to four, it also considers 3, I consider four also, Dan, if I had gone out after this, it would have been 1234. It is okay for us, after this when it comes back, 24 means only one combination is possible, you people will be able to see its mathematics formula, is there any other option other than 1234 to make the combination like this, if K is good for no, then its mathematics. The formula is N factorial N - K factor, its general formula, if I talk about it then you must be seeing the NNCK formula here and you will always understand one thing, time complexity is the same thing, see Vikarshan tomorrow to understand time completely. It is a little difficult, so you guys, whatever records formula is generated by mathematics, that becomes your time complexity, actually why because we can explore as much as we have derived that formula because the value of NCERT is so good. That I took out the shop for 44, then you must be seeing here that he is going in the loop only once, after this he will not be there for ever, so if he tells in time, then I hope it will be sensory, these things and see the template all. I need something, as I had discussed, I am doing the same template again and again, I just put a little condition, one cricket, here, if you want to explore something by doing all the subsets, then look, this template is less or more or less. If there is a thing then I hope you guys would have enjoyed this question and if you guys don't understand anything then we will try the combinations in this way. Combination Sam, after this Combination Sam two three, there are many more questions, try them. Okay, after this you have to do back break, if you pop the element, after this, if there is any variable added in it, then you will abstract it, that means you will just reverse it because you have performed it, you can do it and you will apply a base case after thinking carefully, so what am I supposed to do? And this Karsan tree is made in this way, so let's go, I hope you all enjoyed it. If you enjoyed it, you can like the video and subscribe to the channel. Let's meet again in the next video. Thank you.
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
1,342
okay guys let's go over 1342 number of steps the problem says given a non negative so the number is greater than zero integer number returned the number of steps to reduce it to zero so whatever number we have you want to reduce it to until we get zero and we want to count how many times it took if the current number is even okay even you have to divide it by two so if it's even divided by 2 otherwise you have to subtract one from it so otherwise meaning if it's odd you stop checked one ok example 1 we have an input of 14 right input is 14 right is 14 even number yes so what we do is we divide this by 2 and then we get 7 so 7 is odd so we want to subtract 1 and refer to say counties that we want since P divided by 2 and if since this is 7 is all we want to subtract 1 from it and then we get 6 which is even and count increases 2 and since 6 is even we want to divide this by 2 and then if we do that we get 3 which is odd and we increase our count by 1 and since 3 is odd we want to subtract 1 and we get to it just even increase our count to 4 and since 2 is even 2 divided by 2 is gotta be 1 which is odd count increases to 5 and says 1 is odd we want to subtract 1 from it and it gets you and count is going to equal to 6 so this is how we get a result ok first thing we're gonna do is clear the clear on our function number of steps which takes a number which is all integer and what we're gonna do is we're gonna make a count variable that counts how many times repeated our operations and we're gonna make a wallops so while the number is greater than 0 and you want to check if the number is even or odd right so is equal to zero so if the remainder of the number is zero we know that it's even what were you gonna do is we're gonna count increase the count by one and divide the number by two pi equals two all right now what if it's odd else so if it's odd we want to count the number by one or increase the count by one and then subtract the number by one and finally we want to return our result or return the count and we get our result zero six and four because let's go for our code one more time so with the car function number of steps which takes in a parameter which is an integer which means it's a whole number okay so we declare the count variable so that we know how many operations it did and then the data we returned that counter above when we're done with our while loop so be using all the while loop to check if our number is greater than zero so what if it's equal to zero it's going to automatically loop out of this while loop and then we turn the count of zero immediately okay what if it's not okay so number I mean example two says number is equal to eight right so count is initialized to zero and then if this is Scott check if the number mod 2 is equal to zero so mod checks for remainders right and if we mean there is equal to zero it means that it's even because let's say you have a try 8 divided by 2 is 4 there is no remainder is 0 so if remainder is 0 you want to increase the count by 1 and we want to divide the number by 2 so what we're doing here is basically resetting the number we're setting num to whatever result we get after dividing it by two so in this case it would be four and then go back to wild loop again so it's four greater than zero yes that's true is four even yes so it increased count again and then this time he resets num2 and it's gonna go back up to wild up again so it's two greater than zero yes if an equal to our first obtainment if number is even is it even yes two is even we're gonna increase our count by one again then we set our num to zero and we go back up to our while loop again it's 0 greater than zero no so we exit out of this while loop and we turn our count so for this one it goes numb there's equal to four count is one and then next loop norm is to count is two is numb it's gotta be one actually made a mistake here it should be one here and count is going to be 3 because to point to D by 2 is 1 not 0 I made a mistake there so it's got check is not 1 greater than 0 and it goes to first if statement is 1 the piece of pie by 2 no it's not even as odd so it goes to count and the it decreases is the number by 1 now we get 0 and then we return our count variable because we check as 0 greater than 0 no it's not so we do parameter count so here nam is going to be easier then we return count which is 4
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
3
hi guys hope you're doing great today's question is longest substring without repeating characters it's a medium level question and one of the top like problems on decode so the question says given a string find the length of the longest substring without repeating characters substring means we cannot have permutations and combinations of the characters in the given string it has to be like a substring of the given string so for example if you look at ABC B be the longest substring here is ABC which does not have any repeating character ABC being distant bbbb these are all the same characters so the maximum length of the desired substring is 1 and the last example is PW w ke W so W K e or ke w could be the longest substring here with three distinct characters alright so I think the problem statement is pretty simple let's think about the various approaches we can take so these are the approaches that I have witnessed till now and all the problems that I've done to solve any question on a string I request you pause the video think for a moment about what the approach could be and come back alright so I think we have a very clear winner here because we are already stating this as an example for the sliding window now if we look at the problem when brute force solution could be for us to find all the sub strings of this string right starting from a so a ABC ABA then the same way starting from b CP c a b and so on but that is definitely not an efficient solution so we need to think of something else in sliding-window is the answer if this sliding-window is the answer if this sliding-window is the answer if this question is basically a classic example of a sliding window approach question right so what we would be doing is that we would be maintaining a window where we desire to maintain all the characters unique right and just as we find a character repeating while traversing the string we start shrinking the window from the start so we will maintain two endpoints of the window one is the start and the other one is the end right and we keep them at the start of the string initially and moons end one by one character of the string and keep comparing it with whatever characters we have seen till now just put them in a collection for example a hash set and as long as we are getting unique actors we keep moving the end and just as we find a character that has already occurred in the past we start moving our star pointer right to the point where we find this repeating character okay so for example in ABC we keep moving our n till C and just as we move it to a we know that a has already arrived in the past so we check our start now in this case start is already pointing to a so we just moon start and we also move the end to B so now we will have BC e which will be again distinct so this is the whole idea and along with that we would also be maintaining a current length and a maximum length so that we derive our answer at the end okay so I think once we start implementing it would get more clear hopefully so as we discussed we would need a start okay we would need an end we would need a current length and we would need a maximum length which let's say we just call it minus one right now okay so now we won't keep moving until our string is not exhausted right so we just say that till end is less than s dot length okay now let's just capture the character at hand so let's say it's current so current equals to s dot sorry correct and okay now so as I was mentioning we need a collection to capture water characters we have seen already so let's just create a hash set of characters okay equals two okay so first we check here if our hash set will take a simpler one first so if the hash set does not contain the current character we simply have to add it to the hash set right so hash it's hash set dot add current okay and we move our end pointer by one okay so you just move it now otherwise it means that our window is having a character that's repeating now so we won't do as we were discussing we want to move our until a position where the start character and the end character are the same that is the repeating character is funk right so what we do is that first of all let's just check for our current length because okay so I think every time we do this let's also calculate the end minus start so what we're doing here is that every time the we move our end we recalculate our current length of the substring that's because we might no not know that in the next iteration our character would be a repeating one and that's when we might want to like check on our maximum length captured till now and update it if the current length is more right so that is the reason we capture it every single time and then we just check that if this maximum length is less than the current line is just updated okay fine so now our hash set contains that right so what we do is that we just want to ensure that our start does not let go beyond end right so because we'll be like moving forward our start right in search of this particular character so we just say that while my start is less than equal to n right and obviously we also don't want our end to go anywhere beyond the length of the string so these are always safe checks to put in whenever you're dealing with pointers you can just put these checks and be sure that the code is not going to misbehave right so let's just do this and now if my character at start okay is not equal to my character at end okay so what we are trying to do here is that let's say for example in pww ke w this example right so what we would do is our n and start would be at P we would move the end P would not be in the hash that we put it in the hash set over here calculate the current length which will come out as 1 then move to W which would not be their current length would come out as 2 and then we arrive at W which will again at be a repeating character so we'll come here update the maximum length by 2 because PW that's the length of the substring gets captured and then what we do is that we start moving or start okay which is at P so we move it until we find a W right so we find our starters here and our end is here so unless we are not finding the W we are shrinking our window and that is why we don't want these characters to be a part of the hash set anymore right so what we do is we just remove them from the hash set because we don't want these characters to be in the hash set because these might occur in the substring later and we want to keep them afterwards right we don't want them to be like repeating characters so that is the reason that we just do a remove okay yeah so you just do this okay so whatever characters that start we just to remove it and then we just move forward the start okay understood of that where it was right otherwise right now we have found this character which was which is repeating in the substring right so what now we need to do is that we just so there is no point in removing this character from the hash set first and then I it again because it will still be a part of our current substring so what we do is we just let it stay in the hash set simply move the start from that character to the next character right so that character is like gone from our substring and also move our end because we have processed this repetition right so we just basically do this okay and we break because we have basically fixed the repetition we have shrunk our window resized it and now the current window doesn't have anything repeating right so we just break this particular thing right and you know okay so now once this is done now there are some things that we need to consider here and keep in mind that it is possible that there was one repeating character and after that there was no repeating character for example if you see pww and then let's say it would have been ke hm right so in that case it would never enter this else and maximum length will never get updated however our current length will get updated it with every encounter coming so that's why to just handle those we just check this after we exit the while loop to make sure we are not missing out on something like that right another thing is that our string could basically contain all characters as distinct right it could be abcdefgh in that case our heart set would always contain basically distinct characters it would never enter the else and that's why I wish this max length would be minus one it will never get updated so what will do is that if this is equal to minus one it means it never got updated and we will just assign it the length of the strength okay and yeah and then we can safely return the maximum length okay let's see this grunts okay so we get the desired on so let's try it submitting it great okay so the solution works and talking about the time and the space complexity so I think since we are like just traveling the string once it would be off end right because we do have a little bit of a repetition but it would be just a maximum of twice of n not n square so we can safely say that it's like 100 of 2 into n which will be basically off n but it is pretty good and the space complexity would be so if you see this hash set would contain maximum whatever is the size of the character set so let's say if we say that it would have only alphabets and numbers and it would be maximum of 256 otherwise it would be the number of distinct Erik ters in the string so whatever is the minimum would be the space complexity of this solution so I hope I have been able to explain this problem and if you really like this video please like share and subscribe keep coding and take care guys
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
167
hi today i will be solving a follow-up hi today i will be solving a follow-up hi today i will be solving a follow-up to the two-sum to the two-sum to the two-sum problem this algorithm is essential in implementing the optimal solutions to another two popular interview questions three sum and four sum all right let's get started given an array of integers that is already sorted in ascending order find two numbers such that they add up to a specific target number you may assume that each input would have exactly one solution and you may not use the same element twice here's an example the target is 8 and we're given numbers minus 1 0 2 4 6 and 10. if we scan the array we can see that 2 and 6 add up to 8. and notice that if we add 4 to itself it also adds up to 8. however the problem specifically states that we cannot use the same number twice therefore this can't be an answer so the answer here is two and six the output should be an array with indices of the matching pair plus one so in this case the indexes of the matching pairs are 2 and 4 so the output would be 3 and 5 since 2 is the third element in our array and 6 is the fifth element in our array we can solve this problem by finding all distinct pairs of numbers in our array and seeing if they sum up to our target this can be implemented programmatically using a double for loop however if we use a double for loop our time complexity will be o n squared which is not ideal we can actually do better we could solve this problem in linear time using process of elimination if we were to take the very first element and the very last element in our array sum them together and compare them to target we would get either one of these cases either the sum will be smaller than target greater than target or equal to the target if the sum is equal to the target then we are done we have found our solution for example in this case when we add we get that the sum would be equal to 9 which is greater than the target so we are dealing with this condition if we were to take any other element and sum it with 10 we would get a number that is larger than the sum of the very last element with the very first one that is because all the elements to the right of the first one will be bigger than it so we will get a bigger sum so just with one comparison we already know that no matter what pair we take with 10 it will not give us our answer so we can eliminate 10 as a viable option so i will write here eliminate last element then moving on to the next step i will once again compare the first element with the last one in our modified array so the sum of -1 in our modified array so the sum of -1 in our modified array so the sum of -1 and 6 would be equal to 5 which is smaller than the target so in this case we are dealing with this condition when the sum is smaller than the target i can conclude that if i were to take the very first element and sum it up with any other element in the array it will be the sum will be smaller than the sum between the first element and the last element that is because the last element is the largest element in our array so a sum where one of the elements was replaced with a smaller element would of course be smaller once again it was just one comparison i'm able to find out that no matter what hearing i pick with element minus one in the modified array i will not get my target answer so i can eliminate the first element from the array of viable answers so i will write eliminate moving on to the next iteration i will be comparing 0 and 6 so my sum will be 6 and once again i'm dealing with the case where the sum is smaller than the target since i know that no other pair with 0 in my modified array would sum up to the target i can once again eliminate the first element and i would update my starting pointer to be a two and finally two plus six is equal to eight which is precisely equal to the target so this is my solution and i am done so using this method of iterated elimination i am able to solve this problem in linear time how can we implement this solution in code we could take a recursive approach where we would pass the modified array into our problem over and over again until we finally find an answer however this would take linear space complexity since each function call will require extra memory so optimally we would take an iterative approach we could label the bounds of the modified array with two variables upper and lower and then as we work through each iteration we could update our upper and lower variables to denote the bounds of our modified array now i will code up my solution first i will change this to arrow function syntax okay i will need my bounds for the array of viable answers i will have lower set to zero and upper set to numbers.length minus and upper set to numbers.length minus and upper set to numbers.length minus one and then i can just go through my loop while upper is greater than lower while i still have two elements in my array i will compute the sum first so then if some is smaller than target i will eliminate the first element by moving my lower bound to the right and this can be a chip by adding one else if some is greater than the target then i want to eliminate the last element from my array so i will subtract one from upper and for the last condition else if the sum is not smaller than that target nor is it larger than the target then it must equal to the target so in this case i have found my answer so i will return the indices and now i am done writing the code then submitting it i get that my solution has been accepted so this solution runs in linear time and constant space and now you are ready to go on and solve three sum and four sum i hope this was helpful and good luck with your studies
Two Sum II - Input Array Is Sorted
two-sum-ii-input-array-is-sorted
Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. Return _the indices of the two numbers,_ `index1` _and_ `index2`_, **added by one** as an integer array_ `[index1, index2]` _of length 2._ The tests are generated such that there is **exactly one solution**. You **may not** use the same element twice. Your solution must use only constant extra space. **Example 1:** **Input:** numbers = \[2,7,11,15\], target = 9 **Output:** \[1,2\] **Explanation:** The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return \[1, 2\]. **Example 2:** **Input:** numbers = \[2,3,4\], target = 6 **Output:** \[1,3\] **Explanation:** The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return \[1, 3\]. **Example 3:** **Input:** numbers = \[\-1,0\], target = -1 **Output:** \[1,2\] **Explanation:** The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return \[1, 2\]. **Constraints:** * `2 <= numbers.length <= 3 * 104` * `-1000 <= numbers[i] <= 1000` * `numbers` is sorted in **non-decreasing order**. * `-1000 <= target <= 1000` * The tests are generated such that there is **exactly one solution**.
null
Array,Two Pointers,Binary Search
Medium
1,653,1083
548
let's go to question number 548 split already with equal sum this is medium question let's get into it kevin array with an integers you need to find if there are three fleet ijk which satisfies following condition first i must be bigger than zero and then j must be bigger than i plus one and then k must be bigger than j plus one and then smaller than minus one second sum of the sub over a zero comma minus one i plus one comma j minus one j plus one comma k minus one and k plus one comma m minus should be equal where we define the sub array l comma r represent or slice of the original array starting from the element index it added to the element indexed okay let's check the example let me cut p if you can put it here and then you also need condition first condition second condition okay so let's check the example now one two so let's see i must be bigger than zero right so that must be zero one two three four five six okay let's pick other one so it start from i here then j most people call i plus one bigger so j is three and then k is j plus one because okay this makes sense okay cool so in this case subway sum jump my minus what is zero i minus one and is next is i plus one is here and the j minus one is here so this one next j plus one here k mass one is here final k plus one and minus one so if this value is same one yeah we need to delete it that makes sense okay i'm gonna use the ijk so logic is the same as this one i'm gonna start from here and then i'm gonna make the j range k range and then i'm gonna try to luffin luffy roof and then if i find the uh the summary song is this sequel i'm gonna return to otherwise later first at this time i think if we use pro process and first so because we needed to do k and they have to finish it we also needed to small roof to calculate support sum let's say k length of here is we also need to calculate it so we need to iterate this one but if we use uh plus three pics so that is learning song maybe you could reduce this one is three and then but we also needed to split in your space for graphics so we're gonna make some prefix one three four six seven nine ten maybe we easy to calculate the range in this case range is i minus one and then j must be j minus one minus i so one k minus one minus j one so the last one minus k so one then we can calculate the uh sum of sub subway with constance so we just need uh and cube opening okay can we make the better please yes we able to use roof in loop first hash set plus learning software learning some processes and this time complexities we go and scale this basically okay my approach is first this one is thing and then first i'm gonna select j first so the minis for j in and then i loop i in and then i make one is the first is already and then there's a great two subarray and if one and two is the same i'm gonna put sinister set put into the sea one so in that i finish the loop and then this time here let's make the another cane and then make quick with some of the insert and therefore and if three equal force m three in sin i gonna return two otherwise if i cannot find this first the legion the yeah that's right so actually the scene is some kind of bridge with the two iteration if we use the scene don't need it to make looping because first belly this i'll be able to put here and then this value is the same as this one that is the point we needed to return that this makes sense so we're gonna use this one okay for a second i make crazy see prosperity is not first value non-zero prosperity is not first value non-zero prosperity is not first value non-zero and then i'm gonna do my range one two rings nice so then this is hand see recently some us quite well so we made some and that's insane so what is go for j is the three light so of course i must be okay this is good must be here let's jk so i need to take it bigger than three so range star three and then what is finish so in this case this is one two three four so sum is negative four thirty three two one this mean is thanks minus this part right minus one so this one must be included so this one is not so this one is that and if we had the ranges here that means this one is not included that this one is liquid because this is the excursive so i'm gonna put lengths minus one okay and then let's make i must be integer bigger than one right so it starts with a one two j minus one that just makes sense j minus one this is j minus one and then here so one must be acc i minus one in this one right and then he must be j minus one minus i this one minus this one so cc j minus one minus i c i okay and then that's my k r three range is r j plus two of course this is g plus one and then this is j plus two comma k minus one minus acc j that is q minus one and j the final is this one that is length h is minus one minus k this is c minus one and it says this is a k so three fortressing okay looks good okay let me type check that type of things isolating one two let's collect them apparently this minus one knowns minus one i okay cool challenge what's my answer taylor indian solid yeah this one is not good so t must be minus three so this one is the j maximum range oh no this minus 4 because this one needs unique root so this is all here is correct this is -3 and then okay range of i is j minus one correct and then k is the j plus two minus one here okay correct three a k j minus k looks okay awesome thank you
Split Array with Equal Sum
split-array-with-equal-sum
Given an integer array `nums` of length `n`, return `true` if there is a triplet `(i, j, k)` which satisfies the following conditions: * `0 < i, i + 1 < j, j + 1 < k < n - 1` * The sum of subarrays `(0, i - 1)`, `(i + 1, j - 1)`, `(j + 1, k - 1)` and `(k + 1, n - 1)` is equal. A subarray `(l, r)` represents a slice of the original array starting from the element indexed `l` to the element indexed `r`. **Example 1:** **Input:** nums = \[1,2,1,2,1,2,1\] **Output:** true **Explanation:** i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1 **Example 2:** **Input:** nums = \[1,2,1,2,1,2,1,2\] **Output:** false **Constraints:** * `n == nums.length` * `1 <= n <= 2000` * `-106 <= nums[i] <= 106`
null
Array,Prefix Sum
Hard
1678
989
hey everyone welcome back and let's write some more neat code today so today let's solve the problem add to array form of integer so we're given the array form of an integer num for example the number 1200 would be represented in an array like this is the array form of that integer each digit is going to get its own position in the array so the most significant digit is going to be all the way to the left the least significant digit is going to be all the way to the right in our array we're also given an integer K in this example let's say it's 34 and we want to take this integer K and add it to the array form of this and then return the new array that would be the result so in this case when you add 34 to 1200 we get the integer 12 34. then this in Array form will look like this 12 3 4. and then that's exactly what we would return so there's multiple ways to do this we're going to be focusing on the most efficient way and even then there are multiple ways to do it the most obvious would be just to take the array and then convert it to an integer and then add K to it because then we don't even have to worry about this being an array we can just add two integers together then get the new integer which would be 12 34 and then take this and convert it to an array that's not too difficult but we're going to be doing it a bit differently we're just going to do it in place because I think it's more interesting so with something like 34 we would want to start at the least significant position and with this integer the least significant position here which is the four then we want to take these digits and add them together we get four and then we want to put that 4 in this position so now we're going to have a 4 here then we're going to take this pointer and increment it to be over here now in the next position over here you could say we want to increment the pointer but an even easier way would be since we're never going to need this digit we could just chop it off how do you chop off a digit well with 34 we can divide it by 10 and round down we would get a 3. we'd basically be getting rid of this digit every time you divide by 10 and round down so that's integer Division and python we need two slashes but I'll leave it like this so instead of Shifting this pointer we're just going to get rid of this and then by default we'll be at the first integer again and now we're going to do pretty much the same thing we're going to take this and divide it or mod it by 10. that's how we're getting the least significant digit anyway when we take 34 and we mod it by 10. that's how we're getting this digit so we would get four we're dividing by 10 and getting the remainder this is a pretty important bit operation well I wouldn't call it a bit off operation but an integer operation and now instead of having 34 we just have three modded by 10 which is going to give us a 3 in the output so 3 is the digit that we want to now add to this position so we'll be replacing this with a three and now we're done this is our solution and we can return it and this is pretty much how we're going to be solving the problem but we're going to make a couple slight changes here because with this really simple example we didn't go through a few of the edge cases a couple would be what if our K number is even bigger than this number in that case instead of just overwriting some of these positions we might have to actually append to the array we might need to add additional values the way we're doing this what if instead here we had 34 000 well in that case these three zeros wouldn't do anything here this 4 would change this one to a five and then this lasts 3 over here would need to go over here the only problem doing it this way is if we have to add new digits inserting at the beginning of an array is an O of n time operation we don't know how many times we might have to do it if this is a really big integer we might have to do it quite a few times that's not going to be super efficient we can instead take this and actually take the original array and reverse it so it would actually be written like this which is kind of confusing when you're looking at it drawn out it would be drawn like this and then when we need to append the three we would just append it on this side and then afterwards once we've built our entire result then we'll take this array and reverse it again and then we'll get something that looks like this well we'd have the 4000 added here but you get the idea that this is going to be in the correct order by the time we return it but for an intermediate step we are going to reverse it so that when we append new values we'll be appending to the right side of the array which is normally a constant time operation now the last little trick that you have to worry about is what if we have a carry value we don't with this example but taking this and changing it to be a bit more interesting what if we actually had 3 900 that we're doing well we would take this array and it would look like this when we reverse it we would go digit by digit so we'd take this mod it by 10 to get the zeros Place well the ones place and then we'd add that here well it's still going to be zero then we'd chop off this guy look at the zero here and our pointer would be over here we'd take these and add them together well it's still going to be zero so nothing different here we'll chop this guy off again and now our pointer will be over here we're going to take this 9 and add it to the two well when we do that we get two plus nine which is equal to 11. so 11 is definitely too big to put in this spot so what we're going to do to it is we're going to divide it by 10 because we know in real math there would be a one that goes here and then another one that's going to go in the carry position over here so that's what we do we take the resulting number which is 11 I divide it by 10 and that will give us the real integer that we should put over here now before we actually divide it by 10 we would want to mod it by 10 11 modded by 10 would give us this value which is 1 and that's the value that would actually go in this position 11 divided by 10 is what's going to tell us the carry value in this case both of them are 1. so now we would have a one here our pointer would be over here we would chop this off but I guess what I didn't say is where are we actually going to store that carry we know this one is going to overwrite this but what about the carry we know it should be added over here but should we do that immediately where do we store that before we actually get to this position well the easiest thing here is since we already know this three is going to be added over here we might as well add this one to this value here so we'll add one to it and then we'll get a 4 over here that works because we're continuing this addition until this guy is zero until we've gone through every digit so even if we overflowed this like we added another one or we or this was maybe originally a nine and we added one to it now it would become a ten like if this is nine and we add one to it now it's a 10. it doesn't matter because we're only looking at this digit by digit we're going to look at the zero now and then on the next iteration of the loop we would look at the one so it will work out for us in all cases in this case though it's going to be a 4 so let's consider that case we're taking this 4 adding it here to this one that means this is now going to be a five there's no carry here and we'll chop this guy off we've already gone through our pointer here will now be out of bounds but it's okay if the pointer is out of bounds because what we're deciding on how to stop is this guy over here but now since we've gone through every digit over here we are going to stop we've basically completed the addition here we ended up with 50 100 well we would take this and now reverse it which would be 5100 and is that what we were expecting well we took 1200 and added it with the value here which was 3 900 and yeah that looks right to me 5100 is what we would expect and we did this in O of n time because well I guess o of n could be whatever the upper bound is of how many digits the value num has and how many digits the number K has so now let's go ahead and code this up okay so the first thing I want to do is take our num array and reverse it and I'm going to have a pointer I which is going to tell us the digit that we're at in our num array but that's not going to decide how long we continue our loop we're going to continue while K is non-zero so then we continue while K is non-zero so then we continue while K is non-zero so then we want the digit from K that we're going to add to our num so we just take K and mod it by 10 giving us the remainder will tell us the digit now normally what we would say is at num index I we want to add to it the digit that we just got but we can only do that if our index I is in bounds of the num array so in this case we can do that in the other case if I is too big that means we've gone out of bounds then we want to append to this array that digit that's mainly what we want to do but now don't forget to do some of the updates and also don't forget to keep track of the carry what happens if num of I is too large how do we know if there's a carry well we take this value and divide it by 10 that will tell us the carry if it exists if num of I is less than 10 then this will be zero anyway and this is integer division in Python that's what double slash means here so we have our carry and at that point we should probably also take num of I and mod it by 10 because if it is bigger than 10 then we only want to keep the ones play so for example if num of I is 12 and we mod it by 10 then we're going to get 2. we only want the ones place now if it's less than 10 so if it's 2 and we mod it by 10 it's still going to be two so we're not losing anything that's why we're allowed to do this and we don't have to wrap this in like an if statement or anything like that so this is a required operation now remember what we're doing with that carry we're just going to add it to K so let's go ahead and do that but also remember what if K here was 34 and our carry is equal to one then we don't want this to be 35 because remember we want to chop off the digit we don't want to ever reuse that digit so we want to chop this off and then add the carry so it will result in this case four so before we add this carry here let's make sure to chop off the ones play so we can do that by dividing K by 10 just like we did kind of over here and then we will add the carry to K also don't forget to increment your eye pointer so up we'll do that I plus equal one and that is pretty much the entire algorithm so now before we can return our num we have to also reverse it so I'll do just like this whoops I did not need to index num here when we're appending to it hopefully you caught that earlier sorry about that but as you can see yes it works then it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a ton of free check out neatco.io it has a ton of free check out neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Add to Array-Form of Integer
largest-component-size-by-common-factor
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num = \[1,2,0,0\], k = 34 **Output:** \[1,2,3,4\] **Explanation:** 1200 + 34 = 1234 **Example 2:** **Input:** num = \[2,7,4\], k = 181 **Output:** \[4,5,5\] **Explanation:** 274 + 181 = 455 **Example 3:** **Input:** num = \[2,1,5\], k = 806 **Output:** \[1,0,2,1\] **Explanation:** 215 + 806 = 1021 **Constraints:** * `1 <= num.length <= 104` * `0 <= num[i] <= 9` * `num` does not contain any leading zeros except for the zero itself. * `1 <= k <= 104`
null
Array,Math,Union Find
Hard
2276
448
all right so welcome back and this is question 448 and it's called find all numbers disappeared in an array and so for this question we are given a nums array and in this case we are given an array of length eight and so the question wants us to go through this array and find all the missing or disappeared numbers and so in this case we want to consider all the numbers between 1 and n where n is the length of the array so we would be considering from 1 to 8 in this case and so we see here that in this array the values five and six are missing between the numbers one and one to eight and so if we look through this array we see that all of the values from one to eight are here except for five and six and that's because well three repeats twice and then two repeats twice so there's two missing values and that happens to be five and six so if you look at a smaller case where we're given a range from one to two since this has a length of two and we see here that one appears but two doesn't appear and so 2 is the missing number that doesn't appear in this array okay so to do this one nice thing about java is that although we're past like a static size array we see here that they wants to return an arraylist and so it's a bit of a hint to actually use an arraylist when you're not past one and so that's immediately what i did so i saw that hint and i took it so we're going to have an arraylist of type integer and we'll just call it output and we'll return that at the end of our method great and so the next thing that we're going to do is use a direct access array and this is a very popular data structure especially for string type problems where you want to increment whenever you see a specific character like you saw the character a before and so you might do something like you know this is your array here and we want to do say this is your string dot character at i and so and this is in a forward that's why we're using i and so this would iterate and say okay we've seen this letter before and we want to increment by one and so whenever you go to the index of that letter's integer value in your array you can see whether or not you saw that letter or not but it's a constant time lookup uh data structure so it's really useful for all these easy problems so we're gonna be using that here and so we'll create that so it'll be an integer we'll call this just uh appeared new int oh and so this is going to be of the same size or of the size of the nums array plus one and so what this is doing and you probably can infer by the name of the array here is that we're going to be iterating through this list and say for the value 4 then at index 4 of this array we'll increment it whenever we see it and so by the end all the values here in this table will be if we took that value as the index in our array and increment it then if we look an array at that index we can tell if we've seen that number or not if the value is greater than zero that doesn't make much sense it will make more sense as i go but this plus one here is so that we can consider the value eight because this is only from zero to seven and we're not even going to consider the value at the index of zero and so we want to consider from one to eight in this case it'll be zero to seven so it's just how i implemented it and so we're going to populate this appeared ray with a for loop so for each value in our nums array we'll loop through those values and if or no we'll just increment whenever we see that value so we take our appeared array at the value of i it will increment it and so say for this value four then at a period four it'll be incremented to then one right and so by the end of our array for say the value three then at the index location of three it'll be equal to two because we incremented it twice here and here so that means that well then appeared at the index of five will be equal to zero since we never incremented it while iterating through this array so then what we're going to do is we're going to iterate through the values of the superior array and wherever it's equal to zero we're going to append that value to our output arraylist so to do that we'll be iterating through the length of this array plus one once again because we're doing it here this one and then we'll check if appeared at i is equal to zero then we'll append it to that output array and so one little caveat that we had to handle here is that we're not considering whether or not we've seen zero or not because we're just considering one to n and so we don't want to say yes we've seen zero or not if this was zero to n then we'll include it but in this case we set it to one great so i think it looks okay we'll try running it oh let's see here nums.length so that's just because i nums.length so that's just because i nums.length so that's just because i added brackets but in array you don't need brackets that's only if you want to see the length of a string let's try that again accept it and let's run it awesome and submit it so this is actually a pretty optimal solution it's uh only three milliseconds and it's faster than a hundred percent so uh simple solution but it seemed to work really well and then the memory usage is less than 88 so it's actually if you looked at uh the uh here it's uh very performant so yeah i hope that helped and good luck with the rest of your algorithms thank you
Find All Numbers Disappeared in an Array
find-all-numbers-disappeared-in-an-array
Given an array `nums` of `n` integers where `nums[i]` is in the range `[1, n]`, return _an array of all the integers in the range_ `[1, n]` _that do not appear in_ `nums`. **Example 1:** **Input:** nums = \[4,3,2,7,8,2,3,1\] **Output:** \[5,6\] **Example 2:** **Input:** nums = \[1,1\] **Output:** \[2\] **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= n` **Follow up:** Could you do it without extra space and in `O(n)` runtime? You may assume the returned list does not count as extra space.
This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think counters! However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution. The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?
Array,Hash Table
Easy
41,442,2107,2305
956
hey everybody this is Larry this is day 24 of difficult day challenge hit the like button hit the Subscribe button drummer Discord let me know what you think about today's poem 956 tonis billboard it's okay yeah I'm still in this bin I'm just hanging out uh yeah let's check out this car oh ah man okay so install billboard you don't have the largest height the boat will have two still supportive on each side you support must be you go right so your collection watch take a few videos together so you have one two three six okay so you're trying to figure out basically two numbers that uh okay yeah I mean I think this is dynamic programming generally speaking and there's something some of the words um going up to 5000 actually proves it because then now you can just well do a DP on 2500 uh do we have to use all of them doesn't seem like we have to use all of them so yeah so basically so yeah so there are basically a couple of ways to do it but oh sorry man I'm just struggling with just sneezing right now but basically hmm oh wait n is equal to 20. I actually missed that what does that mean for me I'm going to DP in a couple of ways so n is equal to 20 then you know three to the 20 is going to be a little bit too slow um being you know part of a part of B and then part of just not uh item one so yeah um also the thing that you can do is that you can keep track of the dowter instead right because if the Summit is up to five thousand maybe that's good enough right so let's kind of write that and give it a try so then you can maybe just say I don't want to say it okay so let's say you have definitely oh man I'm sweating just sitting here just kind of uh all right yeah so let's say we uh some index I'm not the current sum or something like that total say right what does that mean so then now you have two things you can uh three things that you can do right so you can use this as product a or the left side or whatever it says so it's total plus parts of index and then you're gonna use this part of B something like this foreign right um so those are the three choices that we can do it's almost very consistent I think we find so Yeah so basically if total is equal to zero I guess yeah say n is equal to length of what if index is a good end and this is just being once we calculate all of them the total is equal to zero then we can return zero Maybe otherwise we return some negative value Maybe um yeah and then here we can just add lots of index and then now we return the max of these way foreign if we make one contribution to the left and that just somehow does a way to get back to zero on the left side or on the right side so that the doubt is zero then we get use this as part of the final calculation um and that should be pretty much it though this is very awkward looking and of course like this one uh and of course this isn't uh good enough fight yet by now because of you know it'll timeout for any reasonable amount of things so let's uh let's cache this right so what is index can go from 0 to end and total can go from zero to someone could go up to five thousand so we'll just say five thousand and maybe we can make an optimization here as well right being that if total is less than zero then we can return calculate a syntax negative total so that we make it positive for symmetry reason it doesn't matter which one is left and which one's right so we can do it here and then for and then now we just add the caching right uh so yeah and why is only up to why that's only 20 that's I think that just brought them a little confused about maybe but that's fine perfect oh I just wait Max is Max sum is equal to say sum of rods so then now you can do this cash is equal to none times this and then now you all you have to do left is just using the cache right and that's pretty much it as we can see it takes n to five thousand times so it's a pseudo pop now uh pseudopolynomial algorithm uh DP so yeah um that's all I have for this one let me know what you think stay good stay healthy do it mental health I'll see y'all later take care oh wait I should submit this first oh schnapps all right well that was unexpected I'll put four expected six why did I only get four maybe I can do this optimization then we could do another one right if Toto is greater than maximum uh over two so then we can return negative Infinity otherwise we can just use this Plus maximum over 2 or something like this to handle the negative numbers maybe the negative thing kind of screwed up with this so we can kind of take a check um yup Maybe hmm by optimizations a little bit weird of course you can also just cache it the normal way with caching or something but uh wait here then maybe zero you go to oh excuse me maximum over two so maybe just like don't do okay and this is why you would have a library for some of these things yeah it should be okay but maybe press one maybe I'm just like well if I have one somewhere oh but actually somehow that was true all right well yeah made a silly thing so the idea here is just to keep the caching index positive that's why we added to Delta so that when you have negative to 2500 say you add to um the middle thing so that it adds it back to zero that's basically the idea uh yeah that's right for today and let me know what you think stay good stay healthy do your mental health I'll see you out later take care bye
Tallest Billboard
number-of-music-playlists
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`. Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`. **Example 1:** **Input:** rods = \[1,2,3,6\] **Output:** 6 **Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. **Example 2:** **Input:** rods = \[1,2,3,4,5,6\] **Output:** 10 **Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. **Example 3:** **Input:** rods = \[1,2\] **Output:** 0 **Explanation:** The billboard cannot be supported, so we return 0. **Constraints:** * `1 <= rods.length <= 20` * `1 <= rods[i] <= 1000` * `sum(rods[i]) <= 5000`
null
Math,Dynamic Programming,Combinatorics
Hard
null
269
foreign hi my name is Jasmine and welcome to another tutorial today we're going to be going over a problem called alien dictionary from leak code it is classified as hard and was asked by many big tech companies such as Google Amazon Airbnb Uber and many more so let's start with reading the problem description so we have a an alien language that uses the English alphabet and the problem here is the order among the letters is unknown to us so basically means that in English we might have a and then B and then C but in this alien language we don't know the order of these letters it could be C and then um B and then like a it could be the order of this alien language now we're given a list of strings from the alien languages dictionary so where the words are sorted um legs are sorted lexographically by the rules of this language so we have to return um a string of the unique letters in the alien language stored in lexographically increasing order so we're given a set of words let's and I'll explain it in the algorithm section what it all means but for now let's just say we all we want to do is we want to find out the lexographically increasing order which is like this it could be something like this in this alien dictionary language so we want to find this in English in regular English we have a b c and that's the electrographically increasing order um and if there's no solution we return an empty string if there are more multiple Solutions we can return any of them so a string s is lexographically smaller than another um then string T if at the first letter where they differ the string s comes before the letter T so for example if we have let's say s a and then like B a in this alien language because s the first letter comes before the first letter of the second word um and the lexographically order increasing order we have S and then B this is what it means and if the first letters are the same let's say we have S M and then we have SC so if the first letters are the same we're gonna have to check the other letters here the second letter in each word and compare it so M comes before c then in our Alexa graphically increasing order a string we have to return it should be like this something like this now there are a couple constraints uh we the words length the length of the array that we have is between 100 same with each word's length and the words are consist of only lowercase English letters so for this problem um and I'll show it with an example what do what kind of algorithm we'll be using and the concept we're going to use for this problem is a topological sort and I'll explain it in the algorithm section as well so let's actually get into the next section okay as I explained in the previous section we're going to be using a concept to in this problem called topological sort in order to sort the letters of the alien language and in simple terms it means a directed acyclic graph is a linear ordering um vertices such that for every directed Edge like you and V U comes before V basically and you'll understand exactly what I mean with an example that I'll be going through right now so let's say we have um this list of words and we want to find out what's the ordering of the letters for this alien language now it is sorted in lexographically increasing order all of these Awards so first Simplicity I'm going to convert it to a graph like this and as we can see wrt comes before wrf and so on now what we're going to do here we want to find out the order of letters as explained in the problem section we have to first compare the first letter of each word with its next word so first things first we're going to compare W with W they're the same so we move on to the next letter it's R and it's also R in this one as well now this one is T and in the next word it's F so right off the bow we understand that t comes before f now let's do that again with wrf and EA so here we have wrf and EA so the first right off the bat the first letters in each word are different so meaning that W has to come before e now um if I want to compare we with W with er sorry um the E's are the same so we Skip and move on to the second letter A and R so meaning that a comes before r um excuse me so we have a that comes before r now here in this section we have ER and ett well of course the E's are the same we compare R and T R comes before T here and then with this last letter we compared to the last word and here we have e and r so meaning that e comes before R so we connect these two graphs and we have this F here that comes after the T so we added here as well we add it to f so this is our graph this is the graph that we get let's actually I actually created a graph here that's simpler and way more needs so let's actually remove all these problems this is the final graph that I draw here that I drew here this is the final graph all right so now that we um found the answer what is the found the created the graph what's the answer for this problem we need a string that has all the letters in the alien language and topological order sorry and increasingly lexographically increasing order so what we do here is we start from w and just move on until we reach the end so we first have W here and then e so let's say our first string is w and then e comes after that but we also have an A which has no dependencies so we have to bring it before a now this is keep in mind this is one of the two possible solutions that we're going to go over the other one and then after that we have r so we have R here and then T and then f so this is the first solution now you could also start from a and come to W and E so first thing we can have a and then W and go over e and then RTF the rest is the same so this is exactly uh what a topological sword means um and there are two possible solutions for this particular example and we can return any of them now how do we actually um visualize it and um you know make it into an algorithm now we can use a couple um other couple tools for that first things first we can have a dependency map that ha we determine the dependencies of each letter and we can have another um table which is Count map so according to this graph the graph we created here a has r as its dependency now we also have w as ease dependency so because of this W comes before e and um e is an independence independency of R and R has an independent independency with t and t has an independency with f um now what do we do in count map we uh in Cal map we keep track of all the independencies that we have in this graph and we actually put it in the dependency map we keep count of those so first things first um we have a um because there's no um dependencies before a we're going to put zero here um because nothing comes before um a so there's no dependencies now same goes with the w here we put a zero in the count map but for E because we have an independency here W uh we're gonna have to put one for R because we have two letters that are going to R we have to put a 2 and the for T it's one for f is also one so this is the count map now what are we going to do with this count math now keep in mind that um we don't have this string yet we want to find the strings from these two maps let's say let me just like actually erase this one we don't have these answers right now we want to find these this is our solution so what we do here we're going to use these two we have a Q here this is how we're going to use these words um actually find the string so what do we do exactly here first things first uh we're going to look at the count math and find all the letters that have zero independencies Like A and W and put them in the queue now we can start from each of those I start from a so I have a and then W now what do I do next so um I pop a out of the Q here I pop it out of the queue and put it in our answer string now since I pop a out of the queue we're going to look at the end dependency map and see what are the dependencies of a it's R so we look for R in the count map and since um it is one of the RS dependency we're going to actually decrease it by one because one of them is gone now what do I do after that we actually put W in our answer do the same thing with W as well and we're going to look at again look at uh W's dependencies and dependency map and it's e so we're going to actually decrease e and it's going to give us it gives us zero so again we look at the count map and we add the letters that have count zero which is now e so we add e to the Q as well so this is e we repeat the same procedure here um at e and then look at the dependency map well it's R so we're going to actually decrease R again we're going to decrease R and add it to the Q because it's zero now the dependency counts of it is zero and then what do we have here and for R we actually add um I don't know why it we had to add e to this here and then we have R pop it out of the queue and look at here what is uh what is our dependencies it's t and we have to decrease it again here and it's zero we add it to this here t and okay so what is T's independency it's f um by the way sorry I forgot we have to add t to the string here and then pop it out of the Q and then look at its dependencies which um we know here is f um and um decrease it by one add it to the Q and repeat the same thing at F and it's our last letter there's no remaining letter now if I did this and instead of um putting a because we have at the beginning we have two um letters that have zero dependency on count math I could have picked W first and then add a it would have been w e and then a the rest of it is the same we had the string w e a r t f so this is the general solution for this problem we can never have keep in mind that we can never have a cycle in our graph like this let me give you an example if this is our word list if we have z x and z again it forms a cycle um Z comes before X and then X comes before Z now here we have a cycle um and um we can't have that why because our count map says Z has one dependency and X also has one dependency none of them are zero so we don't know where to begin we can't add it to the Q and also the count map will never be zero like here we have all of them equal to zero none of them and our count map is basically empty but here we'll never achieve that and also we'll never add anything to the queue because we have to start from letters that are that start at zero so that's why we can't have that let's actually examine how to implement it in code in the next section okay so let's examine the code for this problem uh first we have our main function alien order um it's a good practice to catch on for scene errors beforehand uh so if our words length equals zero we have no answer obviously and we return nothing now here we have our data structures dependency map and count map and here we have a function if you notice we have couple functions a build graph and BFS instead of like putting it all here in Alien order it might um increase the run time a little bit but overall um if we create functions uh for you know blocks of code that are a little complicated it doesn't increase the complexity you might increase the run time a little bit but it makes your code readable and it doesn't increase the complexity so it's a good practice um and so we have this function build graph which takes three inputs our data structures and words and uh returns a Boolean it's called success so we want to see if we can build a graph and if we can um we return true and these dependency and count Maps will be filled with proper values now if we can't build a graph obviously we have no answer so we return nothing um and ultimately after we built after building a graph uh we run a BFS as explained in the algorithm section uh we have a queue we run BFS and then uh we return a string this BFS function returns a string which is our answer now let's actually uh first examine build graph function so it takes three inputs as discussed and um first we initialize our count map so what we do is like we Loop over all the words in a words array and then we put each character of each word into our account map we initialize the numbers the number of frequencies with zero so this is for initialization and then this section this for Loop what it does is actually Compares each word in our Awards array and see um and you know attempts to find the um order of the letters so what we do here is we um we Loop over our array and then uh if uh these are two special cases we first run these and then we examine um our main possibility so if the two words are equal as explained earlier um we skip it doesn't give us any information however there's a special case if our um current word starts with our previous word we have no answer we can build a graph so here if for example I have ABC that comes before a b um I can't build a graph C comes before nothing so um obviously it doesn't give us anything we can build a graph however if there is um if none of these cases are true what we do is uh we're going to compare the each character of the current letter and previous letter and find the orders of the letters so we Loop over um each we store the um character from our previous word in first Char and from our current word in second Char we compare these two if they're equal it doesn't give us anything so we continue otherwise we're going to do this if the first Char isn't in our dependency map yet uh we are going to add it to our dependency map and we're going to add first Char uh to the dependency list of the second chart now here's the thing if it's the first time we're adding a second Char and first Char to our dependency map um the add method is going to return it's going to be successful and also is going to return a Boolean a true so we put it in this if and if it's true we're going to add we're going to increase the number of dependency for a second Char on our dependency map for example if we have let's say a b c and then we have ABD then a c comes before D so in the dependency map obviously the number of dependencies for D will be increased from zero for example to one and here we're going to add C to the list of dependencies of d now after that after we create our graph we return true and move on to the BFS section here so what we do is obviously we build a queue as explained earlier um in the algorithm section um we're going to Loop over we create a cue and then uh we Loop over our count map and see if we can find characters that have zero frequencies and add them to the queue now we use result a string Builder result to store the final string the reason for that is it's easier to manipulate and add characters to it now while our queue is in empty we're gonna pull the front most element called C from the Q and then obviously we're gonna remove it from count map by the end of the algorithm it should be empty if we have an answer and we're going to add it to the final result string Builder and here if our C character is a dependency of another character isn't a dependency of another character we're going to continue our search however if it had it's a dependency of another character uh we're actually going to first decrease the number of dependency for that uh character which is called Next here and then if that character's frequency equals zero we're going to add it to our Q otherwise uh we're gonna skip um so this is um by the end of it we should have uh final string and if and our count nap should be empty if it isn't empty we have no answer as explained earlier and we return an empty string however we return if we have an answer we return the results string and we convert it to two um to a string and we return it and this is our answer so let's actually submit the code so it was submitted um and uh successfully submitted so the time complexity for this algorithm is O of um M times n and the reason for that is n is the number of words um and M is the number of characters in each word we have we uh since we like compare each word each two consecutive words and check them character by character for Miss for a mismatch we're going to have o of n times n as our time complexity we also have a topological sort which has a complexity of uh o of D plus n and the reason for that is uh D is the number of characters in the alphabet and N minus one is the number of edges so the overall complexity for that part is O of D plus n minus 1 or of D plus n but the overall time complexity for this algorithm is going to be the sum of these two which is going to give us o of M times n the space complexity is going to be o of D plus n and like I said D is uh the number of characters in the alphabet and N minus 1 is the number of edges so we have we also have a topological sort section since we create a graph by the way since we create a graph the time complexity for that part is vertices plus edges um so it's going to be of D plus n but we also have topological sort section that we have um a q that topological sword would will take o ofd As Time comp as space complexity and we have a cube which also takes o of D in the worst case and the overall space complexity for this part is ofd but if we sum um the last section with this one it's going to give us o of D plus n as the overall space complexity for this algorithm uh now I hope you learned something from this video and I'll see you in the next one
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
201
Hello Welcome to Delhi Distance Between Suzy Under Dividend of Numbers subscribe to subscribe the Channel Please subscribe and subscribe this Video plz subscribe Ki Between Us and of Numbers Riched Ko 2010 Electronic Chronic Problem The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our numbers from subscribe school quote and even before jumping and details nearest plus revised and operation preeti 30510 is this remedy number three do subscribe toe states of knowledge with loot-loot states of knowledge with loot-loot states of knowledge with loot-loot responsible wheat phone number 90 verification tab scam and operational Number 900 Electronic Computer Channel Subscribe Must Zid Numbers Ki 19.10:30 Subscribe Channel Ko Now subscribe Video Subscribe To Ki Ve Swarg 960 Adhir Witch State The Water Tank Kabir Viukt TimesJobs Subscribe 9000 Subscribe To That Nine Comes The Question That Can Be Identified As Using Only Two Numbers Laxative Video subscribe and subscribe I am getting in different office on 909 add 2009 Subscribe 300 That Bigg Boss Give The Question Left Festival 12218 Start Hai Allu Anda Truth Will Tell Me Up Till What In Next Volume Increase It's Not Good Morning To All Co Select Hydration Tarf Intership Tweet Aisi Subscribe Perform Forest Rights Act Operation Nuvvu subscribe Video Ko Ke Veero 100000 900 to 1000 subscribe to yesterday morning remember number has not writing against profit 131 battalion lighting text message update do subscribe channel subscribe to that if store number 10 notice get then from desktop impression month sudhir and number 90 subscribe unmute video Bill Gates Intermediate Brian Adams 2353 Subscribe Not Well After Subscribe What Was The Number Three Times Hai So Let's Rider That Bihar All Videos Accept For The Last 20 Years From Nine From Right To Left Operation Three Times In The Resurrection Subscribe One Adhikari Dr 's Problem in assam rahul ko trying to 's Problem in assam rahul ko trying to 's Problem in assam rahul ko trying to identification in taxes in urine subscribe video ko ki itihas when i don't worry tweet clear indication so let's move on to bebeautiful.in ki in so road festival from left number to the number and tried to conclude day is Later to subscribe my channel subscribe to and Aanitik Antonov tweet and difficult to optimize solution list sunao ki heroin system very little time left Video subscribe The Video then subscribe to the Video then subscribe to Hai So Let's transmitters of this is updated from Master of Jamun Information And The Time Complexity Based Approach Episode 132 Subscribe 32bit In This Brings Into The Introduction Of United Please Don't Forget To Like Share Cycle Stand Most Strong Modification Subject Good Bye Subscribe Properly Updated On
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
1,845
Hello friends welcome to my channel here solve L quot problems and prepare to the C interview today the problem number is 1845 C reservation manager design a system that manages the reservation state of end seeds that are numbered from 1 to n implement the seat manager class seat manager iniz a seat manager object that will manage and seats numbered from one to n all seats are initially available method Reserve fetched the smallest number and Reserve seat reserve it and returns its number method un reserve and resoles the seat with a given seat number let's try to find a solution we can solve with different ways the easiest way is to store the list of fre seats for instance by default we have n fre seats from one to n each time we will find the smallest number and return it after it we delete this number so initially we return number one so we resolve it then delete after it we have some numbers from instance from 2 to n now it's fre when we need to unreserve some seeds we just add the seats at the end so it could be some numbers for instance two some numbers and after it we add and reserve seats one in this case we have algorithm complexity to resolve is O of N and the complexity of the method unresolve is O of one it should work but it needs too much time so it's not enough to submit we need some something more efficient for this case we have special data structure called minimum or maximum Hep it's kind of binary tree so it has node it has root at most two branches with ch children and so on root is always minimum of or maximum element of the tree depends on its minimum or maximum Heap the complexity of this kind of data structure always logarithm of n so if we need to return minimum element we just delete the root and the reorder all three and it takes at most log of n operations adding new element is the same and it needs uh log of n operations so it's more efficient algorithm and it's better to implement it for our problem let's try to solve it python have a model so the minimum Hep called Min Hep cool to use it we need a variable to store uh initial list and better to sort it so we create this variable called hip and it's list made from range from one to n + n + n + one and to resolve uh seat we need to find minimum item and return it after it we need to delete the Min item from the Hep to do it we have a special method hip pop which find the minimum element it's the root element deleted and after it we will return it the method has one parameter is the hip variable so uh in our case it Hep property to un Reserve we need to add some element which will be fre and to do it the module hip Co have a special method hip push we two arguments one of them is hip list and second the number which we going to add so that's it and it should work and uh will be much better than linear algorithm let's try run test past and uh let's submit it works is pretty efficient and uh that's it for now see you tomorrow bye
Seat Reservation Manager
largest-submatrix-with-rearrangements
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number. * `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`. **Example 1:** **Input** \[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\] \[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\] **Output** \[null, 1, 2, null, 2, 3, 4, 5, null\] **Explanation** SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\]. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3. seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4. seatManager.reserve(); // The only available seat is seat 5, so return 5. seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\]. **Constraints:** * `1 <= n <= 105` * `1 <= seatNumber <= n` * For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat. * For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved. * At most `105` calls **in total** will be made to `reserve` and `unreserve`.
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
Array,Greedy,Sorting,Matrix
Medium
695
52
hello guys today we are going to see the uh question n Queens 2 the N Queens puzzle is the problem of placing the N Queens on N cross and Chase board such that no two queens attack each other for two queens not to attack each other so uh we know that Queen can move in all the e Direction so we need to check that uh both the Queens should not be present in the same row or column and they should not be diagonally present as well so in order to ensure that we had uh it is similar to previous question here only we need to uh return the number of solutions uh here so in order to do that let us see the code of the question here is the code of the question first a vector string VT is taken uh and a board is taken which is initialized with all the dots then the solve function is called in solve function if the column becomes equal to n then each of the time we have to increase the number of iterations because increase the answer count this is the answer that we have to return finally which is declared globally over here and we have to iterate the whole rows and if that row is safe then we have to call we have to place that in that row we have to place the queen uh in that cell that is row column and we have to call for the next column and during backtracking process we have to remove all the queens that we have placed and we have to replace it with that dots and if each of the iterations in recursive C if column become equals to n we have to increase the answer count and we have to return this simply and to check this is the same as we move from left to right we need to only check from uh the top left uh then the left and the um bottom left bottom and this is the code and first we have done the row minus- and first we have done the row minus- and first we have done the row minus- column minus- for this is then column minus- for this is then column minus- for this is then column minus- to check the uh left most column minus- to check the uh left most column minus- to check the uh left most column and uh this is done to check the left down most area and if all uh did not return any of them did not return false then we have to finally return true and this is the code thank you
N-Queens II
n-queens-ii
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_. **Example 1:** **Input:** n = 4 **Output:** 2 **Explanation:** There are two distinct solutions to the 4-queens puzzle as shown. **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 9`
null
Backtracking
Hard
51
1,732
hey guys in today's video we are going to solve one more lead good question that is question number 1732 find the highest altitude this is an easy level question and we can see it has been asked by Adobe apple and Microsoft in last two years so let's see what this question is all about and how we can solve this so in this question it has been said that there is a biker going on a road trip and the road trip consist of n+ 1 points at different consist of n+ 1 points at different consist of n+ 1 points at different altitudes the biker starts his trip on point0 with altitude equal to zero now we are given an integer array gains of length n where gain I is the net gain in that altitude between point I and I + 1 that altitude between point I and I + 1 that altitude between point I and I + 1 for all the values like I is always going to be greater than equalent to Z and less than n and we have to return the highest altitude of a point and here are some of the examples given so let's understand this question even better by this example suppose this is the place where I'm standing right now and this is the value of the highest altitude because it has been given in the question that we are starting from point0 right so we are starting from zero so that's why this position is zero now after moving as after moving some distance at this point what is the gain is minus 5 so what I will do I will take my previous altitude that is zero and I will add the current gain into it and what will be the value will become minus 5 so this is the current altitude but is this the greatest one so no because uh if I'm going to compare 0 and minus 5 I know the greatest one is zero right so at this position the greatest altitude is 0 and the current altitude is -5 now again I will move -5 now again I will move -5 now again I will move forward and after traveling some distance at this point the gain in the altitude is 1 so what I will do I will again take the previous value that is minus 5 and I will add the current value that is 1 and the sum will become Min -4 is the greatest altitude do we need -4 is the greatest altitude do we need -4 is the greatest altitude do we need to update the greatest altitude no because Max X among 0 and minus 4 is still going to be 0 so I will again move forward and after traveling some distance at this point what I will do I will again do the same thing I will take the previous altitude that is min -4 I the previous altitude that is min -4 I the previous altitude that is min -4 I will add the current gain that is five and the value will become 1 so now is there a need to update the greatest altitude then yes because 1 is greater than zero so now our greatest altitude is updated and it's become one now again I will move forward and after traveling some distance at this point again I will do the same thing I will take one and I will add zero and it will remain one so my greatest altitude is also one and again I will move forward and I will read this last step which is - 7 and at this point what I will do I - 7 and at this point what I will do I - 7 and at this point what I will do I will again take one I will again add - 7 will again take one I will again add - 7 will again take one I will again add - 7 into it and the value will become - 6 into it and the value will become - 6 into it and the value will become - 6 and as - 6 is lesser than 1 so I don't and as - 6 is lesser than 1 so I don't and as - 6 is lesser than 1 so I don't have to update the greatest altitude and at the end of this traversal what I will be having greatest altitude equalent to 1 so what I will do I will return this and this is the answer so this is how we can solve this question so there are few things that we can clearly see via this example that is firstly we are maintaining two variables that is the current altitude and the greatest altitude and greatest altitude is only going to get updated when the value of current altitude is greater than the existing greatest altitude right and the current altitude is nothing but a constant prefix sum that we are maintaining while we are traversing this altitude array so this question was a prefix sum type question and we solve this question with the time complexity bigo of n where n is the length of this gain array and space complexity is going to be bigger of one because we hadn't used any data structure we are using only two variables so our space complexity is Big of one and time complexity is Big of n so now let's quickly code this question and today we are going to code this question in two programming languages that is Python and R so firstly let's code this question in Python and after that we will uh see the Ruby solution as well so as we have already seen in the drawing explanation we need to Define two variables right firstly first one will be current altitude and second one will be highest altitude and initially both were zero right then what I'm saying for I in gain now what I will do I will update my current altitude first and I will do plus = to I and after this I will update plus = to I and after this I will update plus = to I and after this I will update the highest altitude which will be maximum of highest altitude and current altitude and after stepping out of this Loop we will return highest altitude now let's submit this and see if it works or not so we can see this solution is accepted so now let's quickly code Ruby solution as well so in this as well we are going to do the same thing that is firstly we will Define two variables and initialize them with zero after this what I'm saying gain dot each do I this is the loop Loop and inside this loop again I will do the same thing that is current altitude plus equal to I and after this update the highest altitude and in Ruby we check the max in this format after this we add this do Max and after stepping out of this Loop simply return highest altitude now let's submit this as well and we can see this is also accepted so this was a very short sweet and simple question and I hope this video was helpful for you all and if you really find it helpful then like this video subscribe my channel and I will soon come up with few more questions till then keep messing with algorithms and thanks for watching
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
1,696
hey there welcome back to lead coding i'm your host faraz and today we will be looking at the third problem from lead code weekly contest 220. so name of the problem is jump game six we have already solved jump game five if you haven't watched the video the link will be in the description you can go and watch that video so let us go through the problem statement first you are given a zero index integer error nums and an integer k you are initially standing at the index zero so we are standing at the index zero and in one move you can jump at most k steps forward without going outside the boundaries of course so that is you can jump from the index i to any index in the range i plus 1 and minimum of n minus 1 there is the boundary and i plus k you want to reach the last index of the array that is n minus 1 your score is the sum of all the nums j where j is the index that we visited written the maximum score that we can get so looking at the first example we are at the index 0 so we will be getting 1 as the score then we are going to minus 1 that will make our score as 0 1 plus minus 1 then we will go to 4 so score is 4 and then we will jump to 3 so our final score will be 7 and that is the maximum that we can get so now let us go to the white board and try to build a solution for this problem so we'll be using example number three for that here we have the example these are the scores that we can get okay and k is given as 2 and we are standing at 1 so our score is initially 1 now one thing we know if we are standing at the last index our score would be -3 score would be -3 score would be -3 this is for sure and if we go to the index 6 so what's the possibility so the only possibility is to add minus 6 and minus 3 because minus 3 we will have to add that to a score anyhow so the last index has to be visited that is why minus 3 will be added so the option for if you are standing at minus 6 will be minus 9 minus 3 plus minus 6 if we are at 3 then we have the option we can either go to this or we can directly jump here if we are directly jumping here the score will be zero if we are going to minus six then the score will be three plus minus six then minus three it is going to be minus six so the maximum is zero so that is why we will be directly jumping to minus three our final score will be zero from here similarly if we are at minus one then we will have certain options the options are to jump to three or to jump to minus 6. if we jump to 3 from 3 we can reach minus 3 having 0 score and -1 will be added to that so minus 1 and -1 will be added to that so minus 1 and -1 will be added to that so minus 1 will be one option if we are jumping to 3 from -1 if you are jumping to minus to 3 from -1 if you are jumping to minus to 3 from -1 if you are jumping to minus 6 from minus 1 from -6 it is going to take minus 9 and from -6 it is going to take minus 9 and from -6 it is going to take minus 9 and minus 1 will be added to this so the final score will be minus 10 so which one is better minus 1 is a better score that is why we will be jumping to 3 so the answer for this will be minus 1 now about 4 again we will have 2 options first option will be to jump to minus 1 second option will be to jump to 3. if we are jumping to 3 the score that we'll be getting is 0 and 0 plus 4 is 4 so 4 is one option another option is when we are jumping to minus 1 in that case the score will be minus 1 so 4 plus minus 1 is 3 better is 4 so that is why we will make a jump to 3 from 4 and the score that we are going to get is 4. similarly for minus 20 we can have 4 plus minus 20 or minus 1 plus minus 20 so minus 16 is better that is jumping to 4 from -20 then from 5 we jumping to 4 from -20 then from 5 we jumping to 4 from -20 then from 5 we have two options to jump to minus 20 or to jump to 4. i think it will be beneficial if we jump to four because we will be getting four as the score and four plus minus five it is minus one and when we are at one we can make a jump to minus five or we can make a jump to minus twenty if you are making a jump to minus 5 we are getting minus 1 s square minus 1 plus 1 is 0 if we are jumping to minus 20 we will be getting minus 16 as the score and minus 16 plus minus 15 so the better is 0 and we can see that 0 is the answer for this case now how are we doing this so we are moving backward and while moving backward we are calculating the answer for each of these indices so in order to calculate the answer for the ith index let us say this is the ith index and in order to calculate the answer for this index we were exploring the next two indices because k was given as two if k was given as three then we would explore the next three indices and if k was four we would explore the next four indices so in order to calculate answer for each of the index we are using the next k indices so the overall complexity will become big o of n multiplied by k for each index we are visiting the next k indices looking at the constraints k is given as 10 raised to the power 5 and the length is also given as 10 raised to the power 5 so the overall complexity is going to be 10 raised to the power 10 which is of course going to give us dle so we have to think something better so we were exploring the next k indices so as to get the best answer out of it so which one is giving us the maximum score we want to visit that index among the k options that we have available for us so in order to do that we are going to use a data structure called monotone queue we have already discussed about monotone stack if you haven't done that the link will be in the description you can study the concept of monotone stack there similarly we have monotone queue as well it's a very simple data structure you will be able to understand it thoroughly once we start coding it i will just try to explain how does it work so basically in this case we'll have to maintain a mold on increasing q instead of exploring all the key options we should be able to get in a constant time that which place to go from the current place let's say if we are at this index we already know the answer as there are no options to go from this place so the answer for this place is -3 answer for this place is -3 answer for this place is -3 there's something that we have to add because we have to reach at this place so minus 3 is one of the option if we are at this place minus 3 is one of the option to go and it is the only option that is available to us so the score will be minus 3 plus minus 6 it is going to give us minus 9 from here we have two options first option is to go to minus 6 and add minus 9 to this total score or to go to -3 and to add minus 3 to the or to go to -3 and to add minus 3 to the or to go to -3 and to add minus 3 to the total score minus 3 and minus 9 are the two options available to us which one is better -3 is better so we which one is better -3 is better so we which one is better -3 is better so we are going to keep -3 are going to keep -3 are going to keep -3 at the front we are going to maintain this option at the front so that we are able to get this in a constant time now how are we going to do this i will explain you later but as of now just assume that this is at the front so -3 is the better option we are going so -3 is the better option we are going so -3 is the better option we are going to add that and we are going to get 0 as the total score 3 plus minus 3 and 0 will be the next available option to us so now we are at minus 1 also one thing that we have to notice is -3 will no longer be an option why so -3 will no longer be an option why so -3 will no longer be an option why so because -3 is somewhere that we cannot because -3 is somewhere that we cannot because -3 is somewhere that we cannot reach from -1 reach from -1 reach from -1 because it is taking three step and we can only jump at most two steps so that is why this option minus three will be discarded so we have only two options that is zero and minus nine now as the option zero was added to the list so we know that minus nine will be discarded so zero can just eliminate minus nine so that it can come at the front so now the only available option is 0 and minus 1 plus 0 is minus 1 the answer for minus 1 is minus 1 now when we are here at 4 then the only available option is all right so minus one will also be added to the available options so zero and minus one are the two options that is available to us and the first option is greater so we don't have to do anything so just add 0 to 4 so 4 will be the score and now 4 will be the available option now as far as the available option 4 wants to be at the front so what we can do is we can discard minus one we can discard zero and we can keep four only so we discarded these two things we kept four is the only option available to minus twenty plus four is minus sixteen and minus 16 will be the next available option and then going to minus 5 we have the best option at the front again that is 4 now 4 plus minus 5 is minus 1 and -1 is the next available option -1 -1 is the next available option -1 -1 is the next available option -1 is greater than -16 so it is going to discard minus 16 -16 so it is going to discard minus 16 -16 so it is going to discard minus 16 and -1 will come here and -1 will come here and -1 will come here also the option 4 will be discarded due to the distance so the distance is greater than 2 and we cannot consider minus 4 as the option because of the distance so the only option available to us is minus 1 and that is a different the best option so that's why the answer will be 1 plus minus 1 that is 0. so now we understand so this structure we can maintain in a queue and that queue will be called as monotone queue so monotone q is nothing fancy but we are just maintaining the best option at the front and the best option will be greatest so it will be kind of decreasing q if we have k number of choices and we have key options to maintain it will be the q will be of size k the first element will be the maximum then the element just next to this will be lesser than the first element and so on till the end so this is called a monotone decreasing q you will get a better clarity of this once we start coding this so we have to take care of two things the first thing is to maintain the first element as the maximum and the second thing is to eliminate all those options which are at the distance greater than k so now let us start coding and see that how we can maintain this structure i think once you are done coding this problem you can tackle any other problem which is related to monotone queue and if you want to solve more problems on monotone stack then the link will be in the description okay so now let us start coding we need to maintain a queue inside the queue we are going to insert from the back and also remove from the back so that is why we are using deck here so in a deck what we can do is we can insert at the front and at the back in a constant time also we can remove from the front end from the back in a constant time another thing that we need is a vector of type int dp it is going to store answer for all the indices it will be of size n where as the size of nums dot size dp of last index the answer for the last index is going to be nums of n minus 1 because when we are at the last index the answer will be the score of the last index itself so it is nums of n minus 1. inside the queue we are going to insert the options that are available to us and at the front of the queue we will be having the optimal answer or the most optimal option that we can go to so initially we are going to have only one option let us just push back that option that is the nums of n minus i this is the option that is available to us or we can do this as dp of n minus y now we are going to calculate the answer for each of the indices starting from n minus 2 i greater than equal to 0 i minus so dp of i the answer for the current index is going to be nums of i the score of the current index plus the score when we are at the best option that we are going to jump from this position so that will be at the front of the queue q dot front okay so this is the answer for this particular index now this will be the option for the indices which are going to come now so we have to insert this into the queue and we should insert it in such a way that we maintain the order of the queue as monotone decreasing queue and this option if it is the best option it should be at the front of the queue so for that we have to pop out all those elements from the back which are smaller than this particular value so we are going to pop those elements one thing that we have to see while popping is we should not pop when the queue is empty so that is going to give us the segmentation fault so qr size till the time this q dot size is greater than or equal to zero we will compare the elements q dot front this element is whatever is there okay q dot back so this element is the element which is at the back if this is smaller than dp of i in that case we are going to pop this q dot pop back and then we can insert the current element q dot push back dp of i one thing if you remember we mentioned that we will have to see the difference of the index of the option and the current index if that is greater than key then we have to discard that option so for that we should know the index of the best option that is available at the front so how do you know the index either we can store both the indices as well as the value inside the queue the other way is to just insert the index so if you are just going to insert the index for example if you are going to insert n minus 1 instead of dp of n minus 1 we can always get whatever is there at this n minus 1 using this dp vector so this q dot front is going to give us the index and dp of this index is going to give us the value q dot size q dot back and this is dp of q dot back it is going to give us the value whatever is there at this index db.back at this index db.back at this index db.back and while pushing we can insert the index now using this index we can know the difference if the q dot front this is the best option minus i is greater than k then q dot pop and we are only required to pop this one element uh why so because after this element whatever is there obviously the distance of that with the current index is going to be smaller than or equal to k at most we will have to delete only one element you can just think of it using an example and in this case we will have to remove multiple elements it might be possible that we might remove all the elements as the dpo5 might be the best score all right so the answer will be present at dp of zero let us try to run this there's some compilation error dp we didn't make dp okay all right pop so we have to mention if we are popping from the front or from the back so this should be performed all right now we are getting correct answer let us try to submit this hopefully yeah it will get accepted so talking about the extra space this dp vector is taking big of an extra space and in the worst case the size of this q could be big o of k where k is the steps that we can jump to so big of k in the worst case both of them are equal so we can say that the space complexity here is big o of n talking about the time complexity so this loop is big of n we can see we go of n and these are the constant operations and this while loop you might think that as i mentioned you might have to remove all the key elements which are present but in the worst case only n number of elements can be inserted in this queue so at most one element will be inserted only once and one element will be removed only once so at most an element can be inserted and n elements can be removed using all these for loops so the overall summation of all these while loops iteration over this for loop is going to be big o of n so overall complexity will become big o of often if you found the video helpful please hit that like button do subscribe to the channel so that you don't miss out on future videos and also hit that bell icon so that you can get notifications as we are uploading videos regularly thank you
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
765
hello guys now let's try to salsa couples holding hands purpose let's see a statement uncouple sitting at ruin seats are an arranged in a row and wanted to hold hands we want to know their minimum number of swaps so that every couple is City side by side a swap consists of choosing any two people then they stand up and switch seats the people in the seats are represented by an integer from zero to two minus one the couples are numbered in order the first couple being zero the seven couple being two three and so on with the last couple being to a minus two any two and minus one the cobbles initial city is given by row I pins the value of the person who is initially sitting in the ice seat so let us see the example Row two zero one three we should swap out the two in one in the example - they are the two in one in the example - they are the two in one in the example - they are already seen he does have I said so number is zero so how to think about this problem basically this is a unifying the problem how do you think like that oh twisting on this product basically you see the first example is 0 2 1 3 2 a 1 cup whole the two person should sit side by side in case we have 4 people so it should have two couples and we see each couple is a connected component so we check 2 by 2 first we check the 0 &amp; 2 oh we get the first we check the 0 &amp; 2 oh we get the first we check the 0 &amp; 2 oh we get the ID of the couple say there are 0 it'll belong to zero divided d by 2 which is 0 it will belong to the couple 0 and the to be don't you chew over to do you want belong to the copper one so there are two different couple and we connected them and then one and three do the same thing there we connect a 0 and the 1 so at last there is only one natural components but we should they have to connect components so we should do two minus one swap and I see the example two we are given six people so we should have three couples and we do the same thing check which couple the people should belong to and though we can see we connect a zero in the world couple together so at last so we have two connected components but we should have three so we use the three minus two equal to one we just needed to swap a 1-1 once to get we just needed to swap a 1-1 once to get we just needed to swap a 1-1 once to get a Chu kin took it because there in the wall are connected right but we needed to separate them so we just needed to swap one wants together to connect your components let's see the example three in this case so we do the same see we'll finally we only have one connected component so we should separate this is three connected components and we only needed to do the 3-1 go to choose words needed to do the 3-1 go to choose words needed to do the 3-1 go to choose words you can check data chain fell out so basically we just do unified and the let's write our disjoint sets for class and though we also need that there crisis because pública because we will use that so you use public in turn out now we need a private in the size because we want to do the Union by rank and we also need a the route a red to indicate a route hmm as a writer constructor the SU we are given and which means the number of a couples so this top culture it at the first a equal to n and the size we initialize to paint and the route will initialize the culture in turn and do not forget we utilize the very author route and first each items route to it you go treat yourself okay then we will do the find given X we need to find its route if root X not equal to X we keep a find that and as a sometime do the path compression so root X now finally return this root X then we need to do our Union even x and y refers to get to the root X equal to 5x and the root y equal to 5y if the root I already go to root Y which has the return and then we should do their Union by rank if size root X less oil for the size good why we change the root of the root - root why the center up to the root why - root why the center up to the root why - root why the center up to the root why size of the root y increment by one under else root exercise X increment by one and do not forget that you change the couch - - forget that you change the couch - - forget that you change the couch - - because it we unions and so their total kinetic components couch or shooter agreement in the yeast part we will get and where you go to roll the lens over to this is a number of the couples so we newer ESU has enjoyed the alter each other I understand and I plus index where you culture row I plans to enter the second night in a row to row I come to and we try to Union X Y we get the number of the connected components Alaska pusher Rotonda - their total Alaska pusher Rotonda - their total Alaska pusher Rotonda - their total kinetic the component ah sorry because we should a pastor I ID of the cup of social / - together idea of the couple social / - together idea of the couple social / - together idea of the couple okay thank you for watching see you next time
Couples Holding Hands
serialize-and-deserialize-n-ary-tree
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, and so on with the last couple being `(2n - 2, 2n - 1)`. Return _the minimum number of swaps so that every couple is sitting side by side_. A swap consists of choosing any two people, then they stand up and switch seats. **Example 1:** **Input:** row = \[0,2,1,3\] **Output:** 1 **Explanation:** We only need to swap the second (row\[1\]) and third (row\[2\]) person. **Example 2:** **Input:** row = \[3,2,0,1\] **Output:** 0 **Explanation:** All couples are already seated side by side. **Constraints:** * `2n == row.length` * `2 <= n <= 30` * `n` is even. * `0 <= row[i] < 2n` * All the elements of `row` are **unique**.
null
String,Tree,Depth-First Search,Breadth-First Search
Hard
297,449,771
368
hey hello there today we're looking at uh lead coding challenge question largest divisible subset we have a set of distinct positive integers and we want to find the largest subset such that every pair of integers within the status within this subset satisfy this condition so the condition is that we're doing modulo division between two positive integer numbers for this to divisible for this to be zero that means the first integer number has to be larger and it has to be divisible by the second integer so it's a four the modulo two equal to zero something like that the first one has to be larger and it has to be divisible by the second one and this is a pairwise relationship and it has to be codes for every pair of number in the subset if there are multiple solutions multiple subsets of the same largest size we can return either one of those is fine looking at example we have one two three so every number is divisible by one so we can do one two or one three obviously but uh three is not divisible by two for that reason two and three will never be in the same subset uh otherwise we have a violation of the pairwise divisible relationship so for uh so basically we have two subsets of the same size we can return either one of those looking at the second example we have one two four and eight i just quickly verify the pairwise relationship divisible relationship eight is divisible by all the number here four is divisible by one two is divisible by one so we quickly checked all the pairwise divisible relationship they all holds so it's fine so let's say that um yeah actually that if we look at this 8 is divided by 4 is the largest number among all those then that means 4 has to be divisible by 1 and 2. um if 8 is divisible by 4 we don't even need to check whether 8 is divisible by 1 and 2. so if we if the input contains some other numbers along the line after 8 and they are larger than 8. when we decide can we actually expand this subset to be larger by introducing one more number the only test we need to do is to test whether that new number can be divisible by 8. if that's the case the new number can be divisible by all the number in the subset so that tells us we can sort the numbers and try to build this kind of a subset by introducing larger number one at a time and the only test that we need to do is to test whether the new number is divisible by the current maximum so the kind of a recursive relationship here if we represent fi to be the maximum size or the depends on what we want to store here if this is the definition for fi we can have this kind of relationship so basically this is saying that when we want to consider this number uh as the size when we want to find out the maximum size of a subset with the ice number as the largest number in that subset all we need to do is to check all the subset that's uh with the maximum number that's smaller than nums i and to see if the nums i is a divisible by the largest number in the smaller set if that's the case we can introduce numsai to that set and extend that to have that set grow one size larger we can try to do this for all the subset that's with a number that's smaller than the number we're looking at and try to grow the subset to be one size larger so based on this recursive relationship we can either do top down search with some kind of memorization or do bottom up to bottom up we're basically just populating f0 to fn n minus one and we want to find the maximum i where this f value is maximized once we figure out the maximum um you know the eye for that if we store the actual subset we can just read it out uh if we always store it as a sizing information we'll do one more time to do the backtracking so it depends on what we store on the fi yeah so if we store the actual subset it will be more space expensive it's going to be square time we have n locations every location we can we need to store the actual subset with potentially any number so it's n square in space but we don't need to do the backtrack if we only store the sizing information we will do a backtrack to collect all the numbers that forms that subset so but the backtracking is just going to be linear time so compared to populating this uh if all the fi values it's nothing because just look at if we want to populate i5 from 0 to i to n that's one loop for loop and within each within the loop each iteration will consider the numbers from 0 to i minus one so it's a square time uh backtrack is linear time so it's uh it's overshadowed by the time needed to populate this but we can save the space so let's go up to for that route so i'm just gonna put it on here one d dp for this backdrop so that's uh pretty much the overall summarization about what we're gonna do we're going to sort this so that each time we try to each time when we consider a number we try to bring that number into a subset with a smaller number as the current maximum in a subset here we're basically using this formula here uh let's just do it index so it aligned to the formula a little bit better do the maximum and plus one uh but we initialize with zero so that means every single element by itself every integer by itself is not a subset because for the subset we need all the other pairs so for that reason when we add that one to that when we actually form a subset with two elements uh we're gonna end up with a one so that's not the actual size uh we're gonna increment this by one so that this will be the this workout the mass workout and we're going to keep track of the maximum index so the max i max l is indicating the maximum size of the subset and also the index for the number that's uh that's the maximum in the subset we're going to use this to do the backtrack so after this for loop we basically populated this dp table then the only thing left is to collect all the numbers along the way to form this actual subset um yeah so the basically we're gonna go eight and look at the left-hand side to see a subset at the left-hand side to see a subset at the left-hand side to see a subset with size three and ending with some number that's uh divisible that eight can be divisible off after we find four we will try to look towards the left of finding a number that four can divisible off uh and also that number has to be the be an end element of four sequence for a subset that's of size two so we're gonna decrement this size uh and uh look towards the left try to find the first number that the uh the nums at the previous number can be divisible so previous number is equal to the number at the max eyes location so this time we do a backward iteration wait we are starting with this so we test the nums i and we decrement this and uh oh sorry we put this new number as the previous largest number and also decrement this co lens i guess for to avoid confusing i'll just rename it i need to hurry um yeah i think this is this should be the code does it work it's two one not one two yeah actually i don't need to store this um all i need to do is to check the maximum right yeah i can get rid of that it's working uh let me try this uh looks fine let me add one more turn this time it will be three multiplied by this 81. does it work yeah it's picking up okay let's see what about empty case did i handle empty case nope uh yeah so let's handle that okay uh it looks fine yeah so that's pretty much the code uh to our sword so because that when we try to consider about those subset it's easy to think about that when we try to add one more larger number to expand the subset because all we need to do is check the current maximum with the new number we try to add so process the number in the sorted order it's a really nice here is the double loop sort of double loop to build up this dp array one dimensional dp and once we figure out the maximum we just do one pass backward towards the left to collect all the numbers to form that actual subset all right so that's uh did i sub yeah submit that's the question today cool
Largest Divisible Subset
largest-divisible-subset
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,2\] **Explanation:** \[1,3\] is also accepted. **Example 2:** **Input:** nums = \[1,2,4,8\] **Output:** \[1,2,4,8\] **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 2 * 109` * All the integers in `nums` are **unique**.
null
Array,Math,Dynamic Programming,Sorting
Medium
null