id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,816 |
now let's go over legal question number 1816 truncate sentence the question says a sentence is a list of words that are separated by a single space with no leading or chilling spaces so just defining what a sentence is so first condition is it's a single space with no chilling spaces each of the words consists of only uppercase and lowercase english letters and there aren't any punctuations so for example hello world hello and hello world are all sentences so you can't have lowercase and uppercase you are given sentence s and integer k so we're going to be given a string and a number you want to truncate so you want to cut our sentence such that it only contains only the first k words and return the truncated sentence after now let's look at our example and if we were to look at our example we have a input sentence and we have our input number now we want to truncate this so that it only has four words and if you were to look at our sentence we have one two three four and five so we want to cut this sentence so that we keep up to here so the output will be hello how are you and let's look at other examples so second one we truncate up to four so it's going to be one two three four so up to here finally it's going to be five and this is one two three four fives so we want the whole thing now in order to solve this problem i think the most intuitive one is to first convert string into array with each word so we want to somehow create a array and have all the words in here so the first one would be hello second one would be how and so on and so forth and after we get this array we want to cut our array so that we have our first four elements and return only hello how are you but still this would be just an array with strings right so now we have to convert this into a regular string and remember that the problem says we can't have a trailing space after a word so we only have one space here one here and no spaces after the last word which is you so think about how you can implement the solution and try on your own after that if you're stuck come back to the solution if you guys find this helpful make sure you guys like and subscribe thanks now let's implement our first solution and our first solution is going to have a time and space complexity of o of n and for this one that we briefly talked about how we are going to implement this the first thing we want to do is convert our given input string into an array with each and individual word so how can we do that well first let's make a variable to sort that array and i'm just going to call it array and this will be an array with all the words so in order for us to split all these words what we can use is something called a split method if we were to split our string we want to split where each space is so we want the hello word how are you contestant so we want that all separated so what we do is we pass in a string with a blank space so what this is going to do is it's going to cut all the words where spaces are and return that in an array so let's cause the log and see that and here you can see our each individual word without any space in an array so given that we want to work from this array okay now i want to create another variable so we'll store our output here or our result and let's return our output over here okay that looks good and now is the real deal i want to be able to iterate through my array and i want to erase until i my current index is less than my k and as i iterate through my array i want to put or add each individual word to my output so let's do that using a for loop we're going to start at index zero we increment by one inch time and we do that until i is less than k and increment by one and let's add those words so that would be output dot push and it's going to be array at index i if you look at our solution if we have all the words how are you and that's four and this is also four what is the solution and the last one is all five words in here but now what we have to do is we have to convert this array into a string and another important key thing to note is that there has to be a space between all these words except for the last one because we don't want any trailing spaces well to do that we are going to use a method called join and just like split we will pass in a space and you can see that we got our result so think of split and join opposite of each other but it was used to split the string based on whatever this is in our case which is an empty space join is used to join all the words in an array and we are putting this between all the words which in our case again is an empty space now that's it for our solution now let's try to implement another solution and the logic of this solution is to be honest exactly same as our first solution but i think it's good to practice implementing different kinds of solution it makes you think for this one what we're going to do is instead of having our output as an array and remember that we use join to combine it to into a string right for this one we are going to have output that's a string so first thing will be exactly the same so we're going to have an array with spring splitted into an array and we have to give a space and let's just return our array to see what we get and we got same thing as before everything split all the words split into individual elements now let's create a output variable and this is going to be an empty string before we used a array right and then join here but this time we are going to use an empty string just for fun and let's return that here now same as before we need our full loop we start at index i is equal to zero and i is going to be less than k we increment by one each time now what we do is we have to add each and individual character to our output so that's going to be output plus equals array at index i and you can see that we have our words so it's so it has four words and this has four and this is five but the problem is that we don't have a space between each word so how can we handle that so in order for us to handle that well what we can do is let's first create a statement and as long as i is less than k minus 1 we want to add a empty space to our output variable so that's going to be output plus equals and we just empty string and you can see that we got our result now you might ask why is it as long as i is less than k minus one well if you were to have a k here you can't see it right now but you actually have a trailing space after you after n and after i here so in order for us to prevent that if you want to do k minus one and if you try this on the code online website you can see that if you didn't have this minus one you would get a wrong answer because you would have a trailing space now how this works is well this just works exactly like our push method it's just that we are adding each and individual character to our output and we check so what this is doing here is we are adding each individual word into our output and after we add word to our output we check well is i less than k minus one well if it is i want to add a space after that so for the first one i add hello it is i less than k minus one well it's true so i want to add a space now is my second word well i add how and i check again is i less than k minus one so i add the space and do that for all the elements and obviously i don't do it over here because that way if i were to have it i would have a trailing space and our solution wouldn't work now let's go over our last solution where we optimize our solution with a space complexity of o one before we had all of n right so this is better now for this one what we're going to do is we're actually going to iterate to all the characters in our string and each time we find a blank space we're going to increment our counter variable and when our counter variable is equal to k we're going to slice all the characters up to our current index and just return that later so let's code that i think that'll be easier to see the first thing i'm going to do is i'm going to make a variable named count and this is going to count the number of spaces now let's create a for loop we're going to start at index 0 is less than s dot length and we increment by 1 each time now i want to check if my current character is an empty space so if current character is equal to an empty space what i want to do is i want to increment my account by one and then i want to check if my count is equal to k what i want to do is i want my string to equal to string dot slice from 0 to i and finally i'm just going to return my string over here so you saw that we get our result right but how does this actually work so again our count variable tracks number of spaces so far and we are iterating through all the characters in our given string so before we were entering through each word but for this one we are entering through each character now if my current character is equal to a empty space i want to increment my account and when my account is equal to k i want to cut my string so 0 to i so that's going to be all the way over here and then overwrite my given string so that i can return that later now so how does this actually work well i think everything except this second if statement is straightforward so when my count of spaces is equal to my given number which is k that means that i was able to iterate through k number of words when i'm here my count would be one so i was able to iterate through one word two here three here and four here and since our k is four we stop our loop and we just slice everything up to here and then override it with our input and just return that over here so that's it for our last solution if you guys find this helpful make sure you guys like and subscribe thanks
|
Truncate Sentence
|
lowest-common-ancestor-of-a-binary-tree-iv
|
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation).
* For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences.
You are given a sentence `s` and an integer `k`. You want to **truncate** `s` such that it contains only the **first** `k` words. Return `s`_ after **truncating** it._
**Example 1:**
**Input:** s = "Hello how are you Contestant ", k = 4
**Output:** "Hello how are you "
**Explanation:**
The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\].
The first 4 words are \[ "Hello ", "how ", "are ", "you "\].
Hence, you should return "Hello how are you ".
**Example 2:**
**Input:** s = "What is the solution to this problem ", k = 4
**Output:** "What is the solution "
**Explanation:**
The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\].
The first 4 words are \[ "What ", "is ", "the ", "solution "\].
Hence, you should return "What is the solution ".
**Example 3:**
**Input:** s = "chopper is not a tanuki ", k = 5
**Output:** "chopper is not a tanuki "
**Constraints:**
* `1 <= s.length <= 500`
* `k` is in the range `[1, the number of words in s]`.
* `s` consist of only lowercase and uppercase English letters and spaces.
* The words in `s` are separated by a single space.
* There are no leading or trailing spaces.
|
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
235,236,1218,1780,1790,1816
|
1,238 |
hello viewers welcome back to my channel I hope you are in there enjoying the videos today I'm back with another problem from read code circular permutations in binary representation given two integers and start your task is written any permutation P of 0 to 2 power n minus 1 such that P of 0 is start PF i is equal to NP fi plus 1 differ by only 1 bit in their representation p of 0 and p of 2 power n minus 1 must also differ by on 1 bit in their binary representation so that is the thing so if we closely look at an example at the example 1 n is equal to 2 so that means the number of bits in a given number are 2 and the start is given as 3 so the number 3 is a start so if you represent the numbers from 0 to 2 power n minus 1 in this case n is 2 right so 0 to 3 to 2 power n minus 1 right to power and this 2 square minus 1 that is 3 so 0 to 3 these are 4 numbers so the binary representation for 0 is 2 0 4 1 it is 0 1 4 2 it will be 1 0 4 3 it will be 1 so that is the binary representation but here the task is the permutation such that each element should be differing by 1 bit in their binary representation so the output is 3 2 0 1 right so this is what the representation is 4 3 it is 2 one's right for 2 it is 1 0 so the difference here between these two numbers is the last bit is changed so that is how the difference should be read so between two consecutive numbers there is one bit different so in here so there is one bit different so the first bit is change to zero and for the last two numbers the last bit is changed from zero to one so if you look entirely right so from one to number to the next number there is exactly one change that is happening so this is one of the valid permutations three two zero one so there is one more formulation that is also possible is three one zero two that's what is given so likewise depending on that and given and the start given right we will have to come up with this kind of binary representation and there are some constraints given basically so n will be anywhere from one to sixteen and the start will be anywhere from 0 to 2 power and minus 1 actually it should be right so it should yeah it's not equal to it so it shouldn't be less than to her and ok so basically what we are going to do here is we are going to look at something called gray code we will go look into what is gray cord in the in deep ok so that the idea is to build the array for the gray code for n bits so since we are saying we are given with 2 inputs right one is an and another one is start so for n knees we are going to build n bits and rotate the list or array from where the start is occurring so first thing is will have to try to build the gray code so we'll see what the gray code is actually easy right so gray code is nothing but a series of numbers where you have the consecutive numbers are differ by one bit right so gray code is nothing but you have a series of numbers where each consecutive two number our differ by one single bit in their binary representations that is what we are going to come up with first and then once we have that already in place right then it is easy for us to rotate the array by putting the start as the first occurrence that's it that's a basic idea so step one is we are going to do build the gray code for that for one bit try to understand so let's try to understand for one bit what is a great goal zero and one that's it there are no more bits right so whatever for single bit it could be either zero or one for two bits what we are going to do is we are going to build a recursive logic here so we are going to build started we are going to build what will be the gray code for n bits by using n minus 1 bits so we are building gray code for n bits by using the gray code for n minus 1 bits so for 2 bits we are going to build on the gray code from the gray code that we obtained for one bit so for gray code for one bit is 0-1 for one bit is 0-1 for one bit is 0-1 that's a gray coat so now take the N minus 1 bits gray code so in this case two bits right so n minus 1 is 1 bit gray code so that is 0-1 and generate 2 gray code so that is 0-1 and generate 2 gray code so that is 0-1 and generate 2 arrays so first erase prepending 0 to each element in the gray code from n minus 1 bits so what is the N minus 1 bits 0 1 right so what do I am going to do is prepend 0 so prepend means add a prefix to each element and generate an array so that is what we are doing for one bit array right 0 1 let's output up so for the first step first array we are doing prepend so what that means it will be 0 and 0 1 so that is what is prepared and next second array by prepending 1 to each element right so what it will become prepared 1 here so that will be 1 0 prepend 1 here that will be 1 right so now join first array and rivers are the secondary so this is first of it right and River so second everyone at the second array will be 10 sir this is 1 0 1 right reverse will be 1 and 1 0 so that will produce the final array for two bits is 0 1 0 right so this is the gray core first two bits so similarly we can go work out with what happens for three bits four bits five bits and whatever that is right so the logic is very simple these three steps so you have two prepend by zero and prepared by one and generate two arrays join the first array with the reverse of the secondary that's it that is the logic behind the gray code generation so one now that we have gray code for two bits right so this is the gray code so the thing is we are given with a start right so that means start should be the first element in the array that is what is asked right though that is when we move to step one now we have the gray code arranged binary strings we need to convert that to the integer while converting check if the element is equal to start so we'll convert 0 2 back to 0 1 2 back to 1 because this these are a binary representation right so we'll convert back to integer representations so if the number is not formed just append to the elements list but if the number is found then insert the element at the index I initialize to 0 and increment at each insert basically once we find the element right so in this case 0 so by following these two steps right what we can do is so we go through the first element right so it is 0 so we are preparing a list let's just suppose so we are adding 0 and let's say in our case start given as 3 let's say right as first example right so we go through each element here 0 DB 1 since if the start is not found just up into the element list right that's what we are doing right so this is the list and now we are at 3 is equal to 1 if you convert back to decimal right or integer it will be 3 so start is also 3 so when the start is found then insert the element at I right so initially I is initialized to 0 right so what we are saying is any inserted I so 3 will be inserted and after that I will be incremented right so that means I becomes 1 right the next we go through next element 2 so 1 0 we convert back to integer it'll become 2 so we have to insert that at index 1 now so that index 1 is 2 so this will be at so that is the final array for the gray code they see this is the answer that they are looking for this is one of the permutations right so that's the logic behind let's go and see what is it takes to write the gray code right it's exactly the same stuff that we had we have described so gray code list of string answer right into count is equal to 0 if n is greater than 0 add 0 if and increment the count if n is greater than 1 add answer add 1 to the answer and any increment the count right so well count is less than or equal to M that means this is where we are trying to build the logic of generating the gray code from n minus 1 level to the empty level right so this is what it is so count is greater than less than or equal to an Ifrit of ground is less than or equal to M right it is get into this while loop so what it is doing to do is essentially so it is trying to append 0 and append 1 right so it is trying to do append 0 and append 1 so after a pending zero and one right so the answer will be the new answer so it's the same way but the only thing is here if you look we are going from the first index to the last index when we are appending from zero here we are since we have a step to reverse right instead of doing reversal we are going from the last element to the first element so we don't have to actually do the reverse in this case right so this is essentially as good as doing the reverse so here we are generating the reverse array by prepending the one to the existing number and finally we are generating the new answer array and then while count is great less than or equal to n this process will continue to generate the gray code so now in anus the list answer list we have the gray code readily available right so now what it takes is we need to rotate the array right that's what we are going to do so even though the answer list is a string right but the answer that we need to return is an integer list so that's what we are going to written so we create an integer list and initialize the index to zero and initialize the start whether the start is found or not right initially it will be false so for each string in the answer try to convert it to integer once if at all X is equal to start red then we will say start discount if start is found then we start to insert from the 0th index and we increment the index otherwise we just happened to the list finally we are going to return the list of the numbers that we have generated so hope this is clear for you it's exactly the same step that we described here if you go take these steps and write the code for yourself right it will be easy to understand if you like the solution please subscribe to my channel and share among your friends if you are looking for the guidance on the interviews are more interviews or one-on-one sessions right interviews or one-on-one sessions right interviews or one-on-one sessions right please leave your email in the comment section please click the bell icon so that you get all the future videos as updates your email or the notifications to your mobile devices will be delivered for by YouTube thank you for watching I will be back with another video so until then bye
|
Circular Permutation in Binary Representation
|
alphabet-board-path
|
Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:**
**Input:** n = 2, start = 3
**Output:** \[3,2,0,1\]
**Explanation:** The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is \[3,1,0,2\]
**Example 2:**
**Input:** n = 3, start = 2
**Output:** \[2,6,7,5,4,0,1,3\]
**Explanation:** The binary representation of the permutation is (010,110,111,101,100,000,001,011).
**Constraints:**
* `1 <= n <= 16`
* `0 <= start < 2 ^ n`
|
Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board.
|
Hash Table,String
|
Medium
| null |
380 |
hi guys so next we will be solving the problem of insert delete and get random in constant time yeah okay so we have to design a data structure that supports the following operations in average of constant time insert a value if not already present remove an item from the set if present returns a random element from the current set of elements it's guaranteed that at least one element exists then this method is called each element must have the same probability of being returned okay i think we can use a random function to get the random number but the problem is okay i think we can use two data structures over here the first one is uh the first one is a map which maps one particular element to its particular index in the vector so whenever we are told to insert we will check if this exists if this entries exist in the map or not so all more specifically we can use an ordered map of integer right so let us say this is the map and we will also create a vector of integer d y so let us define some private parts and this both will come in the private section right so whenever we need to initialize do we need to do not anything yeah so let us say that click here both the values now suppose we want to insert so if so we will check if this value is equal to m dot n only then we will insert right so the what we will do now so now what we have to do is we have to insert this element into the vector so what we will do is let us say and size so currently it is zero so right so what we will do is yeah whenever we are um if this is equal to n that means okay um m of value is equal to s z as z plus and push underscore back and we are pushing this value and we will say okay we have returned it okay we have inserted it lc will return 0 because we were not able to insert now similarly in the case of remove is that so if this value is not that means it exists that means we have to remove and if we have to remove then what we will do is m dot so we move this key and then we will decrease the size and so also we have to remove this element from the vector okay so how we will remove this particular index from the vector in constant time so that one that will not be a constant time operation okay so we also okay so it's okay because uh it should be a constant in average okay so what i can do is right so we will erase this and then also yeah now we need to get the random so we know the size currently so what we will do is we will say okay and okay so how the ending works do we need to import it an integer okay so and we will return because at the end we will require vector only because we can return every element with the equal probability so i think let me check it i am not let us see if this works first of all we are inserting get random so we said we will insert zero then we will insert one then we will remove zero so we have only one now i will insert two then we will insert two okay so we have one and two right now so then they remove one so we have two so then we since we have two the expected value should be two because we are just removing one argument okay so i think yes this should work fine okay um i chopped in size plus one now i think i'm making a small mistake over here we will figure out quickly so the standard output is one since we have only we just have one element in the set and therefore just print out this right we are having a one and we are not having two let me think what is happening over here this value okay oh yeah i think first of all it does um we are inserting at the zero size becomes one and zero becomes into 0 comes into set then you are inserting a 1 then size becomes 2 then we are removing a 0 so the size becomes one but whenever we are removing something then all the then the indices of all the other elements have been changed so the entire point of keeping the indices in the map becomes useless so let us do one thing instead of let us use um so what we can do is so the entire game is spoiled because whenever we are trying to remove something from the vector we want we are getting an error and also this areas function takes order of n times ultimately we are going to fail so what i am thinking is so basically if a value is present then we need to delete it from there so what we can do is we know that deleting from the end of the vector will take constant time so what instead what we can do is we know that m of value represents the index of the element which we want to delete so if m of so basically we need to first check if value is so basically we will swap it with the last element and then because the ordering in the vector is not important for me so if this value is equally too bad right if the value is equal to v dot back then it is easy we can simply and also we can simply erase but if the value is not present at the deck then what we will do this is the back element so this well its value will be equal to now this value is equal to v dot and also m of hmm and this index we have this value that is okay but also we need to say that the index of this is now index which is equal to this and then we can pop from the web right so what we are doing over here is so let us say we have an array of 1 3 five and eight now we want to delete three so what we said that the index of three is over here at this particular index the element which is present in this eight v and then we will delete this eight how we are doing this then we are saying that also the index of eight is now the index on which three was present and then we are deleting the eight from the back that means we are swiping the index swiping the element which is present at the last index yeah and then we are erasing the this is okay i think now we are going to go and let us run the test case so yeah this was a nice question from this point of view let us try to submit it so this is also a constant time operation that we have done just a second yes so this runs in constant time staffing is turning constant and this runs in constant time um yeah we are assuming that uh insertion this fine function all works in constant time for map the lookups are in constant and move yeah so i think with this we end the question but there is a follow-up question follow-up question follow-up question which i saw over here so let us see if what if there are two bits right so this is um this is another this question is for another day the probability of each element being returned is linearly related to the number of same value uh under the definition so yeah this question is for another day but yes we will solve it so that's it from my side for now see you in the next video
|
Insert Delete GetRandom O(1)
|
insert-delete-getrandom-o1
|
Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
**Example 1:**
**Input**
\[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]
**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called.
| null |
Array,Hash Table,Math,Design,Randomized
|
Medium
|
381
|
1,020 |
hello guys welcome to deep codes and in today's video we will discuss let's go question one zero two zero that says number of antlers so guys this question is almost similar to yesterday's Daily problem that is number of close Islands so if you guys have any doubts in this question that is number of close Islands or if you haven't solved this question then I highly recommend you to solve it now before solving today's daily challenge solve this question okay and I have already made a video on this question so if you have any doubts in this question then make sure you first check out my video so today's question number of handclaps is just a follow-up number of handclaps is just a follow-up number of handclaps is just a follow-up question of the yesterday's question so yeah that's why I highly recommend you uh recommending you to solve yesterday spiritual daily challenge then come to today's question okay and also I will compare both the questions so that you will understand that there is a small complexity added to today's challenge otherwise uh it is just same as yesterday's further guys in this video we will discuss two approaches one approaches would be done using DFS code another approach would be solving using breakfast as there is BFS code so yeah guys stick till the end and watch the complete video okay so guys here you are given one M cross n Matrix like this and where a grade means containing zeros and ones uh binary Matrix grid so 0 represent a C cell that means a water and one represented light zero means water one means light now what you have to do is you have to return the number of lenses in which you cannot walk off the boundary okay so as you guys can see the cells like this is a lens cell but from this land cell in whatever Direction you travel you cannot come to the boundary see this is the boundary right this is the boundary you cannot come but this lens cell you can come to the boundary right you can walk through the boundary say from any cell you can walk in poor Direction so if you are connected to any of the cell that is connected to the boundary then you can walk otherwise you cannot so yeah guys that's the move that you have to uh you can handle from one Lancer to another lenser such that you reach the boundary yeah this is your goal to reach the boundary and yeah we need to return number of lens cell from which you cannot walk off the boundary so like cells like this is one cell this is seconds this is third circle where you cannot walk off the boundary so yeah we need to return number of such uh land cells okay so I hope you guys uh I have now clear understanding of the question okay so yeah guys for as you guys you can already see that here there are three such lenses that you cannot walk off the boundary so you'll be written three here now in the second example you can see even this cell so this length cell is connected to this so from here you can walk here then you can walk off the boundary here you can also Walk Off The Boundary so all the land cells wherever you are from here from any of these four lines and you can go to the boundary so yeah guys that's why we written 0 here as our answer so yeah I hope you guys have understood today's challenge now if I show you the yesterday's challenge and compared so in yesterday's challenge the difference was see yesterday they either were using zero for land and one for water this is the first difference they were using and the second difference they were using is you need to find close eye lens see uh so yesterday they were considering this complete uh thing this complete land as the one Island so they were considering this complete land as one Island this is one eyelid in yesterday's schedule this yesterday question okay so you need to count such Islands how many closed islands are there okay like this surrounded by water so number of Island surrounded by water this was the yesterday's problem and today's question this was yesterday's and today's question is nothing but number of lenses that are surrounded by bottom see formal lens cell if you cannot travel to the boundary that means it is four direction is surrounded by water this walking of the boundary is not possible that means it is surrounded by water it is one in the same so yeah this is today's question that so yesterday's question is just you need to find number of islands and now in today's question from each of those islands you need to count the number of land cells okay number of lenses surrounded by water simple it is so yeah that's why I told you initially on LinkedIn yesterday's question uh is uh very much similar to this question in today's question you can see it's a follow-up this is a can see it's a follow-up this is a can see it's a follow-up this is a follow-up of yesterday's follow-up of yesterday's follow-up of yesterday's follow-up of your status question okay follow-up of your status question okay follow-up of your status question okay so yeah guys uh I will be using the understanding part of yesterday's question today so that's why I am more focusing on uh yesterday's question approach so let's move to today's question let me take a drop so yeah uh as you have to count total number of cells total cells you need to do some traversal right you need to do some troublesome the tower trouser can be what either BFS or DFS okay then uh one thing you need to check always that if it is surrounded by water or not so you need to check this surrounded by water this condition you need to check and if this is true if true then surrounded by water so along with these uh maintaining the condition of is surrounded by water you need to also keep a count of lens cell and if true then what we will do we would return number of land and if a false then we would return zero okay simple it is so you have either we will both we will discuss both the approach the BFS approach as well as DFS approach we will keep track of this condition if it is surrounded by water or not and we will also maintain the count now if it is surrounded by bottom then we will return the account of the lenser as we would return zero okay so this is a simple logic so this logic I had told you here is nothing but a logic that I have used in the DFS function AFS function call so there is one another approach to solve this equation okay so here this approach I have used in DFS code and this another approach I have using VFS code see this with the same approach you can also write BFS code no nothing new here and with this approach another approach also you can write DFS code really but you have to in this video I will discuss BFS code for this so I will cover both the approaches as well as both the code got it now the thing to notice here is so guys as you can see here that here we have we here we have this as the lenser this is a few lenses and here two other here these two lenses okay so here in what we do in the BFS approach is see we try to run BFS from boundaries what we will do run BFS from boundaries and visit all possible land cells okay so let's say this is the boundary from here we are starting and Mark this is visited we will Mark these as visited okay all the cells we can visit now afterwards this is one boundary and Lancer visit okay now and no uh Lancer replays the remaining on the boundary okay no answer remaining on the boundary so uh afterwards the other cells that are unvisited this is not visited not visible so the unvisited lens simple it is so yeah in this situation what is unvisited Lancer are answered simple it is so yeah we will use this approach to solve ah to write the BFS code okay clear so yeah now let's move on to the coding part where we will discuss both the code for the DFS as well as BFS approach so guys here in this DFS approach as we are traversing uh from any from the land cell see yeah here in this DFS suppose what I did I ignored the boundaries okay yeah let me take one lens cell again so let's now look at here what we will do is in this DFS function call that we will try to find the lens and that are not present at the boundary see we will skip the boundary this and Skip okay the boundary this boundary cells are skip we won't try to Traverse from here okay these are the skip C because we are taking uh from one and up till R minus 1 and C minus 1 okay this is less than so we won't check for the boundary okay clear till here now if a lens cell that is not present at the boundary okay then what we will do is then we will check if the Lancer is surrounded or not surrounded by water or not okay the same code we wrote yesterday for the yesterday's uh solution okay the same code we wrote so let's say this is the lens cell and it is surrounded by water we will check similarly we will check for this so since we are doing DFS so if you start from here then you will visit all these cells correct so yeah for each slant cell we are moving up down left and right and we will check if it is a boundary cell or not okay clear it is here now if it is a let's say if it is a boundary cell so then we will return 0 because that is not closed right we need to find cells that are surrounded by water again if it is a boundary cell then we would return 0 okay so like if it is something like this then we would return 0. and as in the else case what we are doing we will simply return one okay we will simply return one here if it is surrounded by zero see if the read of I is equals to zero then we will return 1. so at the end we will take an operation and that means it is surrounded by water in the up Direction in the down Direction and in the left and in the right that means it is surrounded by water in all four Direction okay then only we will return true then only this is C this is a Boolean function that we wrote yesterday we are using the same function the only difference we did is we took one uh one variable count and we simply incremented the count okay so this is n person count so we are you taking one variable and not creating its copy so this same reference variable we are using here we are incrementing the count whenever we visit new lenses here we visit new lens cell we are increasing simply incrementing the count and if the DFS is really written true then we will add those account to the answer if DFS will return to that means it is surrounded by water okay got this is surrounded by water then only this DFS function will return true and if it is written true then we will add all those count of length cell that we have visited in the current DFS call to our answer got this clear tail here so I guess all this code was all was uh like 100 similar to yesterday score only difference we took here is they've counted able to count the number of lenses that only the additional thing we have to do first we are checking if it is surrounded by water any if it is surrounded by water then the count that we are maintaining then we'll add this count to the answer got it clear till here okay so guys in the BFS code as I have told you that what we will do is see this is one visited we took then Vivid travels from all the four boundaries it is the First Column last column first row last row we will try to make VFS all from all the four boundaries okay we will try to make BFS call and what we will do we will try to Mark as many lines are visited as possible we will try to visit as many lenses as possible and after that if the grid of IH is equal to 1 that means it is a length and it is not visited then it is our answer so let me show you by a dry run okay so let's say you are starting from here this cell so this is the boundaries all right so you are starting from this boundary cell now afterwards from here you can try to visit this okay now all these are visited no more cells can be visited because there is water on all four Direction after this now this is another boundary sense so you visited this you will visit it visit this okay now further you cannot visit now we are uh from so you have visited all the boundary cells now write all the boundary line cells so this cells are not visited okay these cells are not visiting correct so what you will simply do is all the cells that are not visited you will simply add to the count right you will increment the count if a cell is lead and it is not visited so you add to the count so this is the simple way of we are doing BFS here okay so yeah I hope you guys understood the both the approaches as well as the coding part right not talking about the time and space complexity for the approaches see guys the time complexity here would be bigger of M into n that is the size of the grid and the space complexity would be also same M into n right because for this much size we are forming the visited array and total number of cells are this muscle that are we are visiting these cells right so that's for the time and space complexity part so yeah guys that's all for this video if you guys have any doubts then do let me in the comment section make sure you like this video And subscribe to our Channel thank you
|
Number of Enclaves
|
longest-turbulent-subarray
|
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
| null |
Array,Dynamic Programming,Sliding Window
|
Medium
|
53
|
14 |
this might be the most asked coding question I've ever seen the question is called longest common prefix and it's really not that bad we're given a list of strings and we need to get the longest common prefix so for flower flow and flight the longest prefix is FL now the longest prefix that we could have is the length of the smallest word which is going to be four from flow so we'll start our index I at the first character and go up until that length then for every word and this index we check if all the letters are equal and move I forward at this step we can see that the O's match but the I is a mismatch so we'd return any of the strings up until here and that's exactly what this python code does now save it because you will get asked this question
|
Longest Common Prefix
|
longest-common-prefix
|
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string `" "`.
**Example 1:**
**Input:** strs = \[ "flower ", "flow ", "flight "\]
**Output:** "fl "
**Example 2:**
**Input:** strs = \[ "dog ", "racecar ", "car "\]
**Output:** " "
**Explanation:** There is no common prefix among the input strings.
**Constraints:**
* `1 <= strs.length <= 200`
* `0 <= strs[i].length <= 200`
* `strs[i]` consists of only lowercase English letters.
| null |
String
|
Easy
| null |
1,941 |
today I'm solving check if all characters have equal number of occurrences giving a string s we have to return the Boolean value true if it's a good string otherwise we have to return false a good string is a string where all the characters have the same number of occurrences so here we have s a b a c b c you see that a appears twice B appears twice and then C also appears twice so this is a good string we would have to return true here we have to return false because a appears three times and B appears twice so this is my solution in C plus I'm going to use the common technique for character Accounting in programming which is to have an array of integers all the values are set to zero and the size of the array is 256. we intend to store the occurrences for all the characters inside of the string s remember that when we are dealing with ASCII values for characters in programming we are talking about values from 65 for Capital a all the way to 90 for Capital C and then we can also have 97 in for lowercase a all the way to 122 for lowercase z in the solution our array has values from 0 to 255 and the indices are going to correspond to the decimal value of the characters if at some point we find Capital a we're going to have index 65 inside of our array and we're going to increment the value for the index 65 by 1 meaning that we found one occurrence for the character a and if we find it again then we're going to increment it once again so this is the logic I just explained we're going to Loop through the string s and at every iteration we're going to grab the character and then use its ASCII decimal value to increment the value for its occurrences by one inside of this array once we are done we're going to create a variable called Val we're going to set this to zero now we're going to have this for loop we're going to loop from the value 0 all the way to 255 being an included value in the range and the first time we encounter a non-zero value first time we encounter a non-zero value first time we encounter a non-zero value we're going to assign it to this Val variable so at first value is zero meaning that when we look through our string anywhere from index 65 all the way to index 90 for example we expect to have some non-zero values if the string have some non-zero values if the string have some non-zero values if the string contains uppercase letters so if you look here they say that s consists of lowercase English letters so we're not going to have any value from 65 to 90 for this lead code Channel specifically instead we're going to have anywhere from 97 all the way to 122 and if the string was not empty one of the values in there is going to be a non-zero value in there is going to be a non-zero value in there is going to be a non-zero value if you check this year they have 97 for lowercase a so I could say Loop anywhere from 97 all the way to 122 being an inclusive value so I could say less than 123 and at every iteration I'm going to check if we have a non-zero value if we check if we have a non-zero value if we check if we have a non-zero value if we do then we assign that value to the valve variable if Val is still zero then we can also have this if condition is an else if condition and we check here if the value that we had at first for this valid variable the first time we recorded in non-zero value if that value recorded in non-zero value if that value recorded in non-zero value if that value is different from the current occurrence that we have inside of this for Loop then it means that we have a wrong string we don't have a proper string as what they expect here because the number of occurrences is difference so if that's the case then we have to return false otherwise if this for Loop terminated properly then we can return true because all the occurrences were consistent so now let's run this code here we passed both sample test cases I'm going to submit this now and we pass everything with 6 milliseconds which is not bad so that's it for check if all characters have equal number of occurrences this was Elite code in C plus if you like my coding tutorials please subscribe and I'll catch you next time
|
Check if All Characters Have Equal Number of Occurrences
|
minimum-number-of-operations-to-make-string-sorted
|
Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
**Example 2:**
**Input:** s = "aaabb "
**Output:** false
**Explanation:** The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
|
Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately
|
Math,String,Combinatorics
|
Hard
| null |
215 |
Jhaal Hello guys welcome till Thursday in the pot Video subscribe like subscribe comment and subscribe to subscribe our that gas - vacation president Mirwaiz subscribe and subscribe the and landscape Laxman 9 introduction elements I am India so then good qualities in holidays are this I do You can incident that the first value is I Suraj Kundli Volume Paying Ru Cute Reddy ABC Playlist Play List Tomorrow Morning Giver Try Tubelight Submit Two Alarm Set WhatsApp Meter Sector Correct Time Complexity subscribe And subscribe The Amazing subscribe Video Subscribe Time Complexity Click ki kuch lekar gautam users party ne mirwaiz complexity subscribe to hai to admin request let it be alive principle of partition engineering students in the elements in the middle of a lake placid in love that android we need to shift am busy and tell a value Present at Ayat Index in a Generic Question Value President Android The Benefits of Do Bollywood Aadhe Pet Hi Hai Na Mintu Intimate Submit and To Intimidate News Post Increment One President Vinod Jain Love You Left of India Close Loop Loot The Amazing Loot The Use of to then the number of value is equal to k dhundhu have the largest element year celebration account number subscribe to on thursday welcome the answer lies in the laptop and ki vinod and container take this day to visit to remove background subscribe video to Jhal ajay ko ki jis computer coding lets country doctor test kaise ho 108 sexual at summit country set alarm kar review obscene remind wondering s b use and share and subscribe vidron in every subscribe to ki a
|
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
|
1,026 |
Hi gas welcome and welcome back to my channel problem is maximum difference between node and sister and see you have to find maximum value week so see you find d value for which there exist different nodes A and B so date will be you not where value Off Anode Mines B Not This Absolute Value Should Be D Maximum A Basically Maximum This Value Should Be Maximum But Like A Should Be In Sister OK Sister C Want D Maximum Right So Right Nine Till Nine Five Is D Greatest Nine OK 7 Will Be D Maximum value so output for this tree ok only 47 and 10 14 and 13 problem right this right see if let's say you have a right you have to work on this so basically see want see will see want see fix it you will C will as you made date this is a so let 's say c want c so c want a - be 's say c want c so c want a - be 's say c want c so c want a - be right you want a - b so ho can this be maximum can this we maximum c want it right you want a - b so ho can this be maximum can this we maximum c want it you must be maximum right ho this c Can See Maximum See Can See Maximum Agree On This Because Difference Is You Will Get D Minimum From This Left Tree So Minimum From The Left Shift All Trees What One And Also Write A Value Is Greater Example But Let's Say This Six Long With date which I will also get d max value what is d maximum in this sabri which is 7 so c will check d difference of this coming with both everything which is in d laptop I will get d minimum value which is in d right sorry which This 10 and I will get d maximum value also which is in d rights of previous 40 so these are my too possible and 8 - 14 what this will be maximum 7 is d maximum so seven will be my output so i Hope you go it like let's quickly do a dryer and once I hope you go d approach is better if you are on yourself first and then continue with d video but let me just quickly draw d tree again it three one six four seven 10 First of all they have to get the values tha is the max they have to get the values tha is the max they have to get the values tha is the max value and the min value what they will do they will get from this laptop c will you return what they have to return the max value and the min value right d max and win And for here let will call on 6 root will come every 7 and 7 ok 6 right what you will do six is six is what 6 right what you will do six is six is what 6 right what you will do six is six is what de root you will have tu first of all you have tu check this six with six is your A have tu check this six with six is your A have tu check this six with six is your A Right - B A - B Was Your Right So You Right - B A - B Was Your Right So You Right - B A - B Was Your Right So You Things Can Be There Else This B Is Lowest Or This B Is Greater Minimum Value This Is Un Minimum Value So First Maximum Value So Which Is What Is Maximum 4 And 7 Is D Maximum Value From left hand rights of tree so what is d maximum so you do 6 - 7 which is mines which is greater than this van d maximum so you do 6 - 7 which is mines which is greater than this van so which is greater tu is greater right so you can store you maintain date ahead of nine d maximum value of V2 but nine u Have You Return Also And What You Have To Return The Maximum And Minimum In The Subtract The Max Value And The Min Value Maximum Will Be Wherever Maximum You Go From This Four Come 7 Whatever Max You Go From This One And Six Also D Root Also Root Jump B D Maximum among all these right so maximum of these will give you D Maximum so which will be 7 years so maximum will be 7 and minimum will be what IIT value and D Minimum of so minimum values which they go From so minimum values which they go From so minimum values which they go From left and right everything 4 and 7 from every 7 seven four is de min of ok d maximum and minimum so maximum every is what 7 and minimum and maximum ok so this is ho this is working I hope you go some idea about it End Let's C D Code Once Code Global Variable Tu Show D Answer And Will Return This Answer Will Be String D Maximum Value V And C Will Be Returning A Par As We Say Every Will Be Returned Because This Par Will Be String D Disperse Will Store the max and minimum OK so IF root is a maximum right first of maximum so minimum so first for minimum you can just give max value and for maximum you can give minimum just opposite OK NDAcall having d left minimum maximum value minimum value and maximum Value right call will give you d right minimum what is d minimum value d right seventh and d maximum value in d right something after date your answer will be what is maximum of root value - d minimum and root value maximum of root value - d minimum and root value maximum of root value - d minimum and root value maximum mines here root value ok smaller And when minimum of what you are doing when you have to return minimum of d root value and d left minimum and d right minimum dat this root value left minimum right minimum maximum value will be root value left maximum right maxi I hope you understand the Problem and approach let me know in d common of d tree are not using other extra space every apartments base if you are not considering d recursive tax ok please like it subscribe to my channel and next video thank you
|
Maximum Difference Between Node and Ancestor
|
string-without-aaa-or-bbb
|
Given the `root` of a binary tree, find the maximum value `v` for which there exist **different** nodes `a` and `b` where `v = |a.val - b.val|` and `a` is an ancestor of `b`.
A node `a` is an ancestor of `b` if either: any child of `a` is equal to `b` or any child of `a` is an ancestor of `b`.
**Example 1:**
**Input:** root = \[8,3,10,1,6,null,14,null,null,4,7,13\]
**Output:** 7
**Explanation:** We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
**Example 2:**
**Input:** root = \[1,null,2,null,0,3\]
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[2, 5000]`.
* `0 <= Node.val <= 105`
| null |
String,Greedy
|
Medium
| null |
496 |
okay so today we're looking at question 496 nick's greater element one the next graded element of sum element x is an array in an array is the first greater element to the right of x in the same array you are given two distinct zero index arrays numbers one number two numbers two is a subset of nums one for each zero i between zero to nums one length find the index j such that nums one at index i is equals to num stu at index j and determine the next greater element numbers to j in at index j in nums two there's no greater element than we the answer is minus one so we're supposed to return an array of answers of length nums1 dot length such that the answer at index i is the next greater element as described above okay that's a lot so let's just look at an example uh the example one here how do i shift this thing ah there we go okay so we have nums one oh wait a minute how do i okay you know what i'm gonna shift this back and i will switch screen to a nicer looking more aesthetic background because apparently it helps with learning and problem solving i think uh numbs one four one two nums two one three four two okay so given these um memories what we wanna do is basically we see element four we look at the element for in numbers 2 and we see if there is and if there is any larger elements to the right of this to this number so 4 to the right there's no more numbers bigger than 4 so we put in our resultant array result array minus one next we look at number one we see that for number one the um there is one element i mean there's two elements greater than it but the immediate right element that's greater than one is three so we put there three and lastly for number two we can see that there's no more elements to the right of 2 so we again do -1 in the end we return the again do -1 in the end we return the again do -1 in the end we return the array minus 1 3 and minus 1. let's check our answer okay looks correct so how can we solve this we are going to uh construct a dictionary where we have we traverse through numbs two ones to figure out what is the pairings between for each of the numbers in numbs two so we construct something like this dictionary construct something like one the rightmost one is three and then three the rightmost one is four uh four there isn't any so we don't we can either put it into the dictionary or just not even bother with it so let's not bother with it and two there's no more right most elements so we end off with this temporary dictionary and then taking this dictionary we can traverse through uh num one nums1 array and then we check oh four there isn't a key in this dictionary right so we put -1 there -1 there -1 there one oh one has like a uh the key one has the value three so we put there three and then lastly uh two doesn't exist in the dictionary again minus one so how do we construct this um what do you call it uh pairing right we can do something like have a temporary stack and then we start pushing things on to it and when we figure out when we find out that there is a larger element we can pop it off the stack right so uh we push one first and then we compare three and one and we see that three is larger than 1 so we have found the wait is it strictly larger let's check greater than right okay so there will not be any repeated numbers all numbers in the arrays uh unique uh let's push one on and then we find that three is larger so we do not we pop it off and we found the pairing for uh 3 and then remember that we need to do the same for and then we push three onto the sack and since four is larger than three we do the same thing for three and then we push four onto the stack uh that's two is smaller than four so we don't do the popping thing and we push it on and that's the last uh element to be examined with our stack so-called so-called so-called so let's try another example of say uh maybe one two one three four let's say this right so the answer for this should be something like two is to goes with three one goes with three goes with four and go four goes with nothing am i right uh yeah i think so okay so again let's try with this stack uh push two on one is smaller so we can uh how do you say this we can continue pushing it onto the stack okay that's fine and now we're looking at three is bigger than one so popping three off and then pairing it with three and again we look at our next element 2 is also smaller than 3 so we continue popping 2 off the stack and then comparing with finally stack is empty we push 3 onto the stack now we're examining four is again bigger than three so we pop three off and then pair it with four okay so now on to the code clear this board there's a few things that we need right number one is the temporary dictionary oh what's going on temp stack first oh what's going on with the indentation this is really weird let me refresh the page okay the indentation is really weird but let's just try again stack oh okay it's fixed now uh tam dictionary we have a temporary dictionary okay so now we start off by traversing nums to array first uh for i in nums to oh hang on while stack and stack topmost element is topmost element we want it to be uh we can continue pushing it if it's smaller than so we want larger than right larger than the topmost element if it is large wait is it larger than no if it's smaller than the element that we're looking at then we do the popping right okay this is confusing to me like the legend when it comes to larger and smaller than it yeah okay so then what we do is we pop num is maybe i should just name this stack instead pop num is stack dot pop now we have the pop number uh and then what we can do is once we pop it off the stack what we want to do is assign that to s key to the dictionary to our current eye yes temp dick pot num is hey hi okay so we're done we've done our popping and then at the end of it we do stack dot append our i so at the end of this uh we should be we should have our uh temporary dictionary of pairs and then for num in nums 1 we traverse through it and then if nam in temp dick if it is it can be found in the temporary dictionary it means that there is a greater element then we oh we have to have a resultant array as well right can we modify it let's just modify it i think it's fine to modify it yeah norms 1 okay let's do by index for i in range length norms one if one i in temp dick if it's in the dictionary that means there is a pair so we want to write it to i we want to assign it the value of attempting nums one i else this one at this position we wanna assign it minus one okay in the end we return norms one let's try this code okay great so thank you for watching this video
|
Next Greater Element I
|
next-greater-element-i
|
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
| null |
Array,Hash Table,Stack,Monotonic Stack
|
Easy
|
503,556,739,2227
|
46 |
Hello hi guys welcome back point wise and today's demanding question to join but in mutation service what is the first hard work to give are numbered here stitching is written meaning it will not be repeated even once ok return of the possible permission servi meaning Now I can do one to three, I want to subscribe. Are you getting injured by Amazon? Himmatnagar three places, 365 Navratna elements, if you get mail messages, how much time can you arrange? Okay, so less than three elements, keep three in the first position. We can put two on the second position or we can put this here and we can keep the last 201 * When we do that, can keep the last 201 * When we do that, can keep the last 201 * When we do that, our answer will come from Six Sixes All Software, if there were 4 green grass elements in it, then what would be the nerve to keep one first, four Then there are three, then there are two, then it is decided by the court, this is factorial. Okay, so the problem of time is that friend, whatever is your own, it is factorial. If the number of elements is given in time, then we have given these factorials. If your land is standing, then you would know what are its health etc., then you would know what are its health etc., then you would know what are its health etc., how to do it through the code. We understand this. Well, we do not have it, we will talk about it here. There are three options in one go for the first one and two options in the second one. In the t-shirt, we do one option like this, In the t-shirt, we do one option like this, In the t-shirt, we do one option like this, okay, you have 13 to keep it as the starting point, okay, in the second, we have put two, at the same time you tap here to keep it in the second position, then two. There will be options in all that I have kept it in the other one, there will be only two options to keep it, now if the guy has come then can he come to Sector-2, now if the guy has come then can he come to Sector-2, now if the guy has come then can he come to Sector-2, can it be ok at our place or I will see here, Guava 2 had come but can it be made? You can go here, similar to what has been done here, you can make it and then you can come forward. Yes, there is one option left for the horror show, it is not me, you, what is one option left that our three are missing, we gave it time 1234, you or we. Look at the National Organization Minister, trim it here, make it 2313, here too, Singh Rajput's has been closed, if you have our YouTube channel, you have made it 312 and the last number has been made 132, then you will see all the politicians with me, further whose total. Wisdom is that which is a class, this omega three factorial, one is that it will have to be maintained, you will have to work for an hour, this is a small job, I can have a light plate, so it will be cut, now schools are using extra, so that's why I'm going to subscribe a little bit and now if you see, if you subscribe towards this, then a new one started our body here one two three positions, I have cleaned some game in hours by sitting here. But what else Mangal Poonam has handed over to the police, kill me here, I have just kept you, okay, now if you meet such a multiple, then you are sleeping, multiples, then how come you come, we will discuss, let's start taking care, we have 120. His option Daya cannot be at his place again or he can take 120, it can take the place of bondage, you look at all three options, what did he say, leave me friend, if I look for you, keep yours everywhere, I will be there only when I Then I said no, friend, I am scared to offer Bittu wali, so two, Radha, I was sitting in the middle, then everyone said, friend, you were voting on Aali, but let's sit, so I, these were the three initial options, they were that now he is saved. Now we can hand over both of ours, we can use less of ours, we can urinate in days, again despite the option song, we will take lemon once for everyone and you are looking absolutely right, he will say, friend, cigarette, you have employment, I have one The bar will not say, now it is looking good, I will change it properly, then on the other side, I will change the other side, here one of the experts is closed, but we are feeling fine, but sitting in the middle here, it seems that it is not very good, friend, last. Let's sit in the last help and sit without one, is it the last to meet the family, not at all, if we go to the last, then our Prem Bhai options have come here that six permissions have become, this Mallika Sherawat went every time, there is current in her diet. From the index, we hit shop on it and subscribed that see, we had three options in the beginning, so the next one has three options, so take it in place or there is a further treatment, then we were engaged here. Imposition is the second option, if both the options are there, then take it to the place and go. In the last option, Tulsi will have to stay at his place, if you can't do anything else, then we have also written another one soon, other drivers of the court will do it. So I will understand better, okay, so what is he saying, whoever you have the option, give it in the format of Victor and person, it is understood that people make lighters, okay, it is easy to do it, I have not given the facility. Pass value pass that reference you will have to wash hair na I am acting ok make one your helper got it passed and passed the minimum on vectors end number here cent missile should be in abe condition tomato post everyone think then If the value of this condition cannot be equal to your number, then we will say subscribe, put Lal in the looting answer and go back, after that the tractor is your work, it is your work, I did not think that if we subscribe then go mature friend, you will have to put a loop. We are starting from the aaye, ok and ji set and going till here, namaz and literature will be done, so it's object will be Hariom plus, now cropping us, net welcome my sanam white, with a number of ji, I will tell him and the shop is done, now go helper, my name is Vrinda Plus One from the front and this is the one who used to make all your answers captive and then what will we have to do, we have to bring him back to Norway State, less original Singh, original and We are making changes in it. Okay, so I have to come back to the same state in which the team started it. We will click back. This is called tracking the talk. What is Batra now, so that in the upcoming video, we will keep the box and listen. So in that you will find that there is a difference between backpacking and carrier. Keep the bag. Kumli problem solving is your problem. Brute force is there. They cut in the middle so that we can move ahead and get some water. So I am here and we just brought it back to normal. Kat Mila is left. You come in your pocket, your bad leftover joint, we will send it to Nikhil, we will send it to you on e-mail, my friend, the name is here, on e-mail, my friend, the name is here, on e-mail, my friend, the name is here, start from 0 and do all the work, then I will transfer the data to you that I am running. I am near you and why should I submit it and see. Elder brother, you are watching. Brave seconds, hundred percent better than C Plus. President Polish. Now the last question is Try 20011. If you are coding quickly, then take a quick screenshot of it and explain to them that What happened, well, we have it, I say, I have given my name, Pawan Kumar has brought 253, ours is also zero, okay, we said, friend, have I come, your volume is not worth the size, friend, now it will go in this and subscribe and for 20 years we have He likes, ' we have He likes, ' Should I subscribe to his channel ? I will become okay' and he said, 'Just ? I will become okay' and he said, 'Just ? I will become okay' and he said, 'Just kill me with him. If you will speak, then worship him with me. Who said, 'Okay, okay with you, I will become worship him with me. Who said, 'Okay, okay with you, I will become worship him with me. Who said, 'Okay, okay with you, I will become yours' and it will be clear to him now. The yours' and it will be clear to him now. The yours' and it will be clear to him now. The recording is done, let me call you once more, okay, we will talk now, let's accept it, like it will open, let's do next, let's withdraw the cash, tourism has reached here, brother will say here 1243, it will come again. The size of 282 which is not only not the size is not a pimple, it will go into it, then this trick of yours which Stuttgart will clean it, okay and you will do plus one and fold it in this way, see here, it is on the side, free call is free. What will he remember, will vitamin help or not? Will he say, friend, I gave a little answer, go back - will go back, you will go, we will mix it, back - will go back, you will go, we will mix it, back - will go back, you will go, we will mix it, now guest, there is no use again, okay, now we will go back to the features, go to index 181, we will call Edison again. We will welcome you and give these theses first of all. Ok friend, let's go to his village for the purpose of fire control. Subscribe to Azam Print 2.2 Subscribe to Azam Print 2.2 Subscribe to Azam Print 2.2 and change it to say that after the war, we will use it here. Subscribe is in the village, let's do it like this, we will take it all. Now we will keep adding that next to this, the family has to make their own request, why don't you worry about your homework, if you make this point a duty, then you will understand this point much better, we are not doing anything, possible in all the indexes, the people on the right next to it. Okay right, with this we are doing the same thing that whoever has got the show will go ahead from that. Last month, if I click on Tulsi Roli Be Tu and opportunities here, then I don't know how big it was that Ali would have given it. I am you and this is ours, you go check it and try it, if you want to understand something then I will put it in this, see you in Delhi in the next video, till then
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
50 |
let's look at this problem poll so we have to implement our own poll which calculates the X raised to the power of n X to the n like this to 210 is 1024 there is a case that it might be - the M there is a case that it might be - the M there is a case that it might be - the M might be - so N is a 32-bit signed might be - so N is a 32-bit signed might be - so N is a 32-bit signed integer the round is like this okay so okay we have a naive inclination instead we just calculate the result right so the naive implementation so we so if you just count it to the end times at the time will be oh and the space will be just yeah there's nothing too serious constant so let's result b1 Wow and in speaker then so n - well any speaker then so n - well any speaker then so n - well any speaker than 0 so we loop it and the result equals x and then we return results it's very straightforward except that n might be - yeah what - it becomes this so we should yeah what - it becomes this so we should yeah what - it becomes this so we should luminize a problem okay if n is more than zero then X x equals one divided by X and N equals minus n now we can have all positive numbers what if n is zero yeah so it should work finished yeah it's work but it must be time they may exceed it I think it's too slow time limit exceeded t OE let's comment this out and try to improve it okay the next thing we came into my mind is that we can use a recursion but it doesn't help much right we can't get 2 X 2 n we try to get X n 2 minus 1 and then multiply it by X so actually the time is the same we cut its num tail its space will cost us extra cuts cost us extra stack which is Oh N but maybe it's a well we just say the first one is actually iterative okay net result because one if N equals zero there's no result if N equals zero we return one for the other case we return on the - of course we also need to do on the - of course we also need to do on the - of course we also need to do this normalization and say if say return my pole X minus 1 right now should work its run code Oh God they should not work yeah hmm maximum cost as a city of course because we use extra space they say and cost okay this one is not also not possible we need to find that other solution is that during recursion we can find that actually if we want to get to the eggs 211 we can actually get X - 5 the eggs 211 we can actually get X - 5 the eggs 211 we can actually get X - 5 and then square it and X right so things become a little simpler because we forgot to get my PO of n if n is odd then we say we return my Paul - is odd then we say we return my Paul - is odd then we say we return my Paul - one gets the minimum 1/2 / - yeah and then square it and then / - yeah and then square it and then / - yeah and then square it and then times X if he's even we just say my Paul X and we can have this and the base function is that if n equals 1 we return X this should also working yeah it's accepted okay so improve recursion it's not tail but time yeah it's obviously we every time we kind of cut down the calculation so it's actually it's like binary search it's not in time they're just there is actually a stack because it's long tail for space like meaning of it stack the distal stack is log n yeah can we do better we try to write this in the iterative way improved iteration oh this is not from me I just read the solution and try to explain it okay so let's say act if you won't get the power of 11 and we're trying if we cut down like this actually we want to do the same as the recursion the improved recursion way it's like we try to calculate the squared results iteratively like it's kind of like just to get to the binary form of the number right so for looking at for freedom but 413 is actually in binary is 1 z 1 right it's equals to 8 power 8 plus 4 no its first 3 2 plus 2 1 right and we can see that actually we can get the result at this because it's that the it's the PO of the number so for these forms actually we can just to say it's like this right x and good thing is that in binary right in binary form binary format you actually can get like from right to left it's to 0 - 1 - 2 - 3 it's to 0 - 1 - 2 - 3 it's to 0 - 1 - 2 - 3 so the actually what we need is to collect the digit where binary the bit where it is 1 right because we need to collect sorry this is not 1 this is 0 because this is 1 so we click this is 1 we collected this is one collect this one right so just we just start get them and am i right yeah that's all so if we just to traverse through all the bids from right to left we can you fail this one if it is odd we just collected the result if it's zero we ignore it but we need to calculate the base right this is the base and just to continue at last there will be also own only one right the first significant bit and then we just collect it so we need to try another way first one is there's a result there should be because we're we start with the first digit the result should be one that the base should be X right because this okay we just x2 to 0 this month I think this is more understandable okay so Wow and do we need normalize yes we need normalize need to normalize in this modern 0 X equals 1 divided by x equals minus n so why any speaker than 1 why we end at one because at because already have the base of one okay or stop at one okay don't forget to minus decrement okay so now we need to some thing is if any zero make sure you return what okay now let's get it down so if any odd number which say that the last bit is zero is 1 then we need to collect the result right so result should be times the base because this is time the base and then don't forget to update the base should be this right so more to square yeah it actually should be what is it so it should be actually okay base actually because this is this one if we square it will actually be mmm wait a minute so it yeah times two yeah this base okay so that's done we go to next one don't forget at the base should be updated every time here so and then if and if it is odd number don't we don't minus 1 here and equals n minus 1 divided by 2 if it is even number okay we don't connect the result but we update the base so we can ignore skip it and N equals n minus 2 naught divided by 2 and then finally it stopped at N equals 1 so that is the last one 1 and then we will collect the result right result is out equals base return result if you're working you should work yeah except it one thing is that I think that maybe we can just stop at zero possible if equals how can we get that this one right X to zero if that's the case if a bass should you also be xb1 if we don't say the base we just say the base right mm-hmm just say the base right mm-hmm just say the base right mm-hmm seems not very simple why not start with zero because we're handling the first bit there should be a basic base the base is X we are incrementing the base by X square not one not X right so yeah this is the best result I mean base because it's this one so there's no more if we got to like this it's gonna be my half it's gonna make things bad anyway that's all for this problem thank you
|
Pow(x, n)
|
powx-n
|
Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`).
**Example 1:**
**Input:** x = 2.00000, n = 10
**Output:** 1024.00000
**Example 2:**
**Input:** x = 2.10000, n = 3
**Output:** 9.26100
**Example 3:**
**Input:** x = 2.00000, n = -2
**Output:** 0.25000
**Explanation:** 2\-2 = 1/22 = 1/4 = 0.25
**Constraints:**
* `-100.0 < x < 100.0`
* `-231 <= n <= 231-1`
* `n` is an integer.
* `-104 <= xn <= 104`
| null |
Math,Recursion
|
Medium
|
69,372
|
1,213 |
so lead code practice time so in this video there are two goals the first goal is to see how to solve this problem uh so first of all we are going to do a solution searching and also we are going to do some coding work and the second goal is to see how we should behave in a real interview so let's get started so in real interview remember the first step is always try to understand the problem if there is anything unclear please bring out the question and also at the same time think about some hash cases so let's take a look at this question intersection of three sorted arrays so given three integer arrays array one two and three sorted in strictly increasing other return a sorted array of only the integers that appear in all three arrays so example one we have array one two three here and output is only one five because only one five appear in all the three uh arrays so let's see some constraints so every array the length of every array is between one to one thousand and the number within the array should be within one to two thousand okay so i think it makes sense uh and i don't see uh some very clear ash cases because each of the array is going to be not empty so let's think about how to find the solution so how to solve the problem so first of all a very uh a very um obvious solution is to have a hash map uh and uh to the hashmap the key is the integer and the corresponding value is the frequency and we go through every number within the array try to update the number and the frequency in the hashmap and finally we will iterate through the hashmap and see uh which number has frequency s3 so the for that one the runtime is going to be linear to the lens to the sum of the lens of all the three arrays and the space wise uh it could be also uh the same similar like linear to the length of all the three arrays uh let's see if there's any better solution for us to save some space so let's say if we have a pointer three pointer it's a pointing at the very beginning the three pointers point to the index of the three arrays so let me give you an example so let's say this is array one two and three we have three pointers and let's say this is p1 and this is pointing to uh p2 this is a p3 so at the very beginning all the three pointers start at the beginning of each of the array and we will do the comparison to see if the number is eyeline among all the three arrays if yes then we just need to proceed everything to the right by one otherwise uh we will just uh proceed the smallest the index pointing to the smallest number to the right by one so in this case we are just going to proceed here one by one and uh it is not eyeline then we are going to pro to move p2 to the right by one and then we see that it's still not online then we are going to move p one by one because it's pointing to three which is the smallest and currently next time we are going to move p4 by p3 by one and then this time you're going to move p1 by one then you're going to move p3 by one and you see that another uh number uh five and we add it to the result list and then we are just going to move p one by one so on and so forth until um the until any of the point run out of the range so the runtime for this approach is going to be all of n and space wise is going to be all one so having said that uh let's get started and do some coding work so for coding we care about the correctness of the code the readability of the code and of course uh the speed is also a concern so let's see um first of all we have the integer array as the intersection new linked lists so we're going to say okay we have three pointers in p1 and p2 and uh the p3 and um it's like well uh py a smaller e code smaller than or a one lens and the p2 is smaller than every two gallons and the p3 is smaller than array three that lens so we are going to say um if um every one p1 is equal to r2 p2 and array one p one is equal to array three p three so that's this time we encounter a number that exists in the other three arrays so we are going to have intersection dot add the array 1 p1 and move other pointers p plus p1 plus fc2 plus c3 and the other y and then we are just going to continue otherwise uh it is um uh it is a mix there is some place that has mislea missile line so we are going to say um we need to find the index that has that is pointing the smallest number so let's say the small list num as equal to everyone p1 and so let's say uh which this is the smallest number and uh i'll we need to decide which one to move um so this is the smallest one or uh we could actually have an array which would be simpler actually let's say p is new industry so in this way we would just say this is p zero uh p0 p1 p3 the exact way to represent the pointer so it is then p0 this is p uh one this is p zero this is uh p2 so something like that uh so this is p zero one this is the two all right so now we have the smallest number and the smallest idx as equal to zero so if uh arr two this is uh p0 so if a r2 p1 is if it is smaller than small list num then you're going to have the small list idx as equal to 1 and if the ar p 2 is smaller than small list num then we are going to have smallest idx as equal to two and then finally we are going to plus uh p uh smallest idx uh yes and then finally we are just going to return intersections intersection interception okay so that's pretty much it about the coding uh let's see let's do some testing so we are going to go through a example to explain this piece of code and also at the same time do some center check about the logic so let's use this example one so first of all everything is pointing to this is p0 this is p1 and this is uh p2 and we have a result so at the very beginning uh one so all the first numbers are one so we are going to add one into the intersection and then proceed all the indices and then we see we have the smallest number as early on p0 which is two and we see that the smallest index as equal to zero and after the comparison we don't see anything smaller than two so you're just going to press it p0 and similarly next time we are going to press p1 so on and so forth so i think overall it should be workable uh let's give it a shot that i run this piece of code so it is uh everyone p okay so i forgot to change this one intersections okay let's fix the title so it is array uh this is array 2 p1 this is the restraint e2 okay so intersections all right so after fixing all the typos i think it should be good let's give it a submission yeah so i think everyone everything works well now so that's it for this coding question about the solution if you have any question about the puzzle or about the solution itself feel free to leave some comments below if you like this video please help subscribe to this channel i'll see you next time thanks for watching
|
Intersection of Three Sorted Arrays
|
handshakes-that-dont-cross
|
Given three integer arrays `arr1`, `arr2` and `arr3` **sorted** in **strictly increasing** order, return a sorted array of **only** the integers that appeared in **all** three arrays.
**Example 1:**
**Input:** arr1 = \[1,2,3,4,5\], arr2 = \[1,2,5,7,9\], arr3 = \[1,3,4,5,8\]
**Output:** \[1,5\]
**Explanation:** Only 1 and 5 appeared in the three arrays.
**Example 2:**
**Input:** arr1 = \[197,418,523,876,1356\], arr2 = \[501,880,1593,1710,1870\], arr3 = \[521,682,1337,1395,1764\]
**Output:** \[\]
**Constraints:**
* `1 <= arr1.length, arr2.length, arr3.length <= 1000`
* `1 <= arr1[i], arr2[i], arr3[i] <= 2000`
|
Use dynamic programming. Let dp[n] be the number of ways that n people can handshake. Then fix a person as a pivot and turn for every other person who will have a handshake, the answer is the sum of the products of the new two subproblems.
|
Math,Dynamic Programming
|
Hard
| null |
1,458 |
hello and welcome to another video in this video we're going to be working on Max do product of two subsequences so here you're given two arrays nums one and nums 2 and you want to return the maximum dot product between non-empty maximum dot product between non-empty maximum dot product between non-empty subsequences subsequence is uh array which is formed from the original array by deleting some characters or none while the positions of the rest are the same so should be familiar with the subsequence that Parts pretty straightforward and essentially let's just kind of go through some of these examples so for this first one 21 -25 and so if you're not familiar with -25 and so if you're not familiar with -25 and so if you're not familiar with the dot product normally you have two vectors with uh an equal amount of values but essentially you just multiply two values of the two vectors so for example like you can multiply this like two and three normally like I said they would have the same uh length and then you would just multiply corresponding Ines and add all that together so it be like 2 * 3 + 1 * that together so it be like 2 * 3 + 1 * that together so it be like 2 * 3 + 1 * 0 Plus -2 * 6 and so on but given these 0 Plus -2 * 6 and so on but given these 0 Plus -2 * 6 and so on but given these are different lengths essentially now you can delete some elements so you can just say like okay well maybe I'll delete this element and then I'll like multiply all these or you can even delete most of it right so you can even delete like this and then you can say like I'll just multiply the 2 * 3 the like I'll just multiply the 2 * 3 the like I'll just multiply the 2 * 3 the only constraint is that it has to be a nonzero subsequence so you can't just say like I'll just not use anything so that's the only constraint which is going to be a little uh it's going to be important so uh it says the maximum here is 18 so if you multiply uh what does it say here 3 * um let's see 2 what does it say here 3 * um let's see 2 what does it say here 3 * um let's see 2 * -2 is going to be one of them or * -2 is going to be one of them or * -2 is going to be one of them or actually oh okay never mind actually so they're saying you want to take two -2 they're saying you want to take two -2 they're saying you want to take two -2 from the top and you want to take 36 actually Mis wrote this is should be like this so if you did if you take these two subsequences then their do product would be like this right so it be 6 + 12 and you get 18 and so that's be 6 + 12 and you get 18 and so that's be 6 + 12 and you get 18 and so that's the maximum there um in the second example so you have 3 -2 and then you example so you have 3 -2 and then you example so you have 3 -2 and then you have 2 -6 have 2 -6 have 2 -6 7 and you want to take three from the first one and you want to take seven from the second one so you would get 21 here and in the third example you have1 1 or 1ga 1 and so this one is kind of will give us a little bit of intuition so you could see here actually like the dot product no matter what you do if you take a subsequence DOT product will be negative and that's going to be important so basically this problem is pretty straightforward right like you just have two arrays like let's just go back to this first example so let's get rid of all this and let's go back to this first example so let's say we have a 21 -25 and then you have -25 and then you have -25 and then you have 306 essentially all you really need to do is just try to maximize your dot product and so you have the option of like multiplying like let's just kind of look right like let's say we start at some index here and some index here so we have a couple options right and let's just kind of write those down so a we can multiply these two values and add them to our result and if that's the case then we would just move up our indices right so then we would just like compare these indices we can do that and then B we can just move we can just ignore one of the values and move the pointer up to the next one right so like we can just say like maybe we don't want to do this maybe we want to delete one of these right so this would be like the deletion so maybe we want to delete -2 if you delete Nega we want to delete -2 if you delete Nega we want to delete -2 if you delete Nega -2 we would just move this in index up -2 we would just move this in index up -2 we would just move this in index up here or maybe we don't want to delete -2 here or maybe we don't want to delete -2 here or maybe we don't want to delete -2 maybe we want to delete three so then we would move this index up here right so essentially you just you have those you just try to maximize those two things uh either take the values and multiply them or just delete one of these and by deleting I mean just moving the index up and then getting like the recursive case there so this pretty much going to be like a pretty simple dynamic programming problem and let's kind of like go through our states and then we're going to see why this part is important so for the dynamic programming let's just write down like all our steps as usual so we have our states so for States uh you can do this one of two ways and I'll kind of talk about that a little bit later but essentially let's just write like um the things that we have to have and then we'll talk about the other part so for the states we have to have uh index one and index 2 right you have to have it you have to know like where you are in the array uh base case and this one is also going to change regardless of which or regarding which solution you pick and I'll talk about that as well so base case let's just say for now uh either i1 or I2 is out of bounds right like we just went through our stuff like let's say we're over here on this one but then on the second one we're out of bounds so we can't really take any more products right so if one of these is out of bounds then we're just going to want to return um yeah so one of these is out of bounds we are going to want to okay there we go return zero for now and I'll talk about like the extra thing that we need to think about right because we can't multiply anything else and then the recursive case is kind of the thing I was saying up here so we maximize a take both values get product and add to and then what's going to be our like recur verive State well that's going to be prettyy straightforward right so if we take both the values we're just going to increment both into C so we'll get the product and we'll add that to DP i1 + we'll add that to DP i1 + we'll add that to DP i1 + 1 and I2 + 2 that's one of the cases B 1 and I2 + 2 that's one of the cases B 1 and I2 + 2 that's one of the cases B we uh remove element from array one right so like this would be like we are over here let's say and we're saying we don't want to use this two we're just going to remove it so that if we want to do that then what's going to be the our DP state so there's going to be no value there but it's just going to be DP i1 + one but it's just going to be DP i1 + one but it's just going to be DP i1 + one and then I2 is going to stay the same and then the other Cas is we remove element from array2 right so DP i1 now is going to stay the same and then I2 is going to move up right so the it would be um in If instead of removing this element we want to remove like the three and we want to move this up and you don't want to move both of them up if you don't use them because otherwise you're just going to like miss out on comparisons like let's say two and six was like our optimal solution if we just move both of them up we're never going to hit that so if we choose not to get the dot product here we can say like okay let's just move this up here and then maybe we'll choose not to take it sometime later so we move this up here so we're actually going to get to this case and we're obviously going to have like a cache as well for a base case so let's think about the problem with that the problem with this is if we try to maximize and let's kind of like walk through the maximization of this solution here and let's see the issue so let's say we have negative 1 or negative 1 and then one so when we first get to our numbers we're going to try to maximize um either taking both of them or moving one of them up right and remember our base case is zero so if we take both of them we're going to get a negative result and so in reality we never really want to take a negative result because that would make like normally if you're trying to maximize why would you take a negative result right you can just ch choose to pass so let's see what happens if we pass right so it doesn't really matter actually like which one we move up but let's just say we move up this one first so let's just say we choose to pass and then we move our index up over here and now we are on this case and once again we're going to choose to pass like no matter what state we're in we're always going to choose to pass and once again it doesn't really matter which one you move up because eventually you're just going to go out of bounds on one of them but basically what's going to happen here is you're going to choose to pass on the whole thing and then you're going to return zero because the max like when if you just try to maximize um these three things the case of b or c will always be greater and then you're always just going to end up at your base case and not take anything and that's a problem because they said in the problem that you actually do have to take a sequence right so if every single dot product in if every single combination is negative your maximal result will actually be zero but then you don't actually want to do that and you have you want to figure out a way to like differentiate that somehow right because like if you actually had a zero here like let's say zero was one of the values then this would be fine right then you can actually just return the zero and so you have to find a way to differentiate this from this case here and there's two ways of doing that um one you can add another state in your DP so you can add another state and that's what I originally did you can add state of like used the number or something and then what would happen is in your base case if you never used the number you would just return negative Infinity so you would return negative Infinity here or sorry uh yeah it would no it would be negative infinity and that would ensure that like any case where you didn't use anything would give you the worst possible result so that therefore you are guaranteed to use something and then basically what you would do here is in this state you would just uh anytime you use a number you would add you would put that as true and then if you didn't use a number you would just pass on whatever it was before right so if you did use a number you would just pass that on so you'd say like use a number something like that you essentially just pass that on and that then that would be like a valid solution and then it's not going to take up any more space because if you think about it um like if we have i1 and I2 and then like a Boolean then our number of states is just i1 * I2 * 2 i1 * I2 * 2 i1 * I2 * 2 so like in Big O it's not going to take any more space so that's one way to do it where you could just add a Boolean for like did I use a value and then anytime you never use anything at all you would just return negative Infinity as a base case um but the other way you could do it that I'm going to do and I'm also going to do that for uh for the uh like bottom up solution we will actually talk about the bottom up solution is we will essentially just get them in Max for all these things and so if the max for one of these is negative right so let's say the max here is negative and then the minimum here is positive so if this is the case that means we know every single number will be every single number in a do product will be negative right because every single number here is negative every single number here is positive so that's if that's the case then the dot product will be negative so then we'll just kind of like short circuit and we'll just say okay well we have to use one number in each what do we want to use so then we want to use the greatest number here right the like the greatest number meaning the smallest negative number and then the um the biggest positive number so we're just going to check for that case and then the other case is just the reverse of this so if the Min of this is positive and the max of this is negative then also we will just short circuit and we'll say like okay let's take the biggest positive number or actually sorry we're going to want to take the small the smallest positive number right cuz the results going to be negative so if one of these is all positive numbers like let's say we have like 1 2 3 4 five and then all of these are negative like this is kind of the case we're checking for if all of these are negative so let's say these are like this and we can just check this like to check this is an O of n time so because our solution is OV Square doesn't really matter so if this is the case right if this is the case or the reverse is the case then we will basically take the smallest number here and the biggest number here CU that's going to give us the smallest like we're always going to get a negative dot product but we want to have like the least negative dot product so we'll take the one here and the negative one here and that's how we'll like handle that case where you don't you do take a number and then as long as um there is at least a zero or a positive number like as long as not every single dot product is negative uh this will be fine then like this will work but if you didn't do that you either have to have that extra um that extra state or this like min max track and we're going to use a min max track because we're going to use that for the bottom up as well okay so now let's code up the recursive solution here so first we're going to have that min max check right so we'll say uh we're also going to actually rename these because we're going to use these a lot so we're just going to rename these to m&n just to make it to m&n just to make it to m&n just to make it easier okay and so we're going to okay if Max n or I guess you can do it whatever way right so if Max n is less than zero meaning the biggest number in N is negative and Min m is greater than zero so that means every single number in N is negative every single number in m is positive that means we're guaranteed to have like a negative dot product let's just return the max n meaning the least negative value in N right we're going to try to minimize this essentially and then we are going to return the Min of uh M so that's one of them and then basically it's the same code uh like just swapped around for these so MN right so that kind of handles our case for negative dot product and now we can do like a normal uh solution like we can use this for all of our Solutions so we're going to do the uh recursive and we're also going to do like the space optimized bottom up here cuz this one's a little bit simpler it's more like a medium problem so we're going to have m&n is going to be the going to have m&n is going to be the going to have m&n is going to be the length of these so m&n equals length of the array these so m&n equals length of the array these so m&n equals length of the array M and length of the array n get the length and we're going to use this for everything as well so we're going to have our visited and now we can just do a normal easy memorization DP of index one index 2 and we're going to say if index one or index 2 is out of bounds so if i1 is M or I2 is M whoops okay so if any one of these is true let's return zero and we handle the case where everything is negative by just short circuiting here so we're not going to have the problem of you know like I said if you did this without this then if your uh if your do product was negative you would return zero and that would be a problem okay so now we're going to have the caching case so if uh i1 I2 inv visited return visited i1 I2 so we have the caching case now we just simply maximize out of the three options right that I talked about so visited i1 I2 equals maximum of these three Cas M i1 and this is going to be the first option that's going to be taking both of them and actually getting the dot product so mi1 time uh n I2 plus DP of moving both of these indices up so right so I 1 + one I 2 + indices up so right so I 1 + one I 2 + indices up so right so I 1 + one I 2 + 1 okay now we have the other two cases where we just move one of them up right so it's going to be DP of i1 + 1 where so it's going to be DP of i1 + 1 where so it's going to be DP of i1 + 1 where we don't take the dotproduct or uh the I2 is going to stay the same here and then we have the other solution of DP i1 and I2 + one okay and now we of DP i1 and I2 + one okay and now we of DP i1 and I2 + one okay and now we will just return that so we're going to return visited of i1 + 1 and I2 + 1 i1 + 1 and I2 + 1 i1 + 1 and I2 + 1 and there we go actually this not this should not be this should just be Vis to so there we go okay so that's just our DP function and then finally we're going to call it right and what indes do we want to start off at 0 so we want to call it and we want to run it see what happens okay um so let's take a look okay so you can see like it does work but it's not super efficient so now let's actually go through and let's think about the bottom up solution and the optimize bottom up solution and then we can code up the optimize bottom up solution essentially I'm just not going to C up the normal bottom up I'm just going to do the space optimized bottom up and actually figure out like a easier way to do it so we're just going to go straight for that one um right after we talk about like how to do it okay so let's actually maybe take this and move it down over here okay and the solution we're going to do is example two it's a little bit smaller so essentially um if you think about like what our base cases should be for the bottom up let's kind of draw at our stuff so let's say uh and also we what we want to do obviously or not obviously but just like for bottom up um because we're going to be using a we're going to be using one array like a 1D array I'm going to show this with a 2d array but we because we're going to do a 1D array we're just going to say like we're going to take the uh the shorter array and use that for a space so because in the space optimized bottom up we are going to have an array of one row and a bunch of elements be we're going to go through this example but we're going to want to swap these first essentially so um yeah because our space optimized bottom up is going to hold like one of these so we'd rather hold the smaller one so essentially we're just going to swap these two so our two arrays will be uh the row will be 267 and then the column will be 3 -2 and 267 and then the column will be 3 -2 and 267 and then the column will be 3 -2 and we're going to get the dot product this way and so if you think about it um so for the row we're going to need four elements and I'll kind of explain why let's actually draw this different line let's actually use lines so there we go so we're going to have four rows um yeah okay and we're going to have three columns not the best uh let actually like do this not the best drawing but it's okay so for our Row the values are going to be uh this right so it's going to be 2-6 7 so let's actually it's going to be 2-6 7 so let's actually it's going to be 2-6 7 so let's actually draw those to make it easier it's going to be 2 -6 and 7 and for our column it's to be 2 -6 and 7 and for our column it's to be 2 -6 and 7 and for our column it's going to be 3 -2 okay and now so what going to be 3 -2 okay and now so what going to be 3 -2 okay and now so what you want to First do is you want to initialize like the reason we created one extra one for both of these is because if we're out of bounds on one of them we want to be returning zero right like in our memorization if we go back we want to be returning zero right if we're out of bounds that's our base case so that's kind of how we're representing that so all of these out of bounds should be zero so it's z0 z okay and so now basically um if you think about it for like every Square what are three options and let's kind of think about like where they would be so option A is take the value at this Row in this column right so we can actually write these down so option A take value at row and column and then add DP I + 1 j+1 right or something add DP I + 1 j+1 right or something add DP I + 1 j+1 right or something whatever like index we're on right so if we take the value and actually get the dot product we're going to add uh the like our indices are going to both move up by one and then the other two options is we have I + 1 is we have I + 1 is we have I + 1 J and DP i j + one so pretty much all we J and DP i j + one so pretty much all we J and DP i j + one so pretty much all we have to do is we're going to just go backwards and we're just going to Simply say like what's the biggest thing so I +1 J is over here right like it would +1 J is over here right like it would +1 J is over here right like it would just be moving up in the row and then um j+ 1 would just be moving down here and j+ 1 would just be moving down here and j+ 1 would just be moving down here and then if we take the value then we have to add one to both the row and the column which would be down here so let's kind of like walk through what those would be so for this we actually wrote this down so if we take the value we'd have -14 + 0 so obviously we wouldn't have -14 + 0 so obviously we wouldn't have -14 + 0 so obviously we wouldn't want to do that right and then the other options is either this value or this value so either one of these is fine so here we're going to have a zero okay now we're going to go here and we're going to be basically the order we're going to fill this out is we're going to fill it out row by row backwards because to get the value we need the value to the right and the value down so you always want to go right to left for the bottom of DP here okay so here we have 21 if we take this right and so we would want to take it because that would be bigger so we either have 21 or Z or zero so we want to take 21 okay now here we're going to have 12 if we take it and zero so 12 and zero or Z so we're going to want to take it here and then here we're going to have -8 plus 0 or we can take 12 or to have -8 plus 0 or we can take 12 or to have -8 plus 0 or we can take 12 or we can take 21 so we're obviously going to want to take 21 and so now here we're we can take uh so if we take the value we'd have -4 + 0 if we take the value we'd have -4 + 0 if we take the value we'd have -4 + 0 right so it's take the value then add DP of this and I + 1 j+ 1's over here so of this and I + 1 j+ 1's over here so of this and I + 1 j+ 1's over here so we're going to have -4 + 0 or we can we're going to have -4 + 0 or we can we're going to have -4 + 0 or we can take zero or we can take 12 so we're going to take 12 and then here we can either Take 6 + 12 and then here we can either Take 6 + 12 and then here we can either Take 6 + 12 which would give us 18 right get the value and then the next value is over here or we take or we go right or we go down and so obviously we're going to want to go down and so if you take a look then you just return DP of 0 and then that would be like the exact value one and so for this essentially we made like a 2d array but keep in mind that every single value right like when we're getting this value what does it depend on it depends on this value and the value to diagonally to the right so if you notice whenever you get a value you only need to go one row down so like when you're filling out this row you're never checking here so as soon as you are done with a row like let's say you're you finish this row is no longer needed because you will never look here right whenever you're filling out a row you're only checking the row below it and the row itself so what we're going to do instead of like making a 2d Matrix here is we're actually just going to keep one row and let's kind of show let's do that for the one row and then we'll be done so essentially we're just going to make one row and we're going to make it like 00 0 to start off and what I did actually find is for space optimized instead of doing so for this one I don't know if you can do it completely in place like I don't know if you can do one row in place but the thing that I found that is a little bit easier is instead of keeping one row when you're going one row down you just keep two rows you keep your old row and you keep the new row you made so essentially we're going to start with this and then we're going to be making a new row so for the new row we're going to make a new row here and this is going to represent this row over here so we're going to check we're going to do like all the same kind of stuff right like where do we want to go so actually the row will be like this yeah and it will initially all have zeros but the only values we're actually going to fill out is these right because we don't need to fill out um we don't need to fill out these so actually I did mraw it a little so it's actually going to look like this um and the only values we actually are going to fill out are these two and because we are only going to the right or down we can get our values for the new row this like the new row and this is the old row maybe uh we're going to be able to check these values right and so we're going to be able to go down and things like that so for so essentially this value is going to correspond to this value over here and so we can like look at that again so we can either get uh -14 and the value over here which -14 and the value over here which -14 and the value over here which represents this value over here same thing right so we wouldn't want to do that so we'd want to have zero here so this zero is going to represent this zero here and then for this value we're going to either take 21 or uh or zero right because 21 it's going to be 21 and this value which we have access to or this value and so we're just going to want to take 21 here and now that we filled out our new row essentially all we do is we just make our old row equal to our new row and then we reset our new row so we're going to make our old row now equal to 21 here and then we're going to reset our new row and we're just going to reset our new row enough times to fill out this whole thing so now this is going to be zero and this new row now is going to represent so we filled out this row so this new row is now going to represent this row and the old row is going to represent this row here so this would be like 210 now we do the kind of the same thing for the newo again we only care about these two we don't really care about this last one so it's going to be the same thing like and we're just going to keep track of like a row and a column even though we're not making a 2d array but we can still like have uh numbers for the row and the column so here we can either take 12 and the number diagonal to the right so it be 12 and this number which would give us 12 or we can take the number to the right which is zero or the number down which is zero so we're going to want to take 12 right so we take 12 here which would represent this 12 over here and now here we can either take 18 and the number over here or we can either take 21 or 12 and so we're going to want to take 21 so we take 21 and now we are done with this row and once again we're just going to make our old row equal to this row here so and this doesn't cost us a lot of time because when you make something equal you just like you just point to the same thing in memory you're not really like uh you're not like copying every element so but yeah so this is going to be uh 212 now as the old row and then we're going to reset our new row one more time and now our new row will represent this one up here and the old row will represent this one up here yeah I'm not entirely sure if you can do this like all in one thing because you rely on the element to the right and the element over here so you can't really like these could have two different values so I think you might I think you do have to have like at least two rows for problems that you only need the element to the right and the element below is just going to be like you can just do that all in one place all in one row but in this one I think two is probably mandatory but anyway let's go for the last one so here we can either take -4 right uh -2 * -2 we can either take -4 right uh -2 * -2 we can either take -4 right uh -2 * -2 so we can take -4 and this which would so we can take -4 and this which would so we can take -4 and this which would be -4 or we can take 0 or 12 and just be -4 or we can take 0 or 12 and just be -4 or we can take 0 or 12 and just like in this picture take 0 or 12 so we just want to take 12 and last one here so this would be 12 corresponds to here and last one here we can take six and 12 which would be 18 or we can take 12 or we can take 21 so we'd want to take 21 and once again you're going to make our you're going to make the old row equal to the new row it already is and then finally we're completely done and now we just return the first element in the old row so that's how you do this with two rows and the key for space optimization is just like when you draw this 2D bottom up see how far you're going down and right and if you're only going down uh like one element or two or whatever like not too many then you can just keep that one chunk right so if you're going down only one element you can just keep this chunk active right your two rows if you're going down let's say like five elements you can keep a Five Element chunk and just keep rotating old stuff out so that's kind of like the uh like that's how you see if you can do bottom up space optimize just figure out like what's the maximum actually you're cursing and how much do I actually need here so now we can code up this uh space optimize bottom up so we are going to use this again so we're going to like we still want to have that thing to make sure that like if everything's negative we want to just return the smallest element because that's still going to be broken in our bottom of DP if we don't have that okay but now the rest we can just code up so we are going to so the other thing we can do actually is we want to ensure that we want to use like I said we want to use the smallest array for the column right so what we can do here in the beginning is we can just say like if length M is so we the um the thing we're going to use to make the um to make the bottom of DP is n so we want to make sure that length n is smaller than M so we can just say like if length m is smaller the length n we'll just swap those around right so we can just say like mnal n m so we could swap them around and now we're ensuring that when for when we do the space optimize thing like let's say you know since we are only keeping track of a column if this column was like a thousand and then we only had like three rows we just want to swap that around and it would still work so we're ensuring that for the space we're actually using the minimum and that's also super common for space optimized if you're only using one dimension just pick the smallest Dimension so now that we have that now we should be able to just like do everything correctly and our DP should be the minimum of these two so we're going to say let's just make it zero for something in range length n+ one where n something in range length n+ one where n something in range length n+ one where n should be shorter than M now so and then essentially we're just going to Loop through uh rows and columns and just update everything so we're going to say for Row in range of and I think this should be M minus one this one so we can check the picture here so if this row so here M would be uh three and we want to start at this row over here which would be two right so there's going to be this extra row that we're not using at all so we need to start here and then this n would be two and we want to start over here which would be one so that this incorrect so we're going to want to start there and we're going to make a new row and it's just going to be zero for something in range n + something in range n + something in range n + one and then we're going to go through the column here so every time you go to a new row you want to make this like new row and then we're going to make the new row and then we're going to update our old row to be the new row like I showed before so for column in range andus one- before so for column in range andus one- before so for column in range andus one- one - one - one - one new row column equals and then we have our three options right so our first choice is taking the two values and getting the dotproduct that's going to be M of row times n of column plus so now you want to think about like where you actually go so if we see this is the new and this is the DP so going down to the right we're not actually going down we're just going into the DP and we're going one column to the right and then going down is in the same column but going to DP and going right you're staying in this new so that's what we're going to be using so going down into the right we're not actually going down we're just going into the DP so that's one choice now going to the right is just going to be in the same exact uh in the same exact row and then going down is going to be in the same exact column in DP okay and there we have that and then finally we need to say uh after we go through the column then we need to say the why is this not tab correctly there we go so actually also I don't know why this is this that should be that and then after we're done with a column we're essentially just going to make our DP the new row and there we go and then finally we can return DP Z here this also doesn't look like it's tab correctly which is kind of weird okay see there we go and you can see this one's super efficient and yeah I guess the big reason I usually don't do too many space optimize Solutions as you can see this gets pretty lengthy especially for difficult problems but here it is for this one so we have our memorization and then we have our space optimized DP so let's talk about the time in space for this one so the time is going to be the same for both of them um it's just going to be uh M * n to be uh M * n to be uh M * n right the length of each one and the space for the memorization is going to be M time n because we have this visited cache um that's going to be m n States but for the bottom up it's going to be o of Min m * n because we're just picking of Min m * n because we're just picking of Min m * n because we're just picking the smaller Dimension and always using that to store our numbers so yeah that's going to be all for this one and if you like this video please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Max Dot Product of Two Subsequences
|
sort-integers-by-the-number-of-1-bits
|
Given two arrays `nums1` and `nums2`.
Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not).
**Example 1:**
**Input:** nums1 = \[2,1,-2,5\], nums2 = \[3,0,-6\]
**Output:** 18
**Explanation:** Take subsequence \[2,-2\] from nums1 and subsequence \[3,-6\] from nums2.
Their dot product is (2\*3 + (-2)\*(-6)) = 18.
**Example 2:**
**Input:** nums1 = \[3,-2\], nums2 = \[2,-6,7\]
**Output:** 21
**Explanation:** Take subsequence \[3\] from nums1 and subsequence \[7\] from nums2.
Their dot product is (3\*7) = 21.
**Example 3:**
**Input:** nums1 = \[-1,-1\], nums2 = \[1,1\]
**Output:** -1
**Explanation:** Take subsequence \[-1\] from nums1 and subsequence \[1\] from nums2.
Their dot product is -1.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 500`
* `-1000 <= nums1[i], nums2[i] <= 1000`
|
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
|
Array,Bit Manipulation,Sorting,Counting
|
Easy
|
2204
|
1,035 |
hey everybody this is Larry this is day 11 of the uh what's it called amazing what uh why do these things move around I'm a illegal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problems or problem uh I am gonna do the JavaScript thing so definitely hit the Subscribe button if you haven't and like just look for it on the like search for it or whatever today's five minutes 10 35 uncrossed lines so yeah you're given two integers away nums one and nums two and I'm gonna end up here for a second so I'm going to Athens in a couple of days um so if you're in Greece let me know I'm also going to go uh I didn't book that ticket actually but I'm going to Tennessee in Georgia I hope I'm saying that correctly um so if you're y'all in those areas let me know hit me up with rap a drink of food or whatever it is uh if you know things work out if not that's okay I guess but uh anyway yeah um and also while I'm doing that I'm gonna spam my Instagram things or like just hit the file on Instagram uh it's only if it's my uh it's my hobby so it's not like I'm making money off it because I don't want to make money off something that I enjoy uh because then that's how you make sure you don't enjoy it right so um it would just make me happier if more people like my photos and stuff like this and just follow along I guess if not that's fine but I feel like you know this is the closest thing as an ad as it gets and I don't even make money off that either so yeah anyway okay so let's take a look numbers one numbers two we may do a connecting lines a straight line connecting two numbers one and nums two such that they're equal the line okay so um intuitively uh or maybe not intuitively into intuition is something that you built through like years and years of practice so maybe that is the wrong way to say it but um but the way that the first thing that jumped out at me is gonna be dynamic programming um one of the things that is about dynamic programming is kind of finding the sub problems that we care about right um and not just sub problems but overlapping sub problems so that we can reuse answers that we calculated in another time in this particular case the sub problem is going to be the suffix of both these arrays right um and of course there's o of n suffix for the first of way and O of M say suffix for the second array so together there's gonna be m n times M so the first thing I do is look at the constraints and that's going to be 500 square and that should be good enough um and yeah so I think that should be good enough and we could do that um yeah at least unique numbers now um maybe a little bit awkward but that's okay um yeah I was thinking there are two ways you can kind of um match you can match directly or you could just skip so I think the way that I want to do a Skip and I'll explain what I mean in a second also my apology still I still am having quite a bit of allergies so uh if I'm like pausing and like just looking days it's not because I'm uh on drugs or something in fact the fight is because I'm not on drugs and therefore I have all these allergies uh but yeah okay so I would say this is everyone think that I'm trying to think a little bit about is um whether there's a better solution only because this is a medium so maybe this is too much of a kind of meta-analysis in that meta-analysis in that meta-analysis in that you know for me I mean I don't know it's not a hard problem but I feel like this is a Yeezy hard if you will uh and a hard medium if you haven't like you know got it all down uh that said there have been a lot of dynamic programs lately so maybe that's fine but yeah so then now we want to calculate max say from the suffix of the numbers one and nums two and of course for dynamic programming the suffix just begins with index one and index two right so we can kind of go do that directly um yeah if index one is equal to N1 or index two is equal to N2 then we return zero right because one of the arrays is already used so it's always going to be zero so that's your base case and then otherwise um when we turn the max of foreign of index of one is equal to num sub two index of two then we draw a line right so then best so and we would draw a line then the way to do that is just calculate max of index one plus one index two plus one and then add one two for one line that is drawn right otherwise you have two ways to do it you have either skip ahead on index one or skip ahead on the index two right so that's pretty much it that's the idea yeah maybe that's been enough and then of course you calculate from the whole prefix which is zero um of course this is going time out in a yeah given 500 is going to time out because this is exponential it has you know branching factor of two or three depending you want to say it right so we have to do wrapped ad uh memorization so let's uh let's do it right so then now uh let's just ask cash and of course we all kind of analyzed this before uh index one is all you know all of N1 index two is O of N2 so the total input is all of N1 times N2 right uh yeah oh man sorry I still have trouble uh talking due to nasal issues but right and then you know other than that it's just setting up the cache as we do and yeah and that's pretty much it unless I'm wrong then you know then maybe there's more but no but that should be okay uh relatively comfortable about this one so yeah so let's give a Mist quick like three times quick submit and there you go 1136 uh it's a little bit on the slower side but yeah and the complexity is going to be of N1 times N2 because each of these is just all of One in time and space the past let me do the same password we did the same here and here as well um this is um there are faster Solutions I do they just oops I don't know what I could have done I mean you could also do that I did a top down but you could also do a bottom job it's pretty straightforward to do a bottom jump I'm curious like how people did it faster is it like an easier um OCS longest common subsequence um I guess that's the other way to look at it but it's still going to be the same complexity I guess they just do it Bottoms Up and that's fast enough yeah okay fine uh yeah space optimization yeah definitely if you want to look up to space optimization for LCS especially um I do have a video on that so definitely do that uh yeah otherwise that's what I have for this one let me know what you think stay good stay healthy it's a good mental health I'll see y'all later take care bye
|
Uncrossed Lines
|
cousins-in-binary-tree
|
You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
* `nums1[i] == nums2[j]`, and
* the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return _the maximum number of connecting lines we can draw in this way_.
**Example 1:**
**Input:** nums1 = \[1,4,2\], nums2 = \[1,2,4\]
**Output:** 2
**Explanation:** We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from nums1\[1\] = 4 to nums2\[2\] = 4 will intersect the line from nums1\[2\]=2 to nums2\[1\]=2.
**Example 2:**
**Input:** nums1 = \[2,5,1,2,5\], nums2 = \[10,5,2,1,5,2\]
**Output:** 3
**Example 3:**
**Input:** nums1 = \[1,3,7,1,7,5\], nums2 = \[1,9,2,5,1\]
**Output:** 2
**Constraints:**
* `1 <= nums1.length, nums2.length <= 500`
* `1 <= nums1[i], nums2[j] <= 2000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102
|
435 |
hello everyone so let's discuss a lead code problem for today and this is one of the problems within the blind 75 list today we are going to discuss problem 435 nonoverlapping intervals uh so the problem definition says given an array of intervals where every interval is defined by start value and an N value we have to return the minimum number of intervals you need to remove to make the rest of the intervals nonoverlapping that means you are given multiple intervals some of those intervals might be overlapping right so we have to remove say uh say like if they're overlapping we have to remove move some intervals obviously to make all the remaining intervals to be non-overlapping and we have to calculate non-overlapping and we have to calculate non-overlapping and we have to calculate what is the minimum number of intervals that we need to remove okay so let's look at the two examples here uh for the first example you see we have these intervals one two let's draw a time uh Tim line or real number line so one sorry this is one 2 uh 3 and four okay so this is one and then we have intervals 1 2 3 so 1 2 is this uh 2 3 is this right and then we have 3 4 and 1 three so one three okay now we see we have these intervals uh and obviously we see here that uh these intervals are overlapping right so this one a overlaps with b and c right okay here before you uh start solving your problem you should ask your interviewer whether uh these values like if the end value of one interval uh is the beginning value or the start value of another interval are they overlapping or non- overlapping they overlapping or non- overlapping they overlapping or non- overlapping right so in this case uh we in this problem they are not overlapping if they if the end value of one interval is beginning value of the other interval anyways here we see a actually is overlapping with B right is overlapping and a is also overlapping with C right now there are two ways to make the intervals all the intervals non overlapping one way is like if we remove say uh if we remove say B and C right sorry if we remove a so this is a and this is B and the sorry I just made the mistake again so I call this B and this is C so one way is just removing B and C right or the other way is like if I remove B and C you see what happens right so uh it's gone now the rest two intervals A and D remain like no one overlapping right uh but instead if we just keep these two and remove a even in that case these three become non-overlapping these three become non-overlapping these three become non-overlapping uh and in the first case we removed B and C so B and C are removed so two of the intervals are removed or in the second case we just removed a so one of the intervals are removed so there are two ways to make all these intervals no non overlapping right and uh the problem here ask asks for this solution that means we have to find the minimum number of intervals that are non overlapping okay so let's look at the another example let say the second example here uh so in the second example you see we have like one two and one two right so we have one two we have three intervals now all of them actually overlap with each other you see that right and this is obvious that we have to remove at least two of them right we have to remove at least two of them to make all the intervals non overlapping right that is a straightforward solution and for the third problem we see we have say one two and then we have 2 three and now uh you see that these intervals are not overlapping so in this case the result is going to be zero we don't need to remove any interval okay so how do we solve this problem uh obviously the first thing that okay another thing is uh we have to ask the constraints like is it possible that our input is empty uh here for this particular problem it says uh there are at least like two intervals so it's not empty but obviously in your interview the interview May say yes the uh inter interval length might be empty okay and the other thing is like uh so let's try to build some intuition so from the intuition we know that the first one first intuition is we have to anyways we have to find the overlapping intervals right okay so let's go to a problem so you see you have five intervals here and so as we said like that the first intuition is that we have to uh find the overlapping intervals right one uh okay starts from zero so 0 1 2 3 4 five 6 okay so this is the number line uh okay so first we have to find the overlapping intervals and as you know one of the common techniques uh is to sort the intervals right the sort the intervals and that way actually we can find the overlapping intervals very easily otherwise like it becomes overlapping checking overlapping becomes like order of n Square affair because we uh select one interval and then we have to check it against all other intervals right so we have to check it against the other n minus one intervals and we have to keep on doing this for uh every interval so that becomes order of n square if we don't sort but if we sort it actually it becomes easier in that case uh we can just check against our neighbors right so say 0 1 and then 1 three and we can actually sort it say based on the start value U and you can see like once we sort it becomes like the Sorting takes like for n intervals the Sorting would be n log n and then we can just read it Lally and find the overlapping ones so here for example say after the Sorting I will write them from a to a b c d e and f I'll write them like that so let's sort uh based on uh the starting value so sort based on the start value and if we do that we see the intervals are going to be uh 02 this is one of the intervals right we call it a and then there is 13 okay we call it B and then there is uh 24 let's call it C and then there is 35 actually the input here is like already sorted based on the start value but we never know like if it's not uh told in the problem then we have to consider that this is not sorted so we can you can ask you can always ask if uh the if the intervals like in input intervals are sorted on not if they're sorted what is the criteria of sorting like is it based on the start value or in the end value anyways this was sorted so even if I sort it based on the start value now this is going to look like this okay so 0 2 1 3 2 4 3 5 4 6 okay now uh what we can do is we can actually start from the second one right uh we can start from the second one and this is a very important thing so this is the so the first intuition is like sort it right uh if we sort it uh it's easy to find the overlapping ones and in interval problems we always this is a common Technique we do a lot we do sorting so what we can do is we can start from the second one so after the sorting and then we can check if the starting value of the of this interval okay so let's say uh in okay let's say this is the end so uh to check the overlapping obviously I'm going to check from the second interval right so initially the end is pointing to the end value of the first interval after sorting and then what's what we going are going to check is if this value this one is less than this less than the this end value and if that is the case right because it's already sorted based on the starting value so we start from the second in second one and uh we check so initially we set the end to the end value of the first interval and then we keep on start checking from the second interval to check for the overlaps so if the starting value of the second interval is smaller than the current end value in that case we can say that this one and this one is overlapping right so these two are overlapping obviously you can see here now we have to decide uh which one we want to get rid of because if there are two overlapping intervals uh we have to get rid of one of them now here comes the second intuition so this was our first intuition like how we can uh use it and then second intuition is like once we find uh okay using the first intuition we sort it and it makes easier for us to find the overlapping ones I can just when I'm checking B I can just check against a uh because that's the uh one that it may uh it may work it may uh overlap when I'm checking C I will check against B right because that's the potential one it can overlap when I'm doing uh D I will check in C okay that's that goes there and then we found that A and B are overlapping so we need to get rid of either a or we need to get rid of B so which one we want to get rid of so here comes our intuition here so you can think like you say if I get obviously I want to get rid of the one that ends later why is that because the one that ends later has potentially has more chance to interfere or overlap with other intervals right so say if I uh if I just get rid of this one right if I get rid of this one instead of that because I want to minimize the number of intervals that I want to remove right so even if I uh remove this one there is a chance that because B ends even later so there is a chance that b is going to overlap with other intervals so I want to get rid of the intervals that have uh late end values in that case I am I'm kind of reducing the chance that interval is going to interfere or overlap with other intervals so this is uh obviously it sounds a greedy kind of approach right I am just uh making some assumption that the interval that ends late has more potential to be overlapping with other intervals right so this is a like greedy approach obviously this is a greedy approach and actually it works so what we can do is we can just get rid of B right and now we see that once we get got rid of B what happened is the end actually still is here okay the end is still here now uh let's get rid of say uh now I'm checking C right now C starting point of C we check this again as a current end value so B is gone and what I do is I add one to the result that one is gone now C is not overlapping with this end you see that so it's not overlapping so that means we're fine we don't have to get rid of anything the only thing is we change the end value to this okay because the next interval I'll be checking is interested about this one so I be checking d starting value of D with this and this is overlapping but as we can see the end value sorry uh the last value of D is actually later than the last value of C second value of C so we get rid of D again in a greedy approach so another one and finally we check e against the against this end and these two are not overlapping so we are done okay so that means in total we have to get rid of two one here and one here right so this is the two of the things and let's try this problem on the example one here so the intervals here were one sorry 1 2 three and four so after sorting them let's say since we are sorting them based on the starting value say this one became the first one uh this is a and then one two became the second one we call it B and then 34 became the third one we call it C okay uh sorry I made a mistake here not 34 uh 23 becomes the third one right because we are sorting based on the starting value this is C and 34 becomes d right okay so we said like initially we will start checking the overlaps from the second interval so initially the end is going to be set to the end of value of the first interval and then I'm checking uh if this one is actually less than uh this right so we start from the second interval and we see that the start value of the second interval is less than the current end value that means this is overlapping so we have to get rid of one of them which one we want to get rid of the one that has a bigger end value right so you see this one has the bigger one right so we get rid of this one this time and we set the end value to this right okay next time I check C this one against this start value and value doesn't uh overlap so they're not overlapping okay anyways we removed one here and they're not overlapping so what we can do is we can just uh change the end value to this okay and then um next we check this D interval D with c and they are not overlapping so we don't do anything and that's it so it's one okay so let's try to code this okay so the first thing that we are going to do is check the edge cases and as you see here already it say it is said that uh interval there are at least two intervals but if that wasn't the case I would have done this uh if say intervals equals toal to null or intervals length uh sorry if this was an mt1 if this is zero then I there is no nothing to return uh sorry nothing to remove right so we return zero otherwise what we do is we declare a variable for the result we initialize it with zero this one will count how many intervals we want to remove and then what we do is we do a sort of the intervals right arrays do sort that is the function uh let's stop this okay uh and when you are actually practicing you can just turn this on and off uh turning this on sometimes actually may not be very helpful because you are relying on this to write but when you are actually interviewing you may not have this option so you can turn it on initially learn it and then turn it off okay so what you want to do is I have to uh sort these two-dimensional array right this is two-dimensional array right this is two-dimensional array right this is two dimensional array and I want to sort them based on their start value so we can use this Lambda capability of java okay and okay so the compare between A and B is going to be uh um based on the start values right so a 0 minus b0 that means the uh start values the end values would have been A1 right and we know that uh A and B both of them are like two dimensional so a has two values each interval right each interval is say one of the intervals is one two uh so in that case it's a z is uh one and A1 is uh two okay and similarly say for the second one 2 three right if this is 23 the second one then uh b0 is going to be two and B1 is going to be three okay and so when you are comparing one two against 2 three it's the comparison between a z and b 0 uh so obviously this one will be uh like come before this one because we are uh sorting we have directed the sort okay so uh so we will start comparing from the we have done the Sorting right after the Sorting uh we'll start comparing the overlaps starting from the second interval right so we uh set the initial end to the last value or the closing or the uh like end value of the first interval right so this is interval zero so that is the first interval so let's start comparing the overlaps from the second interval so in I equals to0 sorry one since we want to do it from the second interval and then we keep on going up to the last interval and for each of the intervals we keep on checking if uh if this current interval starting value is less than the current end in that case we can say this is an this is a overlap and if that is an overlap then obviously one of the intervals need to be removed that's why I am doing this result Plus+ so I'm I am doing this result Plus+ so I'm I am doing this result Plus+ so I'm adding one to be removed and then I have to update my end value so the end value is going to be uh the minimum of uh the current end and the end value of this okay so okay I made a mistake here so I have to check the for the overlap I have to check the start value against the current end and the new end is going to be the end of the current interval right with the previous end uh and whichever is minimum because I'll be in the greedy approach I will be removing the one that has the later or bigger end value and then I'm done right okay so that's uh that's what happens if uh the current interval which is I interval uh overlaps with the previous interval if it doesn't overlap even in that case my end value changes right so we from the example here you saw that say when I was comparing between C and B right so I compared between the current end value was this I compared this and I see that there is no overlap so what I have to do is I have to change the end value to the end value of the current interval right okay so that's if I do that in that casee the end is going to be uh the end value of the current interval okay and then I uh return the result okay so this is the minimum number of intervals I need to remove and what is the time complexity of okay so let's run it and you see that yeah so this is accepted now what is the time complexity of these algorithm as you can see uh there if there are like n intervals right the Sorting needs order of n log n right that is in login so this is the time complexity and then we actually read through all the intervals uh and every time we just compare against it's previous interval for the overlap and we just remove it uh we keep it or we remove it right so it's just an order of n aair just iterating through all the sorted intervals and so overall the time complexity is going to be order of in login now space complexity actually we don't didn't use any extra space so we don't have to worry about it okay but U it's the only space that's needed in the Sorting algorithm so you can say that space complexity in the program we didn't do anything but we did a sorting right so space for sorting that is the space complexity and it actually depends on the language because different languages use different sorting techniques some use quick sort some of these other sorts so it's whatever space is needed for sorting okay so that's it thank you very much for watching we'll come back with another problem
|
Non-overlapping Intervals
|
non-overlapping-intervals
|
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104`
| null |
Array,Dynamic Programming,Greedy,Sorting
|
Medium
|
452
|
212 |
That a show more that this dominance in spanish video its support staff available this year 2012 subscribe to dad dictionary channel subscribe videos subscribe to pendoo carefully channel and this sucker eases mother's problem in his pocket and distributed to the awards are given to you and water sports Par 1431 check pradesh word exist in this board and I want to be similar to the award from president to-do list problem video latest to-do list problem video latest to-do list problem video latest them subscribe The Channel subscribe top bottom and tried to avoid you all the subscribe button subscribe to Shruti output list with Force But Not Rise In This Module That Might Be Submitted To Minorities Submitted Sweater Item Distinct Where Couple Of Times Getting It All In One Time And I Want My Submission Was Submitted To Understand Updated On Which Alarms' Judgment Post Which Alarms' Judgment Post Which Alarms' Judgment Post A Nine Setting Message WhatsApp * GUYS IN A Nine Setting Message WhatsApp * GUYS IN A Nine Setting Message WhatsApp * GUYS IN DISTRIBUTED NOIDA SECTOR PLEASE FORWARD THIS IN NOIDA SECTOR 9 IN CASE YOU HAVE PROBLEMS AND DON'T SUPPORT FRIDAY SAVAGE WHATSAPP VIDEO UPDATE SOLDIERS LING DINER DAY LEADERS WATCH THE VIDEO SHOULD BE ABLE TO UNDERSTAND COMPLETE PRODUCTION AND HOW HE IS INSTALLED AND RESEARCH CENTER TEACHER'S UNION K Preferred WhatsApp Video And Come Back To 10 Videos In Case You Don't Want To Suck Solid West Indies Simply Video subscribe and subscribe the Video then subscribe to the Channel thanks for watching this Video Vo Exit To Vo Text Similarly When They Are Trying To AIDS Patient Will Not Be Similarly For Vote In Delhi Assembly On Notice Carefully And Yes Withdraw Class A Pond Destroyed Verdict Class Moisturize With Me To Have Posted To INS Hai Globalization Character See To Connect With Speech Notes Of Chapter Note Directly Notes Are Connected To The North AND NOT RELATED TO ANY 1969 SUBSCRIBE TO WORLD CHANNEL'S NOTE AND DECIDED TO 2006 ELASTIC NOW PERSON THAT HE ME BENGALURU REGIONS WHERE YOU YES IT'S SORRY NOTES FOR THIS IS NOT 100 TONS MORE GORGEOUS AND IDLI SANDWICHES FROM MANDSAUR Subscribe subscribe to subscribe and subscirbe ki idol police notes sutopo says pe active guidance and support and porse page will have adverse effect on ok so one should have destroyed secretary notification best of luck that if independent right away due to water into history can't simply attractive Watering Interview Correct Surya Considered Quiet Forces Hai Ka Hal Check Weather Exhibition Mode Value Ko Ling To Root Hanging Carefully Infrastructure Vighn Not Bay Daru 10 w10 Not Vidron In subscribe The Video then subscribe to the Page if you liked that team subah point to point collect liberty subah trying to find it did nothing laptop over bhi font ko one ko vikaas will win the infantry question because of this he calls for a good cause for udaipur like happening again sudhir vacancy nikala hai at 181 School Time Is In The Morning Winner Of His Followers Who Selected For Telling Early In The Morning Officer A Reduced In Soil From This Is A Proof 182 Call This Channel Check In This Add In This Visit Set Respect To Solve Visit Distic Connect With R E Did Not Even With the bottom subscribe to the channel that we are trying to titan next character Seervi Video then subscribe to the snake button to front neck later shifted from fear factor from oppression and share and subscribe our channel Forget 111 Button Hum Court Ki Vaikuntha Ko subscribe Video then subscribe to the Video then subscribe to subscribe this Video Please subscribe and subscribe the Channel subscribe I am on your show Hair Falling Into His First Administered Best Result Special New Play List Ek Ansh Rajdhani Dress Mail Message To * Size Ek Ansh Rajdhani Dress Mail Message To * Size Ek Ansh Rajdhani Dress Mail Message To * Size That Distant Dream subscirbe Giving That This Will Be Board Dot Loop Subscribe Like and Subscribe To The Words Will Simply Try Not To Insult Vote For Be Id Wood Point 10 Board Dot Loop Plus Points 100 Length Plus Appointed Loot Lo A Tribe Dot Air 6 Came In Mode Off J - K Egg This Is Not Equal To Null Came In Mode Off J - K Egg This Is Not Equal To Null Came In Mode Off J - K Egg This Is Not Equal To Null Absolutely Midriff Is Know What Is Subscribe Must Subscribe To The Channel Like And That Trident Root Ek Ansh Dual SIM leader is the return gift of members' heart members' heart members' heart that board rate dandruff hi friends must have MB last will have destroyed with such labs in this is lead 1004 is gir daily wealth who doesn't length and 1000 length and visit of this is proven and Web Content Not Here Come To This Board Of - Hey Basis Channel Dangal Family Come To This Board Of - Hey Basis Channel Dangal Family Come To This Board Of - Hey Basis Channel Dangal Family Letter On 200 Remind Earrings Rich With This Condition Was Doing Chatting For 11 Years So Basic Subscribe And This Note Checking With Current Month Not Connected Subscribe And Hai So Next World War E Urge For Stool Makhli Current Note S2 President Rule Next Month Will Not Be Sequence To Not Be Aware Of Real Life Enjoy Aay J - Check The Con Is Not Real Life Enjoy Aay J - Check The Con Is Not Real Life Enjoy Aay J - Check The Con Is Not Be The World Is Not Equal To 99 Acid That Not Word And Where To Say Not world record breaking on Thursday subscribe definitely subscribe my channel also see a hello hi gel - 1the left a plus one hello hi gel - 1the left a plus one hello hi gel - 1the left a plus one flashlight on more fuel appointed nodal officer is here who if straight line disco dance 56001 instead of junction and not accepted soul is Subscribe for Deducted from this video thank you
|
Word Search II
|
word-search-ii
|
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique.
|
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
|
Array,String,Backtracking,Trie,Matrix
|
Hard
|
79,1022,1433
|
290 |
foreign only one time right make sure we will divide like that only next we have next what we have pattern two right we have pattern two and in the pattern two what we have to do pattern is given a b a okay we have given pattern A B A let's understand a b a but it is given dog catfish right dog catfish it will divide from here but you will see that we can get dog we cannot we can get cat sorry we can get cat here right but we cannot get yeah dog right we cannot get so how we have to implement here right we should always focus on both uh after that dividing both string this one and this one okay that's why it is not giving true I think you have understood the question let's understand the next example right so next example also given AAA right and this is coming different right and that's why it's not matching right so pattern can be different as you can see he will divide means it should be same but it is not same this is same but this is same and but this part right it is cat dog right so pattern is not matching right pattern is given all the same but here dog is there here cat is there so it is not matching here cat is there here dog is there right that's why it is not matching it should be dog or cat right so this type of examples we have all three types right thing right this was our pattern right a b right this was our pattern I can say this pattern right and another was what our string correct and the string was what we had dog cat dog and that time we are returning what output wise true correct because when I divide this here after a b this is here right so it is exactly this one reverse of the first part so first part is docket the other part is cat dog and that's why it was returning true right but when we will do little changes right what was our changes was dog cat catfish right this one and that time what happened we have to return false right we have to return false so these two combinations we have to check so it fell for what right if we pass right what happened a b a and we all have dog right let's see another example we have uh let me copy this one yeah now we have pattern a b a right and dog here also we can make a dog cat is also dog right so s have dog so what we should expect to return true or false right true or false it should expected it will return true but expected is what expected is false I will repeat if pattern we have A B A if we'll divide here it is just a positive the half part right it will divide it up from here similarly s have the pattern after dividing it is just opposite cat dog docket cat dog that is right according to the pattern now we have p a b a or S Dog catfish right dock at catfish and that is false right because here come fish it should be cat dog right but now if we talk about the pattern in this pattern right we have S is dog so we will get what it will return true but our expectors is but our expectation is what it should return false right so as a fix for this is to have two maps right so one for mapping characters towards and other for mapping words to characters right so what we have to do fix for this is to have two maps right two Hazmat at least we should have one for mapping character two words and other for mapping words to character right first we will check what it will check character characters to make towards and other will check words to character correct so while the scanning each character would pair these two thing if the character is not in the character right and other if the character is in the character toward I'll repeat there is two thing right while scanning each character word repair either it will be in the character right either it will not so if the character is not in the character to word mapping you additionally check whether that word is also in the word to character mapping if that word is already in the word to the character mapping then you can return false immediately since it has been mapped with some other character before correct or else we will update both mapping or if the character s is in the character to the word mapping you just need to check whether the current map what matches the word with the current maps in the character 2 words mapping if not you can return false immediately right so let's understand here in the course section you will understand very well right don't worry for understanding I am here okay so what we can do we will start from here we will make has map right as map I like this right will Mac have has map and another is what we'll take character correct okay I think yeah character and then we will take string will compile again don't worry so we will take it will store the map build store character and another string and that we will say that I was talking we'll take map care and this will be new has map this will be our new hash map right this will be our new hatchback okay not I think like this one we have to do yeah this thing happened right next what we can do we will copy this one I will try to implement this one only okay now we have to reverse first it will come string and then it will come character and this name is what we can do map what it we have taken character string and string character mapping right this is be given character string is given map of character right and map of word this one okay so two things we have implemented now what we you have to say we have to split the string so a string is given what this string s is given right so we can write s dot split a start split based on what based on double quote space based on the space we have to split this string and what it will return string of characters correct string of what's you can say so what I'll do I'll say array of words and that will store here correct now we have to check if you can say base case what's Dot sorry words Dot length if words dot length not equal to python Dot length if this is not equal to this right what we will get it will return false correct we can say that if word length is not equal to pattern length right then what we will do we will say it return false now we have to do we have to move to all the words right or array of the words okay so I'll take int I equal to zero and then I'll take I should be less than words dot length and I plus right we will move to whole array whole words of array then I'll take a character C equal to pattern we have given and Care at will use at I so 1 by 1 character care we will get and one by one we will get how will get what we will get from words at I so this is array for all the index we will get and from the there we will get character now what we should do we should check if uh map care map underscore cat right this is the thing we have taken as map.cat map.cat map.cat dot contents Dot contents key correct which key that we have C character if that we have that we if don't have right if don't have if key is not here a character is not on the map then what we will do map underscore word and then we will take what contains key will check w if that is not on the if map character doesn't contain the character then we will check map what contains key or value or not if that contains what we will tell return false right remember next means we are not matching word and map both map character and word character not matching and that's why we are returning false right so we are here right so otherwise what we can do we'll make a else condition here and will if that is not matching if that contains right that then we will return false if not contains then we will sorry if both node contains right it doesn't it means like that only right then what we will do we will put on first on the character C comma what like this and similarly we'll do what Dot put and will pass W comma C so both mapping we will do if this case will continue right we have completed this one after this if condition right what we will do we will check else condition here if map dot cat mapcare contains the character then what we will do we will take a string map underscore what means it already mapped right how we'll get it we'll get from this scatter we are putting here right if this is Con if it contains right the this is the if right if it is not contained then we will do these things if it contain then we will get from the map right how we'll get that this get function right get of C will get and then we will get the string and if and then we will do if this map mapped word this mapped word doesn't contain equal to equals the w we have right then what we will do we will just return false got it and this one is done this if an else currency is done after that we will complete this for Loop right then we will be here after that we will complete our methods before that what we have to do we have to return true if that is the case if everything working fine then we will return true correct so what I've did here let me explain again first what we will do we will take to map character of character n string mapping your characteristic and another is string character right we will split that string and we will put into the words we'll check both length pattern and words length is same then we will continue otherwise we will return false right then we will make the loop of all the words right and what we will check first if the map character contains the character then we will continue this one if contents then we will get the character right and we'll check on to the word if that is not mapping then we will return false right if that is not present then we will do what we'll check on the map dot contents Word right if word is there right means because character is not there but what is there then we will return false if both are not there right then we have to put correct and finally we will return false as true right and in this way let's uh compile this one compile is working fine let me submit this one us yeah it's working fine for me so thank you so much guys and if you'll talk about this uh complexity right so as you can see what we have taken we are moving to o of end time right because n depends in the number of words and that's why we are going to this for Loop right so it will take time complexity we'll talk about let me write here if we'll talk about time complexity it is nothing but o of n sorry o of n right because and represent represents number of words in s or number of characters in the pattern okay and similarly space complexity is what o of M o f we can say m where M represents the number of unique words right uh even though we have two Haze Maps right the characters to word hazmap has a space complexity of one correct and since there can be at most 26 keys right as you know so let me know if you understand the pattern or your sorry complexity and complexity due to the pattern and if any issue we have picked please let me know so in the other part of this video we will see single index has map so please continue the other part of this video also thank you so much
|
Word Pattern
|
word-pattern
|
Given a `pattern` and a string `s`, find if `s` follows the same pattern.
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
**Example 1:**
**Input:** pattern = "abba ", s = "dog cat cat dog "
**Output:** true
**Example 2:**
**Input:** pattern = "abba ", s = "dog cat cat fish "
**Output:** false
**Example 3:**
**Input:** pattern = "aaaa ", s = "dog cat cat dog "
**Output:** false
**Constraints:**
* `1 <= pattern.length <= 300`
* `pattern` contains only lower-case English letters.
* `1 <= s.length <= 3000`
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in `s` are separated by a **single space**.
| null |
Hash Table,String
|
Easy
|
205,291
|
1,305 |
hello so today we are doing the contest weekly contest 169 and the second problem which is all elements into binary search in to binary search trees basically its problem 1305 and the problem says given to binary search trees root 1 and root 2 when I return unless containing all the integers from both trees sorted in ascending order so basically if we have two trees like these ones we want to return like a merger of the numbers in get to that is sorted and so for example here we have this tree and this one this tree gives us is 2 1 4 this one is 1 0 3 merging them in a sorted order would be 0 1 and then 2 3 4 which is what we get here and so you get the idea so this is the problem if you look at the constraint here we can see that the trees are not very big each tree has at most 5 thousand nodes and the node values are in this range here so even this 2 trees can be at most ten thousand nodes right and so from this we can deduce that ok it's the trees the number of nodes is not very big so we can just do inorder traversal you can look letter but in order traversal follow a binary search tree gives us a sorted array essentially and so if we do inorder traversal for both trees we will get a sorted array representing the first tree and the an assorted area presented the second tree and after that we can either merge the two like using a normal like us the mursaat for example has the second step that does the merging of two sorted arrays right it has a method that does that so we can do that the other option is we can just get them with any traversal it can be in order it can be post or die matter and then we can just merge that add the two together the two lists and then sold them at the end we don't need to worry about the time complex like if it's that will get a time limited exceeded exception there because the number of nodes is not very big and so that's what I'll do not now I'll do it traversal for both and then just add the two of us together and sort them so let's do that so to do that you know the traversal yeah we can just have Traverse or four node right so just helper function here and then so if the node is empty so don't have anything anymore routine just return an empty list otherwise we can just so it's just normal inorder traversal here so traverse the nodes are left so that we can get the left portion first and then get the node devout and then get the traverse for the right side of the tree so here I did an inorder traversal meaning that each tree that I call in this Traverse method I will get a sorted all right I don't have to I could do like a pre-order traversal so as added like a pre-order traversal so as added like a pre-order traversal so as added here because I'll be sourcing at the end anyway but yeah I we can't just do it this way it does not really matter and so once I have that helper function I can just get the array for the first tree and get a for the second tree at the two together that told us together and then softer right and just return that pretty much on this so it looks good submit okay so that passes yeah so very straightforward solution and in terms of time complexity you traverse the tree once so it's like if n is the number of nodes it will be or it will be of lye again twice but then we have the sourcing that takes often like and so it's over like in time complexity in terms of space we are just using the stack here for the recursion that will take off like in and yeah so that's pretty much it okay so another way we can solve this is using the word I mentioned earlier the merger step of the merge function of merge sort right so using this function here since we are doing inorder traversal we get the left node which is the smaller node first and then the root which is just the value next to it and the right side which is which are the bigger values so what we get is sorted always because we are doing inorder traversal for a binary search tree and by definition that give us a sorted array and so instead of sorting again we know we have we will have this way here we will have two arrays that are sorted right so instead we could just merge them such that to keep the salt in order right so we could do that would basically get it down from all the login' to event right so we all the login' to event right so we all the login' to event right so we could merge them the two sorted arrays instead and returned that and so now we need to define the merge function when we have two arrays right and so the way we can do this is so I'm just going to define two things are the lengths of both arrays and we need two pointers so merging basically means we will keep traversing both arrays at the same time and while traversing whoa look is it the value at in the first array is smaller than the value in the other array whichever one is smaller we added to the result until either we and until either we are done with both arrays or one array is done and the other one has told some values left so we add those or the same the reverse thing like the other array is done in the other one still has follows and so we add those so essentially just the merger step of merge sort and so we do a result here and we'd have so these are just the pointers to the values in the first array in the second array and then we have a final result like this and so now we will say okay while we still have some elements in both arrays that we haven't added to the result yet we will continue and then we return result here and so what we'll do here we'll check so either the first array the second array is done so we done traversing a secretary in that case we'll just add whatever is left in the first array and so to check if the second array is done we'll check that the it's equal to the length of the it's equal to its length which means it's done or it's not done but there are still elements left in this one and the value in the this first array is smaller or equal to the values in the second array which here means that this value here in the first array is smaller and so we can just add it right and so we add to the result she's a parent right now otherwise that means either we are here and the this value here is smaller or so basically if this is not true or this is either both are not true right so both are not true which means this value here is smaller and it means that this value here sorry the second array is not done yet we are not done traversing it yet and them is also that the first array the second array value is smaller because this is not true and so that means we can add the value of the secondary right and so we will add that here and that's pretty much it so when this is no longer true which means the array one is done then we'll just go to the else and we'll find that this one is not done yet and we'll keep adding its elements right and that's pretty much we just need to increase the pointers now so that we can go to the next step in the array and we need to do that here that's pretty much it okay so that looks good I'll submit okay so that passes so one thing you hear in terms of time complexity is that this one is just a one plus and two the length of the two array right because that's what I was just doing one loop that goes on and so we Traverse in both arrays and that's just the length of each the number of nodes of each street right and so it's a lot better than the over wagon that we had before and this one still has the same time complexity that we mentioned and in space complexity that we mentioned earlier this merge step here adds an oven space complexity to return the result which we had also earlier yeah so that's pretty much it for this problem yeah thanks for watching and see you next time
|
All Elements in Two Binary Search Trees
|
number-of-visible-people-in-a-queue
|
Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8,8\]
**Constraints:**
* The number of nodes in each tree is in the range `[0, 5000]`.
* `-105 <= Node.val <= 105`
|
How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start. Keep popping from the stack the elements in sorted order until a value larger than arr[i] is found, these are the ones that person i can see.
|
Array,Stack,Monotonic Stack
|
Hard
|
1909,2227
|
54 |
hey everyone welcome back to the channel I hope you guys are doing extremely well so this is another lecture from this right verse A2 said DSA course just in case for the first time out this is world's most in-depth course when you world's most in-depth course when you world's most in-depth course when you talk about bs elbow why do I say that because this course has four 55 modules by the end of the post you'll start more than 400 plus problems you can go over the entire internet you can buy any of the paid courses in the market none of them will be teaching you Dia Salvo in such step something that I can give you as Assurance is if you complete this entire post you can create any of the DSL products in any of the companies in any part of the world so till now we have covered till this particular problem now in this video I'll be covering this problem which is the spiral Matrix now what does the problem state it states that you'll be given an N cross M Matrix and you have to print it in a spiral form what does it mean you start from one you go like this and in this order this is what you have to print yes in a spiral order is what you have to print so I go across print day it will start like this is go like this 26 and then ends up at 36 so this is what you have to do and I've written the integers in such way that you can actually track them in a spiral format so how do you do this so remember one thing this particular problem doesn't have multiple Solutions it just has one solution and that one solution is the optimal solution then why is the interview even asking this particular question so there are two reasons one is to test your implementation skills and the second one is how clean can you write the code so our Focus will be to find the easiest implementation so how do we implement this particular problem because it is an implementation based question so let's observe first we're going like this then like this so can I say it's a pattern first we are moving right then bottom then left and then top so that is this is the outer square or rectangle can I say this so can I say the first will be right then bottom then left and then Pop I can and this will make sure it prints the outer covering it does can I say the second covering is also in a similar fashion that is right bottom left top right so the second layering is also printed the third layering is right bottom left doesn't have a top but it is printed so is the observation something like this first second third fourth fifth so spirals all over till the center I can so this is what I have to implement so how can I implement this let's observe something so if I write down the row numbers it is 0 1 2 3 4 5 if I write down the column numbers 0 1 2 3 4 5 can I say the topmost row is zero can I see the bottom most row is as of now n minus 1 which is 5 and can I say the leftmost point is zero and the right most point is five so what are we doing at first we are printing this one then we are printing this one and then we are printing this one agreed so if I have to print this portion and as of now if I have to write top is here bottom is here left is here and right is here can I see the first printing will be left to right which will make sure this prints so the first printing will be for Loop of left to write and it will be like array of rho will be top and if I am running a loop I equal to left to right it'll be I so can I say this will make sure the right is printed yes it will what about the bottom can I say the bottom will be starting from here not six do not take six it will be repetition it'll be starting from seven so the top has to go one down so can I say top will go one down it will so maybe after this for Loop is complete we can do a top plus this will make sure the right is performed if there was a right okay what will be the next top has gone though what do we need to print from here to here what is constant the right is constant and you go from top to bottom so please go ahead and do it so we go from kind of top to bottom and right is constant remember this and can I say I will print a of I and write as constant perfect so this will make sure the bottom is also printed so the bottom is also printed perfect next you have to print this direction again do not print 11. so can I say the right will move one back it will and now the right stands over here and I need to start from here till here so it goes from right to left and the bottom is constant so what you'll do is you'll say okay listen for I will go from this portion to this portion which is right to left so let's go from right to left and what will you say print array of yes the bottom stays constant and you just take this one so this will make sure the left is also printed what about the remaining portion remember it starts from 17 so make sure the bottom goes up okay and what is the next that you'll do if you've taken the bottom up that's bottom minus perfect amazing was the next job that you'll do you'll have to print from here till here what is constant left from bottom to top you have to run and loop so you run a loop from bottom to top perfect and is a print of a of what is constant left so keep the left as constant and this will print it once you have printed this the top is standing here the bottom is standing here the left is standing here the right is standing here so this will make sure the top is printed so can I say the first layering is printed so let's mark the first layering is print where will the next layering start from Yes it starts from here it starts from 21 so after this print the left has to move ahead please make sure the left moves ahead so after this the left is standing here then left is standing here the top is standing here bottom is here right is here so again the new Matrix looks something like this so I hope you are understanding the pattern that I'm trying to form I'm first trying to print the right then the bottom then the left then the top that is why I'm using four different iteration of the loops so once spiral is printed next I will print the next I'll print the next and you might ask what story before this there is no top how will you manage this I'll show you that in the code editor it's time to code it up covering all the edge cases just in case you want to put it up the problem like will be in the description make sure you try out from the problem Link in the description so at first you figure out the number of rows and then the number of columns in case you are thinking why is it like this so usually you're given a list of list so basically what like the input is basically always like this they will give you something a container and this will be a list this will be in this will be a list all the rows are the list and they put inside this particular container so if you figure out the size of this particular container that will be the number of rows and if you take the first and you say that is at geothermic the first and you see dot says this will give you the number of columns that is why we usually write n and M like this okay now what is the first thing we do we need a left which is at zero we know the right will be at M minus 1. we know we need our top row which will be at 0 and the bottom row will always be at the last that's it and we have to return this particular answer in a vector so let's take a list okay done what are the directions right bottom left and top so let's perform all the directions sat first the right is performed so let's perform the right so it is like I go from left I go still right and I plus and it says answer dot pushback of Matrix of what is constant the left and I perfect top and I done once you've done everything once you pushed it entirely the next starts from seven so the top goes ahead so top will go ahead what is the next thing you have to go ahead and do the bottom part so it's from top to bottom so let's quickly I trade from top to bottom that's from Top till bottom I plus and you will again probably take this line the same line answer Dot pushback but this time this will be I and the constant is the column because we are going Bottom perfect done once you've done this so this is printed now you start from here so the right goes over here yes so the right goes over here so after this there will be a write minus as well so make sure the Right Moves one backward so right minus once you've done the right minus what are the next you definitely start from the right and you go on to the left please go ahead and do this and what do you say answer dot push back you are having the bottom row as constant so have the bottom row as constant and you will have the column as moving okay so once you have put everything on this one then you start from here so the bottom moves are so you do a bottom minus perfect so once you have done this what's the next that you do you go ahead and print from bottom to top so please go ahead and print from bottom to top so it's like in d i equal to bottom minus and you again write answer dot push back Matrix of I what's T is function left once you have printed everything the left will move here because this is the new Matrix that you have to print so the left tip so what you do is once you've printed everything the lift moves one step ahead so can I say this will make sure that this is printed the next step starts from here again right again bottom again left again top so again the same forward Loop so we'll run so can I say if this left is smaller than this right that means there are columns that has to be traversed or spiraled and similarly can I say the top is lesser than the bottom there are still elements that has to be spiraled thereby what I will say is Hey listen while the top if I still have any rules and if I still have one column even one column then I need to do this right left think I need to do it there is no other way so I'll go ahead and do it but will it work we need to think will it work at the end we can definitely return the answer but we need to still cover the edge cases this is fine this is going to go ahead and do it let's come back to the code so what if we have a single lay just a single leg then it is just perform right it is just performing which is the first case it will perform because the top was less than equal to bottom and the left was less than equal to right so the first right case will be performed does it have anything to perform on the bottom on the left on the top no because it is just one row so we're done we have done a top plus so what would have happened was top would have been here bottom would have been here so on doing top plus top moves beneath bottom so basically this condition will make sure it checks it and it will never print anything on the bottom it will never print anything on the water so we don't need to put any extra checks so the bottom will not be printed because the for Loop checks so over here there was top and the bot the bottom was also there after the movement the prop moves beneath bottom so the phone Loop checks in it doesn't prints and the right decreases itself perfect initially the leftovers here and now the right will decrease and come over here what is the next it is saying right to left please move but are we checking because we are sure the top is exceeded so please make sure you check if the top is still underwater move we still have a rule otherwise wherever you print what will you print if it doesn't have anything so just make sure you do this perfect none so this is done so this condition makes sure that if there was one row yes if there was one row the left will not be printed but the top will still be printed so the bottom is checked and it will not print it but if you remember in our case we had something like this in which there was no top how do you make Shoppers works out so the bottom is chunked what is not checked let's write it for that now whatever is not checked go ahead and write for that now if the left we still have elements it's fine to print it but if we do not have why will you print it so please check for left and right because the bottom and Chip prop has been checked over here similarly the right and left have been checked so you don't do it so over here the top and bottom May chat and the Left Right Where I checked here and after that the left right never got increased so that's why you did not write an offense over here where they are required because top changes the right changes once you've done this you can go ahead and ready to run it hopefully it will run at one view it does let's quickly submit it off so what will be the time complexity can I say whatever you're doing doesn't matter you are and ending up iterating for every element once so the time complexity is nothing but be good of n cross n because the loops are written with all the conditional cases so it will make sure every element is like this line will only be executed for every element once so the time complexity will be B go of n cross M and you're storing the answer so that's another Big O of n cross M so going back to the sheet I can mark this as done and if you have understood everything please give that Knight because it won't cost you anything but it will highly motivate me to make these kind of content if you're new to our Channel what are you waiting for hit that subscribe button and to continue our tradition please do comment understood so that I get to know that you understanding everything and if you haven't followed me on LinkedIn Instagram and Twitter all the profile links will be in the description with this I'll be wrapping up this video let's read in some of the videos and provide take care I finally
|
Spiral Matrix
|
spiral-matrix
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100`
|
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
|
Array,Matrix,Simulation
|
Medium
|
59,921
|
1,637 |
hey guys welcome back to my channel and in today's video we are going to solve one more lead qu question that is widest vertical area between two points containing no points so in this question we are given n points on a 2d plane where points I that is an array represents x and y coordinate of a particular point and we have to return the widest vertical area between two points such that no point are inside that area I am stressing this widest vertical area term again and again because there is a difference between vertical area and widest vertical area which is given in this line that is the vertical area is an area of fixed width extending infinitely along y AIS but when we are talking about widest vertical area it is the one with the maximum width so we only have to concentrate on maximum width part not the one which includes this infinitely long y AIS area right and there is a note which says that points on the edge of a vertical area are not considered included in that area so this means that in this diagram you can see these points which are coming on these edges are not considered inside the area so they are not a restriction so what we have to do is we have to check and we have to calculate the maximum width or widest vertical area so how we can do that so first thing is very clear to us that so we don't have to focus on the vertical area which is been located along the Y AIS but we have to focus on the widest vertical area which focuses on the maximum width and if we are talking about 2D graphs or 2D planes then what is the width part width is something that we calculate from x-axis right so that we calculate from x-axis right so that we calculate from x-axis right so the one hint that we are getting from the question statement itself is that we have to focus on the x-axis not on the Y have to focus on the x-axis not on the Y have to focus on the x-axis not on the Y AIS right because if we were told to about calculate the vertical area then we were considering the whole x-axis and we were considering the whole x-axis and we were considering the whole x-axis and Y AIS and then we were also considering the height but in this question we don't have to focus on the height part or the vertical area we have to focus on the Wiest vertical area which is talking about the maximum width or the width part which comes from xais so this is something we are very clear from the statement itself so now let's try to understand even better this question so that we can come up with an optimized solution so here is the example so let's try to understand this thing even better with the diagram so suppose this is a graph and we are saying there are these points right just assume that these are the points which are given in this array random points and these are representing y and x coordinates right in this way so if we are asked to return the maximum width right I'm using this term only because I think still the widest vertical area is a bit tricky term to understand this thing but if we are going to just use maximum WID term then it is very clear to us that what we have to focus on right so let's try to understand if we have to calculate maximum width with this graph then what I will be focusing on is the xais points so if I'm saying I need to calculate the maximum width between two points then I can say this is the width and if I'm going to draw it down then this will be another width and what I'm seeing suppose this is of difference one and this is of difference 2 then I know that this is greater than 1 so in this scenario this will be the value that I will be returning right this is something I'm randomly drawing this diagram I will be drawing it again for the given data but this one is quite random so if I have to understand from this diagram I know that I have to focus on xais and the points which are present on this axis and I simply have to check the difference but what I can't do is in this scenario that I can't take this hole as one distance or one width why because this width is consisting of this point which is coming in between it is not coming on edge so I can't consider this whole width as one I have to break it down and I only have to take the width from one point to another and I have to consider that width as valid only if there is no point in between or if there is a point then it is present on an edge but if the point is not present on an edge and it is present in between then I can't consider this whole area as vertical area or the widest area Okay so this is these are few things that we need to keep in mind so now two things are clear to us that what we can consider as a width and what we can't consider as a width right so now let's plot these points which are in this example and then we will see with which approach we can solve this question so if I'm saying this is my graph and I am going to plot this whole point array on this graph then before plotting this array on this graph one thing that I can quickly figure out from the previous discussion is that if I have to calculate a difference and if I'm considering that I don't want to include any in between points then in that scenario what will be the best approach to proceed with this to process this whole array the best approach will be firstly sorting this whole array and then working with it then only we'll be able to get the adequate results easily right that will be the optimal approach because if we are going to randomly work with this whole array then it would be difficult for us to figure out the difference and then checking is there any point in between these two plotted points then again after checking that we will check that the difference is the maximum difference or not then it's a lot of work to cut off this work what we can do is we can simply sort this whole array and after that we can plot this and we can work with the x-axis points like can work with the x-axis points like can work with the x-axis points like plotting is something is for understanding we are not going to do it in the programming part obviously but the first step that is sorting which is important not only to understand the question but also we'll be doing in the programming part so let me just sort this whole array so just to save our time I have sorted this array as well as I have plotted this array on this graph so now we can see that after sorting this array will look something like this and the graph of this whole array will be like this so we can see that these are the values on X xes that we have to focus on 7 8 and 9 so if I'm checking the difference between seven and 8 these are the two points right seven is one point and second point is eight so the difference is 8 - 7 will be 1 so this is difference is 8 - 7 will be 1 so this is difference is 8 - 7 will be 1 so this is one of the resultant for now I can consider that this is the resultant value now what I will be doing I will be checking the next difference that is 8 to 9 so 9 - 8 will be also equivalent to 9 so 9 - 8 will be also equivalent to 9 so 9 - 8 will be also equivalent to 1 so which value is greater is this value is greater or this one both are same right so what I will be returning one as an answer so if there will be some other difference like 9 and seven or 9 or six in that case I know that this value will be greater than this value previous value so it would be somewhat like three or four or two whatever so I will be returning the maximum of it so for this example we know that the answer is going to be one so this is how we are going to solve this question firstly we will be sorting this whole array and after that we will be working with only the X data x-axis data because we don't have to x-axis data because we don't have to x-axis data because we don't have to worry about y AIS or vertical area we have to work on widest vertical area which is talking about the maximum width and when it's about width we know that it's about x-axis so we only have it's about x-axis so we only have it's about x-axis so we only have to focus on this part now what will be the time complexity of this whole approach so time complexity is going to be n log n for sorting and then again weo of n for traversing this whole array and working with xais data in order to calculate the maximum width so what will be the overall time complexity it will be bigo of n log n right and then what will be the space complexity will be log n or n why I'm saying log n or n because in Java and C++ the input the inbuilt sort function C++ the input the inbuilt sort function C++ the input the inbuilt sort function is of log n space complexity in its worst case scenario and in Python it is about big of n invers case scenario so if we are considering that then for uh if you're solving this question in Java and C++ in that case it will be login and C++ in that case it will be login and C++ in that case it will be login for worst case scenario and if you are working with python then it will be around big of n space complexity in worst case scenario because python uses dim sort for the inbuild Sorting Al inbuild sorting function so this was the space and time complexity of this approach and now let's jump to the coding part and we will again be coding this solution in two languages that is Python and Ruby so let's quickly code this whole solution so firstly let's solve this array after this Define our result variable and then what I'm saying for I in range one to length of points in inside this what I'm saying just update our result with Max of result and points i0 because we are working with only xaxis data and point uh this is not comma this is minus points i - 1 0 because we started from 1 points i - 1 0 because we started from 1 points i - 1 0 because we started from 1 right so we have to do i - 1 to access right so we have to do i - 1 to access right so we have to do i - 1 to access the previous value and then after stepping out this loop I will be returning the result and if I hadn't made any typo then we can run and check okay let's submit it so this is accepted if you can see it on the left side so now let's quickly code the Ruby solution as well which is going to be similar to this one so in Ruby as well we will firstly do sorting part that is python points. sort after this we will again Define the variable and after this we will be running a loop in which what we are seeing from one to points do length the syntax is slightly different dot each we are saying do I and the this is how we are going to access the values now inside this what we were doing is we are saying result will be result so result comma what we were taking points i 0 minus points i - 1 0 and what we have to minus points i - 1 0 and what we have to minus points i - 1 0 and what we have to do we have to take the max of it right and after stepping out of this Loop I'm saying just return the result uh what I have done is okay this is not this bracket actually we do it with square brackets actually in Ruby so now let's submit this okay so this is all accepted and this was the whole explanation and I hope that this video was helpful for you all and if you really find this video helpful then don't forget to like share and subscribe my channel I know that this video was not exactly the medium level questions but sometimes in lead code I have observed that the difficulty tag has nothing to do with the difficulty level of the question so this was one of those question questions but uh yes we don't have to get bothered with the difficulty tag because our focus is on practicing and becoming as better as we can so I hope this whole explanation was helpful for you all and if you really find it helpful then you can like this video subscribe my channel and I will soon come up with more such questions till then take care and thanks for watching
|
Widest Vertical Area Between Two Points Containing No Points
|
string-compression-ii
|
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.
Note that points **on the edge** of a vertical area **are not** considered included in the area.
**Example 1:**
**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.
**Example 2:**
**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3
**Constraints:**
* `n == points.length`
* `2 <= n <= 105`
* `points[i].length == 2`
* `0 <= xi, yi <= 109`
|
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
|
String,Dynamic Programming
|
Hard
| null |
899 |
today that's so orderly cute we are given string s and the integer K we can choose one of the first K letters of s and append it at the end of the string we need to return the legs called graphically smallest string we can get so no matter how many number of moves we can Act so in this case let's see these two examples in the first example we can only append the first character to the string so firstly we move the first character C to the end then we get BAC after that we move the first character B to the end of the string uh note we should change this string so we get the ACP we can keep doing these steps but we will know ACB is a lexical graphically smallest one so we just return that one so it means at the beginning we have this string and in the first three characters we can choose one character and append it to the end then we choose B Because B is the largest among these three characters and then we get aacap afterwards we can do the same thing um now in the first three characters we choose C and then we append it to the end then we get a aapc so how to solve this question well this is a trick question um why because uh there's not much algorithm you can think of but you can observe the there is some pattern for example when you look at this example you will think like if okay great or equal than two we can always choose a larger character and appendix to a string so in that case the final result would be the overall smallest lexical graphical graphically small stream so give any struggle just to return all the characters sorted the smallest one so that's when K greater will give N2 because we can always choose the larger one so when k equal to one what can we do we need to uh like append the first character's end for every um for every possibility because for example if we have some string then it would like look like this um so what's the smallest one would it be a uh I mean you need a append all of these things to the end right so only if we try every possibilities we will know what is the smallest string so when k equal to one we just try to append the first character to the end so that's the true cases so now we know how to solve this question so get the lens and then we have two cases two scenarios when k equals two one we should do something and when K great or equals and two we can just return the overall let's go graphically smallest one so we can just get the chart which is S2 char all right and then we just sort it salt charts and then we return um now we should convert it to string so it is a charts but when k equals q1 as Dimension we need to try to uh securate this whole process so we since we need to delete the chart and also append the chart so we need the stream Builder so it would be new screen Builder that would be of s and also um we need the overall smallest result at the beginning equal to S as well and then at most we need to conduct the delete and append the end times right so an icon oh sorry zero I listen and I increment by one uh the chart we want to delete is the first chart equal to this chart uh well it should be Curt chart at zero and then we delete it so curve delete chart at zero and then curve Panda this chart right so append the first chart and then we just compare two string compared to if it's uh it is lexical graphically smaller than result then we should update Without You occur to string easier just a return result okay I think there will be all the code uh oh sorry compared to less than zero because you need to compare with zero even less than Curry two strings less than result is equal to zero which means these two strings are the same and then if it's greater than zero which means this curves during the larger exam result okay thank you for watching see you next time happy New Year
|
Orderly Queue
|
binary-gap
|
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters.
| null |
Math,Bit Manipulation
|
Easy
| null |
833 |
hey everyone welcome to my channel so in this video i'm going to try to solve this problem at the same time i'm going to follow the general interview steps while trying to solve this problem so let's read through this question you're given a 0 indexed string s you must perform k replacement operations on so the replacement operations are given as three zero indexed parallel arrays and this is sources and targets all of the lens k so to complete the ice replacement we need to check if the substrate source i occurs at index in this eye in the original string s if it doesn't occur do nothing otherwise it will replace the substring with target time for example if we have abcd we have the index i at zero source as a b and targets as triple e because a b matches the source then we are going to do the replacement okay so all the replacement operations must occur simultaneously meaning the replacement operation should not affect the indexing of each other so the task case will not generated will not be generated such that the replacement will not overlap so let's say if you have abc if it's index 0 1 then we have sources a b and b c actually it's very confusing we don't know whether we should replace a b or we should replace bc with something indicated by the targets so we don't need to worry about this kind of task is because it's totally illegal and also since it says all the operations should occur simultaneously we sh we shouldn't actually make replacement affect other replacements okay so return the resulting string after performing all of the operations let's see the example to have a better understanding so we have the input string as abcd we have unicss 0 2 sources a c d target sets triple e for the f so we see okay for the first piece which is a this is a substring starting at index zero it matches with the a which is the source then we are replacing this a with the triple e and similarly for the city it matches with the source cd we are going to replace it with four of the f's which we have triple b triple e b and four f all right so let's see some constraints here we have the input string as a string with less anywhere between 1 2 1 k the length of the straight replacement string replacement rays are going to be the same and they are not going to be empty arrays so each of the index is going to be within the range of the input string and each source or targets array will not be empty string and the s contains only lowercase english letters source targets only contain lowercase english letters so it's very strong constraints which seems to have resolved all of the concerns we don't see any ash case after we apply the strong constraints here so having said that let's see how to solve this problem in general so to solve this problem the first intuitive idea for me is to actually slice the original input string based on the index array and also the source array so let's see for so for example we have uh let's just use the first example we have abcd input string in x02 and sources a and cd so we are going to do the slicing um so the original question description doesn't say if the index is sorted or not so suppose we need to do some sorting and after sorting uh we store the in so when we when i say sorting we should actually sort three of the uh three of the item items together it's not like we just store the index array itself otherwise it's going to mess up with the um with the original or with the intent of the input so let's say if we have uh sorted three of the things accordingly and we end up with something like this we are going to do the slicing based on the index array and also the length of each of the source string so we have the index at zero and the source string as a so has which is which means the lens of one then we are going to let's say get the first piece from the original input string starting at index zero and the results as one so we will have a here and for the next thing we will okay so the next thing we actually do is we say okay the next piece within the next explanation within the original input stream we would be it would be b because we don't have any index here that covers the b here and also similarly for the next piece we will have cd so after slicing there's their input string will be we have three slices a b and c d so a is this piece and the b is a b c d is this piece which starts at index two and then we then the second thing we need to do is we need to do the comparison although and also the replacement so we are going to do the comparison between the source and the piece if the piece match with any of the source so we say okay a is actually equal to the first source and then we are going to replace it with ee um so and then the second thing the b is not actually we don't need to do any comparison with the sort with the source then we append the result to the b into the output and then we see similarly we see cd matches with the source cd we are going to replace the cd with a tree for level f here so having said that let me do some summary about the approach first of all we are going to sort the first step is we are going to sort indices the sources and the targets using easing ascending other of indices so after sorting we should have the indices to have a send the other and also the corresponding so we shouldn't mess up with the original order of the mapping relationship between the indices and sources and also the target and also the second thing we need to do is we need to do slicing the input string and then the next step is to do one pass through the indices through the slices and the hand to go and pass through the slices when i say do one pass we need to do the comparison and also the replacement and uh and also just return and we will return the final results so let's say we have k replacement here because we have some sorting the runtime is going to be k log k for the first time then for the second step and the third step together it would be so in total it would be all of the n when i say all of the n it's n is the length of the string so in total the runtime is o k log k plus n for this solution so actually um when we don't actually need to do the slicing here that is because so the thing that is because we could actually do one pass through the original input string which comes to our second approach so the second approach is we keep a set for the indices so first of all we will i'll say the first step is to add the indices into a hash set so the hash set is for easier look up in the future and then what we are going to do for the next step is going to go through the input string once using index based so it will be something like i from zero to length of the input minus one so 1 so if so the logic is if i is not within the indices then we append the character into the results i forgot to mention that we need to have like a result to be returned finally otherwise if the eye is actually within the indexes we need to get the corresponding substring do comparison so get the corresponding substring from input to comparison with sources with source uh with the source okay with the source with i would say to a source because it should be based on the index so if the source is something matches so if match then we append the target oh say door target otherwise we just append original substring uh maybe or just the source and then we need to update i so we need to update i as i plus less of the source so yes so that's the thing all right so for this one the runtime is just gonna be o n that's because we are not going to do any sorting instead we are just going to go through the input string once using this for loop if we and uh okay so i also mentioned there is a step to add the indexes to a hash set but actually uh because the index so for the index array it should be smaller than the length of the string that is because due to the constraints here which says there will be not there won't be any overlap so there won't be any overlapping about the replacement which means that the index the length of the index array should be should have the length to be smaller or equal to the length of the original string so having said that the runtime for this approach is going to be all of it so i think we currently have pretty much everything let's do the coding work on top of the second approach which is a more efficient version so like i said we need to have a set contain the integers index sets new hash sets and we are going to add everything from the index array into the set so this is index set don't add the index and after that you're going to do one pass through the input string so i is equal to zero smaller than s dot less plus i so like i said uh okay so we need to have like a string builder here string i'll just name it as results as new string builder if the i if index set dot times the i if it doesn't contains i then we just need to resolve out to append uh it will be something like s dot uh car at i and then we continue otherwise we need to get a corresponding slice and do the undo comparison and see if we need to do any uh any replacement we will say so we would do is we say okay so for i don't know it will be something like string subs tr as equal to s dot sub string substring from i to i plus sources um this would be okay so actually it shouldn't be a set it should be a map so the key is the number within the array and the value is indexed within the index array otherwise we will have some trouble finding the corresponding source let me update this one to be a map so this will be a map here so it will be we would put the in okay so this should be index space then zero i is smaller than indices i uh indexed sorry and this is deflance and the plus i so we are going to put the indices the value of it and also the index okay so if it contains a pi then if it doesn't contain then we are going to append the string the character and the continue otherwise we are going to get the okay we are going to get the corresponding source okay so let's say this is the index so index is let's call it index map okay so index map dot get the eye this is the index within the source or the targets i will get sources index.less index.less index.less right and then we do comparison if the substring dot equals if it equals the sources index then we are going to append target corresponding target to the result you are going to say okay result that append uh targets index otherwise we will say okay so let's see we will say results that depend the sources the index and then we proceed the i with a larger step which sources uh index dot once minus one well why we do minus one that is because we have a plus i here at the end so yeah so that's what i want to do and finally we are just going to return the results to string so i will rely on this platform to help us do the debugging which is the fourth step of testing so let's see we have a map i should have an integer map we have contains it will be index map contains key and then i plus equal to sources uh sources index plus one it says can't find the okay so this is the api call all right so we have fixed all the syntax bugs let's do uh okay so we have we definitely have some wrong answer here we have the abcd02 so let's see which one is being messed up okay so this the second one is the thing that is messed up by our algorithm we have abcd02 and we have a b and e c so we so first of all is a b we should replace with triple e and then another thing we have cd so cd is not equal we should uh just keep the cd here but why are we having yeah so why are we having further the e and then the c that's that doesn't make sense to me oh okay so it shouldn't be yeah it shouldn't be the source actually here should be a source because the source can be different than the original string so here it should be substring so okay so now it's actually fixed let's do a summation here all right so that's pretty much it for this approach so let me repeat what i did wrong here so you're going to have the indexes to we are going to have the add indexes to a hashmap so the hashmap is actually the value in the indices array and the index of the array and then for within the for loop if it matches then we are going to replace with the target otherwise we are going to replace with the substring so that's the fix i applied but overall the runtime is still going to be all of it so that's it for this approach and this coding question if you have any question regarding the approach or regarding the regarding anything feel free to leave some comments below if you like this video please helps as well this channel i'll see you next time thanks for watching
|
Find And Replace in String
|
bus-routes
|
You are given a **0-indexed** string `s` that you must perform `k` replacement operations on. The replacement operations are given as three **0-indexed** parallel arrays, `indices`, `sources`, and `targets`, all of length `k`.
To complete the `ith` replacement operation:
1. Check if the **substring** `sources[i]` occurs at index `indices[i]` in the **original string** `s`.
2. If it does not occur, **do nothing**.
3. Otherwise if it does occur, **replace** that substring with `targets[i]`.
For example, if `s = "abcd "`, `indices[i] = 0`, `sources[i] = "ab "`, and `targets[i] = "eee "`, then the result of this replacement will be `"eeecd "`.
All replacement operations must occur **simultaneously**, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will **not overlap**.
* For example, a testcase with `s = "abc "`, `indices = [0, 1]`, and `sources = [ "ab ", "bc "]` will not be generated because the `"ab "` and `"bc "` replacements overlap.
Return _the **resulting string** after performing all replacement operations on_ `s`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "a ", "cd "\], targets = \[ "eee ", "ffff "\]
**Output:** "eeebffff "
**Explanation:**
"a " occurs at index 0 in s, so we replace it with "eee ".
"cd " occurs at index 2 in s, so we replace it with "ffff ".
**Example 2:**
**Input:** s = "abcd ", indices = \[0, 2\], sources = \[ "ab ", "ec "\], targets = \[ "eee ", "ffff "\]
**Output:** "eeecd "
**Explanation:**
"ab " occurs at index 0 in s, so we replace it with "eee ".
"ec " does not occur at index 2 in s, so we do nothing.
**Constraints:**
* `1 <= s.length <= 1000`
* `k == indices.length == sources.length == targets.length`
* `1 <= k <= 100`
* `0 <= indexes[i] < s.length`
* `1 <= sources[i].length, targets[i].length <= 50`
* `s` consists of only lowercase English letters.
* `sources[i]` and `targets[i]` consist of only lowercase English letters.
| null |
Array,Hash Table,Breadth-First Search
|
Hard
| null |
406 |
hey everybody this is Larry this is day 29 oh second to last day of the June Nico daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm let me make sure that I'm recording the screen okay wait is it recording okay I think so uh yes I've uh I actually have a bit of a painful wrist today um because I was playing softball and I did a slide and I think I heard it a little bit um so we'll see how that goes uh may affect my typing maybe not we'll see uh but yeah today's fun is 406 Q reconstruction by height you're giving it away of people which are the attributes of people on a queue not necessarily in order so you have people Supply is equal to height and K where I person is height age and exactly K other people in front okay we construct the queue that is represented by the input away okay sorting problem how do I phrase it in a way that we can get the answer right I think there's a um okay so I think we want to sort by K sub I maybe at Whaley's because that means that for example seven with zero people uh let's actually move this here what is going on why are there two Bowsers did anyone sing this on screen yeah that's kind of weird right hello testing that's really funky okay I think the code I think he's just having issues but anyway um okay so my first idea is sort by the K which is the number of people in front of them because um my intuition here and I guess this is what I would call I mean it may The Anthem may be sorting and maybe um it may be greedy maybe both because sometimes sorting and greedy are the same uh or like the idea but the way that I would uh classify this poem is calling it um what was I was gonna say oh the way that would classify this problem is uh construction algorithm right uh constructive algorithm uh what I mean by that is I construct a strategy to figure it out right and then just have the code simulate and follow that plan and you know if and part of that is going to be greedy but yeah but the idea is that okay so 7-0 for example oh means that okay so 7-0 for example oh means that okay so 7-0 for example oh means that it's just zero people in front of me that's taller so then I start by that right so then I would have seven zero um and then maybe the next is five zero as well and of course by definition you only have two places to put it one is the beginning and one is the end and of course you want it to be the front because the other one is just not working right so you have this and then now you have seven one so then seven one is here um five two would be here right am I missing some numbers I might be missing some numbers so six one I don't know if I'm doing this right I'm just playing around with this identity six one um yeah sixth one would be here right no there's one number ahead so that would be here right uh and then I think five two would be here and then is that right yeah uh and then four would be one two three four right um I think I have to idea now right and maybe when you see the way that I did it makes sense but I'm still trying to think which so I mean the two Dimensions right I think I get the idea of sorting but I'm just trying to figure out more definitively whether I want to sort by the height first or not do we want um I think actually I my first inclination was to sort by K to be honest like I mean you I mentioned it you may have seen it uh but now that thing about it I think sorting by height first makes sense because now let's say we're given height right from tallest to the shortest then we know exactly where to put the number in um because after that you know that for example here there's four people in front and you know that everyone that before you put it in this is the array and or the queue uh Q is a little confusing maybe but you know that everyone that's already in the way is taller than you right um yeah and I think here given the same height we want to go from lowest K to more K just because it makes sense right for example if we're here and we have four and uh for three if we put the four three first then you know we will put it here and then we put four oh wait yeah so then we hear that makes way more sense that and putting it the other way right where if we put four first we might put four here and then for what we hear which then now invalidates the tiebreaker so the type breaking should so I think my strategy now is to sort by height first from tallest to the shortest and then sort by K second because then now you can go from left to right in a way right um okay so that's going to be okay so then now I'm trying to think what is the way to do it right um the reason why I say that is hmm because well um I guess technically hmm is that true no I think because basically okay so the first thing is sorting so we would saw it that's fine that's actually so what I'm thinking of is can I do this so they're sorting so it can't be linear time because if you have to sort it's not going to be linear I know there's some linear sorting but let's just say compare based sorting right um yeah and then after that I don't think I mean it's not going to be your choke points even if you have a linear construction I'll be okay I think you are able to um like I think I don't have a status structure in my mind I think like for example if you have some sort of binary search tree type thing uh or a balanced binary search tree thing where you insert um you know the position or something um then I think you can do this in analog n in total but the naive way which is you know just having a list and it keep on inserting in the middle wherever you need it's going to be N squared for maybe obvious reasons you know because you're at worst you're shifting it to the right end times um hmm how do I want to write that can I do an end like in an easy way that's what I'm trying to do I mean that's what I'm trying to think right all right let's just say people saw it t is equal to Lambda peep uh we want to sort by um to hide first from increasing and then uh P1 okay right so then now we sort and then now we have hmm can I do that in a better way I should find out I don't know that uh because the thing is I mean I guess there are ways you can do with like there are stuff you can do with like binary index tree or something funky where you keep track of the indexes and then you know you um and then like basically you it's almost like um it's almost like a suffix like almost like a prefix somebody reverse of it like a suffix sum and then you kind of accumulate all the order all the ones together and then calculate the indexes at the end and what I mean by that is that for example maybe you would um and I'm not going to implement this because I think this is way too much work for me but for example let's say you have something like this you would have some you start with seven zero um and then seven one and then you have what is it six one so six one would be here and then now you do a suffix thing of uh everything here right so here you accumulate the plus one say I mean and there's a lot of bookkeeping to make sure your index uses are correct but then now the next one is going to be what um five zero so five zeros here oops and then now of course you do a plus one on other stuff afterwards as well um and actually I think maybe the easiest way is just minus one to the prefix um should be equivalent but you get the idea right um and then you kind of sum up all the indexes at the end or something like that um especially given that your um yeah can I do with subtraction would that be really funky now I mean I maybe I don't think this is right because I think you can insert stuff in the middle and then like maybe you can enter stuff here and then maybe even comes up in the next one like five two will be five two maybe I'm making things up and I'm one pretending over here and then here but then the suffix would just be here um and then that would be obviously just wow but maybe I don't know maybe I need to play around with this idea a little bit because but in any case okay so all of that being said so you spend a lot of time here as you might notice I'm doing this live and you guys see my dark process and trying to you know some days try to push myself a little bit today maybe would have been one of them but yeah but the idea is that now for was it height and what's okay again is there whatever K I guess in people um let's say we have an answer way and here we go um uh answered dot so we don't even need the height well we need it because we need to append it but we don't need to hide in theory what we need is what's it is to uh let me look it up python away insert I forget what it said is it just insert huh but I don't okay fine so then insert at K of Pi K right I guess technically this is a list of I think the check is in cap um and that's pretty much it um this is going to be N squared which is why I took a long time thinking about it though the idea is um you know obviously I kept wearing it but I was trying to see if I could do n log n um if you have an N log n solution let me know maybe I don't need it but yeah 820. uh and this is actually very quick code and I probably have done this video much quicker so if you're watching but hopefully I think you can do something cool with um like I mean there are definitely ways you can hack it um to kind of um have this idea I think like a like I was thinking about using a linked list uh so that's another way to do it in analog n um and you know my first intuition is like this but then you have to skip to the cave element quicker so then in that case you just make it a skip list right so if I so I don't know if you can make it what I said with prefix sum but if definitely you can do a probabilistic and again with skip list this is all of n Square here all of n log n sorting uh We've skipped list you can even probably do it with like what is it sorted list uh like a sort of assorted list which is the same idea by kind of um you know for example if you need to insert at K you just take um we could actually play Maybe up solve this a little bit I was I could just maybe not be that hard to write so let me actually try to do this it may be what I mean it should be right but we might run out bits though you could also say that we can be um uh we uh what you might call it we key every like once in a while anyway so the idea behind the sorted list thing um is that you can say insert it with a value in the first place and then when you need to insert it like when you insert the k for Value um you know you take the item on index um index K minus one and then index K and then take the middle value um and you know the average value and then insert it so that you insert it at that place but of course at some point you run out bits um so then you just have to rebalance it by just you know re-index everything from zero to n or re-index everything from zero to n or re-index everything from zero to n or something like that and of course there's the same idea with um like rebalancing on every doubling and if you rebalance it on every doubling it should be linear uh on constant um so then there's just gonna be like n log n or something like that if I make that up uh you know that's me but like I said these things are more complex to the n-square solution but possible uh you n-square solution but possible uh you n-square solution but possible uh you know I mean these are just things that you know uh I like to upset uh a little bit refreshed and rested I like to observe it uh but I'm a little bit tired I'm a little bit lazy on radio my apologies but yeah just you know take uh let's say SL sub K uh maybe episode some K minus one and as L sub K and average the key and then that's pretty much it and insert the key so basically you force yourself to squeeze in there but of course like I said you may run out bits because every time you do this you uh get one viewer and of course the Manchester only goes up to like what is it um 128 is it or negative 127 maybe uh no negative 128 by the way like you just went up bits because web n is equal to two thousand um but you know that's why you do a rebalance but anyway if none of that makes sense to you it's okay I hope that you'll take away from this video If you get nothing else is of course the sorting and the why you saw my logic um yeah the idea is starting by height is so that means that when we get to the person we know everyone in that queue is already in front of you so now you to get to exactly K you do k um you know you just put yourself in a k index and then because everyone that goes behind you is either shorter or sorry everyone that gets inserted after you is either behind you um or they're shorter than you so every everyone before you is taller than you and everyone behind you doesn't matter so that's why we saw it this way and that's the proof kind of I mean obviously I'm saying it in words but you know that's basically almost like an exhaustive case type of proof um cool uh that's all I have for today let me know what you think stay good stay healthy took your mental health I'll see you later and take care bye
|
Queue Reconstruction by Height
|
queue-reconstruction-by-height
|
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`.
Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue).
**Example 1:**
**Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\]
**Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\]
**Explanation:**
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue.
**Example 2:**
**Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\]
**Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\]
**Constraints:**
* `1 <= people.length <= 2000`
* `0 <= hi <= 106`
* `0 <= ki < people.length`
* It is guaranteed that the queue can be reconstructed.
|
What can you say about the position of the shortest person?
If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
|
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
|
Medium
|
315
|
135 |
Problem Which Name on This D New Lead Is Candy Distribution Problem D Problem At List One Candy Mins Each child should get at least one candy Mains is in the rating Which is in each element of each rating They will get one candy and children with D higher rating get more candies give fear nevers it mains zero's perspective one has higher candy if you have higher rating so one will get an extra academy and SMS zero's perspective if you have higher candy then you also get one extra candy If you get a total candidate example, also in perspective, if 2 has higher candy, then you will get it, meaning if you have a hi rating, then you will get an extra candy, but if we want a hi rating, then if it gets an extra continue, then total straight greedy approach. Because of hair, we are seeing that first of all, we have to give Elements 11 to the one who has higher rating, then to all three, but to the one who has hi rating, we have to give Candice first, so it means it is like a greedy approach, first we give to the higher one. Then lower will go like this so this is the Giridih approach hair bill do this they bill make an actor that in doctor what we will do is make a vector of then that will reverse left once and like this one will do left once and once We will traverse right because there is nothing to the left of zero, so we will start from index one and similarly when we reverse left on right, we will not traverse from the next index because there is nothing to the right of next index, so we will We will start from N - 2, so we will We will start from N - 2, so we will We will start from N - 2, so let's do this problem, we have to do Bill travels from left to right, zero system, its rating should be more than the previous element, mains is right to left, what do we have to keep in mind while traversing how to start the index. These type equals from n - 2, how to start the index. These type equals from n - 2, how to start the index. These type equals from n - 2, we cannot start from n - 2 because of n - 1 we cannot start from n - 2 because of n - 1 we cannot start from n - 2 because of n - 1 because if we start from n minus one, then there is nothing lying on its right side, so we cannot compare it from right to side. There was nothing lying on the left, so we could not compare on the left, so we started from the front, so now in this we will start from N - 2. started from the front, so now in this we will start from N - 2. started from the front, so now in this we will start from N - 2. I guttering is equal, you give zero I - - In this we will compare IF give zero I - - In this we will compare IF give zero I - - In this we will compare IF ratings of I. Give greater ratings of I-1 So know what bill do If I minus one means more than the previous index then what will we do about this, if it is more than the index on the right then we can increase it Do you understand NO IT IS GOING 53.5 This solution NO IT IS GOING 53.5 This solution NO IT IS GOING 53.5 This solution depends on time complexity and space complexity so d cart time space complexity is off n you can see a is n vector bacteria space and space so space complexity is bill b off n and d time complexity is bill b of n Also because creating n loop hair and hair it is not n next air look so time electricity bill not be of n² time complexity bill be of n bigo open if you find this helpful then you can like and subscribe this channel and also comment so that I can improve my approach a little too.
|
Candy
|
candy
|
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`.
You are giving candies to these children subjected to the following requirements:
* Each child must have at least one candy.
* Children with a higher rating get more candies than their neighbors.
Return _the minimum number of candies you need to have to distribute the candies to the children_.
**Example 1:**
**Input:** ratings = \[1,0,2\]
**Output:** 5
**Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
**Example 2:**
**Input:** ratings = \[1,2,2\]
**Output:** 4
**Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
**Constraints:**
* `n == ratings.length`
* `1 <= n <= 2 * 104`
* `0 <= ratings[i] <= 2 * 104`
| null |
Array,Greedy
|
Hard
| null |
456 |
Hello hello everyone welcome and welcome back to my channel suggestion or after hours problems want to pattern to interest problem give them go near to find a subsequent is and subsequent true dot print serious ram bhai namaste nuskhe sankat eye lashes relation's putnam sufficient evidence of According to shoot's lab something okay well one two three two take medicine three two pattern me to find the return 2012 pattern otherwise return for this the fifth standard tis born in so let's see 132 patan hair means youth is number of ice MP3 is Naam saunf ke ki end to is namse af ko che a ki ai jain ke haathon end taxes and worship in dishao Voter ID of Baroda Intex 4G thank you should Dwijesh Winters reporting utha ki and with element should be true times of i ki in relationship ke A look and those people's auspicious looms of check times its beginning this end of wishes and right such something like this pattern need to find out whether a subsequent in this area or not then that year in these directions itni si 14214 so this Because I index of years in this also want to three i20 Ujjain that year sorry this face I want JB Urgent appeal to that his is this three two is so 142 basis of oil is vansh we to file name of the WhatsApp To and hum sab jaiz hai 210 inside the short rahi hai a satisfying this order hands in the subsequent sohan tweet 210 b founder subsequent side follow 13252 part three does it is the land of the but hum sab theek hoon 210 is problem rahi hai ansuia1974 problem only and videos improve posts and will give the best upon and will see optimal that said that you are freshly proven everything that such devastation Shane Warne in such cases 134 a is vansh apne husband then and took a the heard that you See What Me To Find The Three And Different Names Of It Which Alarms Of Say Z Ki And Lots Of Cake And Pintu Final Decision On Tomorrow Morning Need To Find Out Free Numbers What We Can Do Also Desai Leave Sorry Exam Ka K Near Meaning Object That I Don't Color Change And Specification K 22.3 Numbers What We Can Do Simply Vighnavinan 22.3 Numbers What We Can Do Simply Vighnavinan 22.3 Numbers What We Can Do Simply Vighnavinan All Possibilities That's All Chief Chemist Host 4142 Please 1342 E Will Wither 142 Can Withdraw All Possibilities Vacancy Is The Software To Find Free Numbers With Three Arrested Looks Like He Had Scene Active Looks 13 Se Related Useful S Every Time Lineage Number To What Will U Do K MLA Paul A Coil On Which Will Start From Throat And Impotent And I Plus This Will Give The Name Of The I Without You 1ST Look For Z It Will Start From - Start From - Start From - 142 Mode Of Muslims Do Not Want To Include Game Morning Setting From It And A Plus That One Day Birbal Hath And Loon Polish Phone Number 1 A For K Sequel To Again From Z Plus One Confident Enough To Respect Element Cancer Hole Tank K PLUG REPORT INSTITUTIONS AND OFFICES ARE INSTITATED AFTER AND YOU WILL METHOD TIME COMPLETENESS AND WHAT DO INSIDE IT THERE IS A WILL CHECK-IN IS A WILL CHECK-IN IS A WILL CHECK-IN THIS CONDITION HAS BEEN SATISFIED WITH TEAMS OF I THIS ARTICLE NORMS OF WHICH IS KOK WITH IMMEDIATE DECISION 900 CHINESE MILITARY RETURNED After subset with all of this for you will just for fun I safe such group photo very simple to approach and you will be type but and physical activity for standard and poor index page and Sudhir that any officer a that from this point project will think Of Optimism Approach But See Mirza Pati Loop Due to this condition of the looted person and start the fast of defeat will return to others then for follow him on twitter and you are the day for the obviously way news most loud get a festival time limit exceeded Not only this, I have in the premises of Kanteen Co for the best of luck, hope and a single marriage time complexity for others to follow it from this how what you can improve your karmic burdens on Sambhav A Few Can Trade and Super Model Sr. Improving it's so how can we square and square in the tool that right now 1000 and 2nd minute one lock flash light that details and things on what are you doing this for finding and fighting for justice element wear look three different looks on other website Patna what we will do will reduce the plots that twenty-20 to let me write the second that twenty-20 to let me write the second that twenty-20 to let me write the second minister photo I want 34 to water will do it a to find norms of I's shooting license of K and terms of caste class and subject this country meru Ooo Ki Swapna Dosh I Will Be See You Every Minute For The Earth Apne Pati Send Your Journey To Roots That And All This One Is Not Used In Excel Unite And How Will It Take Meaning A Variable That And She Will Say Goodbye A Look At This Time to minutes and baking available in English and give you intend to the second in terms of the information for rent in to-do list to-do list to-do list ok equipped on this topic pimple in his mind that of it is and one to right no business management to check Will start from fear and will start from Z plus one okay drowned in this suit what will oo will check weather in the element Vikas Nagpal at this place and norms of that and norms of this lesson name of check person is Condition ka sukriya chatting with kardashians proof like owaisi me powder subsequent death will return to e will attain true is otherwise what will you find out minimum element and will updates name 5a that with face will update 10 min event management with equal to main element That and terms of check on e was not enough because they want a developed to fight with Loom subscribe software update the us and they will put forward till the victims get that us similarly the evil come here and he fears and will find one share the OK management bunungi baje do minimum on two pitches that is on the disputed site that for the state what they are doing this approach is VR signin Gautam Vyas keeping that name file invariable every time they will update absolutely minimum balance developed bean lost in Thought this right down the fifth garlic handed over 100 meal element available absolutely minimum element senior Amazing minimum and baking is condition so open text based approach share time complexities of innocence on bring to do and specific a that pinpoint were ok but this approach will Also not detected with see the countries my tablet above pride and standards above fight you enjoy absolutely low temperature 5 * you enjoy absolutely low temperature 5 * you enjoy absolutely low temperature 5 * text on temperature 510 race-2 so text on temperature 510 race-2 so text on temperature 510 race-2 so in that if this greater than temperature had not come on 56th that fans' metal father optimized For the that fans' metal father optimized For the that fans' metal father optimized For the devices, newly appointed CEO Vikram Father Optimism Ki 1342 Phone Ko Android This Front of Approach is only 250 Kg - Turmoyle in Square Is Not Official 250 Kg - Turmoyle in Square Is Not Official 250 Kg - Turmoyle in Square Is Not Official You Can Do and When You Can Think of a World of Incest and Patidev Sachin Gaur You Can Think Ko Binary Search And Sachin Gaur In This Is Not Any Way Find That You Can Do But Something Is The Kun Is Not To Be Used And No One Can Not Be Death-Proof Indian And No One Can Not Be Death-Proof Indian And No One Can Not Be Death-Proof Indian Institute Of U Hai Because 2010 Login Hotspot Open Ki Daant Previous Song Maafik Airplane mode of Instagram is Facebook app so open either video set 200 liya that tweet a theory behind all vihar to rooms for grade 1 like no need to think of you singer look soft ho sleep chain ko one sirf do one pathan video Send it okay lethargy aa I keep it all day important approach should just click that bihar to find out name white a selection of today shoot from villain no 21 a ko tight is dam ki vanshi to pathak ko tight what is that v9 30 To that and which means me to find a which line what you need to think of anything but how to reduce it into a single that tuition 215 value you can find that find itunes on that Bigg Boss Neetu Singhal on ke Benur finding responsibility Value Alone Without You Need To Them For This Is Not True Values What Do You Simply Need Not True Values What Do You Simply Need Not True Values What Do You Simply Need To Points 138 In Use For Points Only Rottweiler To How To Find The Number Five And Systems Which Can Also Give Store Sir To Sambhav Sunao Question Is How To us a super duper member in the previous problems that tweet yesterday I am told that whenever you want to tours drinking water supply I took minutes to prepare follow that something you can think of as you can attack on 9th may you 2015 Start Kar Do Ki Leti How Way Can Ujjain Hai So Tried And Tried To Think How You Can You Take Care Unit To Find The Number Of And Worms In Terms Of Patience Also Possible Story And Tagged As I Am Online ATopic Hai What Will Do This Is The Wind 141 A Look At What And What You Need To Find 132 Pattern Me To Front A Swing Stock Rate In Stock Which Three Two E Will Be Maintained And Education Will Be Stored Possible Anti Snake Venom White Unite To Fight A Love How This Will Happen Lieutenant 's Fragrance And Third One Needle Solder Iron Or 's Fragrance And Third One Needle Solder Iron Or 's Fragrance And Third One Needle Solder Iron Or Only Wheel Drive Angry Bird Of The Stars In This Day Will Understand What Specific But This Youth Sisodhi Will Start From The Right And Will Go To The Left Now Will Be From Right To Left side white along with me to go for a joke is superhit navjeevan namak hai to and office more tweet challenge in i to from here play time element ki people change srijan k related to start from right to left side of j&k and find it side of j&k and find it side of j&k and find it Difficult to oo ok town that why will be traveling from the best a look on that download how will be to reduce of train number 1 which one day sham singh issue only solve this problem comes in the greater next greater enrichment or right service problem Are Next Greater Element Online Available Shoulder Problem To You Do It Is Time For Similar To This Problem Hogi Sim Which Chapter Notes Greater Element On Right I Do It They 14 Years Only Romance And Sex Similar To This Website Okay So I 'm Junior In This Suit Invent Honge 'm Junior In This Suit Invent Honge 'm Junior In This Suit Invent Honge 250 Set A Look On The Sun Can Invest Rs 14 Will Be Maintaining 32 Readers In Vitamin Tanning Three Do It Is Top Anime Top 10 Talk With Greater Than All The Last Updated On A Look On 220 Tools Such A Beneficial Letter E Will Get More For tomorrow morning this beach and this is greater than this two and Sudesh Kumar Kanvij Times a day that and you can be done village's protest Torch Light Sport this issue and Sanjay Jatan's pat spray turn into problems of change letter in this alone These are the walking 200 grams into a that Vijendra with to can we are a of the boat so let's see then this force third element to the specific file limit for development that and travels to this name of the testicles to interest kinda limit that and Have a sense of today at present for winters removed from the site and support us like switch off do a trunk and sport in benefit semolina investment in english 200 grams sugar slightly different countries name is pic and navmi ko to 13 hai a photo I give that village, the other team, that this jersey, this note, great saints, 220, this canopy cup, I have taken sugar, but now we switch off the vegetable, I pay a tribute to the NDA, smile on the new ten water, this loop changes, list a few. Recently, there was a blast in this rally with a little element, death of 9 and that morning what you think powder want to write in this direction of the village fight aspecific and initiate steps norms of check-in that your you are militant 250 definite in this a little element in The rupee coffee powder want to cuttack I just like water tank pencil four one and they will discuss one more case such a good step for elements of elements notification that dandruff bin travels from right to left in Amlo file so little limit that if name which side Stitch Contact Number File This But Little Element That Dry Found That Arbaaz *Pattern Will Return To Arbaaz *Pattern Will Return To Arbaaz *Pattern Will Return To Hai Otherwise Bill's Popping From This Talk Main Anil Mp3 File Cigarette To Top Up The Phone Katihar To Right Ponting To Regret And 252 One Tex Years To ring Lal Jaswal you can see in stock playstore in the largest value file artistic system subject and object fourth largest and finally chopped one ok and will be what ever been formed step which to retain the forest that Bigg Boss tatmil bhi flash light ko saaf bus Platinum 0 ASpecific The Right 200th Test Absolutely Worry Judgment Aa To Idano Trident Who With AIDS And Will Return For This The Bride In This Code Yes Of Course You Will Understand This Uttarayan Holiday In The Trains With The City Magistrate - 1320 Trains With The City Magistrate - 1320 Trains With The City Magistrate - 1320 A Minus One hands free to Vivo A severe attack in stock Burst element Management University Name Fennel cake Rishi Vaikunth Alarm set with minimal blur Turn off according to weather Yasmin Maya is a profile portion Stock I send your photo in office Two ingredients Top of Elementary mid that to a bit for this from this task is to see Arvind specific Arvind story time thought element and you will come and truly step that some ink tank in dubai a pan also courier mp3s of candidate against talent is frustrated according to film hate Story of want 210 250 notice to here and mihir hai to every time e tried every time his thought element will enjoy the satanic verses from changes 91 tomorrow morning is clear that this - - - - - garlic kinda limit witch that this - - - - - garlic kinda limit witch was to hai to minus one So the little limit has been reached to win this - Pandit comes to and win this - Pandit comes to and win this - Pandit comes to and half inch 3 that and numbers off side stems of chick and we have taken two cups of sugar and so this will return to 15th handed over next this to approach and Code Time Complexity After And Pacific Ocean Singh Extract 105th Album Like Subscribe My Channel And Vitamin E Don't Know The Calling And Thanks Watching
|
132 Pattern
|
132-pattern
|
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
|
Medium
| null |
388 |
today we're going to be working on lead code question number 388 longest absolute file path suppose we have a file system that stores both files and directories an example of one file system is represented in the following picture so it's going to be represent we're going to be given uh a file system inside the like in the form of a string and we're going to be represent are we going to be returning the absolute path of like the absolute path of any file and which is going to make up the longest path so in this example where's example one over here uh the apps so there is only one file in it right file.ext it right file.ext it right file.ext so we're just gonna be returning the absolute uh path of that file which is 20 characters long so we're going to be returning 20. in this case we have two files in this file system we're gonna one absolute path of uh these files is going to be 21 and 32 so we have to return the longest absolute path which is going to be 32. we're going to be making use of the stack in this one uh so we're gonna have a DQ d Q of integer let's call it stack which is equal to new array DQ okay so this is our stack we're gonna push initially we're gonna be pushing uh like a dummy length so for that we'll just push 0 in it and we're going to initialize our maximum length to zero because that if you look at the example three uh when there is no file in there we need uh we need to return zero okay so what we're going to be doing is like we're going to be splitting the this input dots player uh with like whenever you see a slash n uh we're going to be splitting it up and it's gonna give us a an area of strings so we're gonna say that for every single uh every single string in that array or what you're going to be doing is like first of all uh we need the level right so and level is basically equal to that current string which you had you wanna know that if it is a if it is like just a file or it has a level in it so if the last uh index of is Dash t so we're going to take that one and plus one so we're gonna have our level where we can actually start looking for the file so we're gonna say while the level Plus 1 is less than the stack dot size we're going to keep popping things up so that we are left with just the file name stack dot pop okay so when we are here now we can actually what we can do is like we can pick the stack right and then s dot length uh s dot length and then minus the level plus one okay minus level plus one yes so that's gonna give us the length of that and then uh first we're gonna be putting that length into the stack dot push that length and then we're gonna check if we need to update the we are only gonna update the length if it is if it has a DOT and we are sure that this is uh this has a file in it like it is a file so if that s dot contains and how can we check if it has a file in it and we can check it by the DOT sign because uh the files are going to have some extensions so if that is the case you can update the uh the max length to basically the math dot Max between its old value and the new value is going to be the length minus 1. so here we actually calculated that new length okay and once we are out of this for Loop we processed all the uh all the string strings in that splitted array we can just return the maximum length foreign looking good and it works
|
Longest Absolute File Path
|
longest-absolute-file-path
|
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
Here, we have `dir` as the only directory in the root. `dir` contains two subdirectories, `subdir1` and `subdir2`. `subdir1` contains a file `file1.ext` and subdirectory `subsubdir1`. `subdir2` contains a subdirectory `subsubdir2`, which contains a file `file2.ext`.
In text form, it looks like this (with ⟶ representing the tab character):
dir
⟶ subdir1
⟶ ⟶ file1.ext
⟶ ⟶ subsubdir1
⟶ subdir2
⟶ ⟶ subsubdir2
⟶ ⟶ ⟶ file2.ext
If we were to write this representation in code, it will look like this: `"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext "`. Note that the `'\n'` and `'\t'` are the new-line and tab characters.
Every file and directory has a unique **absolute path** in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by `'/'s`. Using the above example, the **absolute path** to `file2.ext` is `"dir/subdir2/subsubdir2/file2.ext "`. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form `name.extension`, where `name` and `extension` consist of letters, digits, and/or spaces.
Given a string `input` representing the file system in the explained format, return _the length of the **longest absolute path** to a **file** in the abstracted file system_. If there is no file in the system, return `0`.
**Note** that the testcases are generated such that the file system is valid and no file or directory name has length 0.
**Example 1:**
**Input:** input = "dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext "
**Output:** 20
**Explanation:** We have only one file, and the absolute path is "dir/subdir2/file.ext " of length 20.
**Example 2:**
**Input:** input = "dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext "
**Output:** 32
**Explanation:** We have two files:
"dir/subdir1/file1.ext " of length 21
"dir/subdir2/subsubdir2/file2.ext " of length 32.
We return 32 since it is the longest absolute path to a file.
**Example 3:**
**Input:** input = "a "
**Output:** 0
**Explanation:** We do not have any files, just a single directory named "a ".
**Constraints:**
* `1 <= input.length <= 104`
* `input` may contain lowercase or uppercase English letters, a new line character `'\n'`, a tab character `'\t'`, a dot `'.'`, a space `' '`, and digits.
* All file and directory names have **positive** length.
| null |
String,Stack,Depth-First Search
|
Medium
| null |
127 |
although i am today covering up for yesterday's session uh and yesterday's question was word ladder in this question you are given a dictionary and a beginning word and the end word uh and some rules and the rule says that two words are related if they differ by archmarks one character so what you need to do in this question you need to return the length of the shortest transformation that is possible starting from the begin word till end word and that in each transformation you can apply the rules that stated that two words are related if they differ by at least one character at max one character so let's walk through one of the example uh you need to start with hit and you need to check whether you need whether you can reach cog or not using the word list which is acting as a dictionary in this case how can you reach uh from hit till cog uh this is the explanation given here hit from hit to you go to hot from hot you go to dot from dot hero to dog and from dog you go to cog how many transactions did we do for reaching the end word five transactions one two three four five so actually we did one two three four transactions and uh we actually did four transactions but uh the total number of words that came in between were five so transaction plus one gives you the answer also uh if it is not possible to reach uh the terminal state uh return zero in those cases this is a negative case that is being discussed in this example without much ado let's look at the slideshow that i have created and let me just start the slideshow this is a typical graph problem uh if you are not aware of graphs don't worry i'll explain how we can do uh how can we build graphs and the second part would be how can we traverse the graphs uh in this question what will you build we will build an undirected unweighted graph what is an undirected graph means uh with a node points a and b nodes are connected with each other there is no specific direction for example this one is a directed one a points to b or b points to a so there's a particular direction uh in which uh the tree in which the graph flows in an undirected graph there is no particular direction you can either move from a to b or from b to a what is unweighted there is no weight a sign on this edge that means it's an unweighted graph and i have taken exactly the same uh example that was specified in the question so as to help you understand better uh i will also discuss why we'll go for the bfs reversal or the dfs reversal whichever is up so moving to the next slide now uh and let's talk about how are we going to build graph uh we will need to define a helper method which tells us uh whether uh the whether a string is related to another string or not so we'll pass a string will pass the string a and string b two strings to a helper method and it will return a boolean telling us whether these are related or not what is the relation between uh these two strings uh that they differ at max by one character and let's build the graph the semantics of the graph would be something like this the first one is the input string which tells us how many strings are related to this string the second value is how many strings are related uh to the string the key string and this would be the value where uh whatever the strings are listed in the value part these are related to uh the key string uh let's talk and take an example uh hit and hot these are related and they differ by one character oh hot dot and lot so this is again a list of strings dot and lot dot differed by dot hot dog and lot they have three words in this part and so on so let's break the problem into two parts as i told we'll build a helper method that accepts two string and checks if they if the two string different bat max one character pretty simple and i think everyone would be able to write this code and how are we going to build the map we'll iterate uh over all the elements using two loops and order of n square complexity and we'll pass for each possibility we'll invoke the helper method and we'll uh will build the graph using the response of those helper meters for what for n into m string for all the strings and let's talk about the traversal part y will go for the bfs and not the dfs one so in general for undirected uh grass uh bfs reversal in this case would give us the answer and no and dfs would be time consuming uh let's take an example here suppose this is the what we do in a dfs reversal we traverse over depth and if from hit you may reach cog in 10 transactions if you are the one part could be this the other part could be a smaller one which is uh which occurs at a depth of five so in dfs reversal what you will be doing is you will be reaching cog and then you will be storing that information in the variable and you write returning through all the paths that are present in this graph in a depth dfs fashion and if you find a better value uh then you will replace it with the minimum value if not you will continue moving in that one issue with this would be uh since you are moving in depth first you will be reaching you will be going by one path instead of touching all the boundaries touching all the nodes uh that are nearest to the root uh that will that is the case with the bfs reversal because in bfs reversal we covered edges that are at the same position at the same time so we go in a breadth-wise same time so we go in a breadth-wise same time so we go in a breadth-wise fashion so think of this example the diagram is a bfs one so whatever nodes are at a distance one will we'll consider them first so you don't need to think of the minimum one part because minimum will be automatically taken care of by the bfs reversal so if length is one here or distance is one this distance is two all the nodes uh at a distance two will be traversed at the same time and for this the distance would be three at any point if you can see you can find your terminal node you break that condition that will be the minimum answer why this is not true with the dfs reversal let's move ahead how are we going to do the first reversal in this case we'll start with an initial word hit add it into the queue and we have built this graph by the algorithm that i specified before and let's move ahead uh we added hit and this is our end word we pull out the element from the uh queue and um since it is not equal to end word we will uh add all its children that have presented our map into the uh queue so this is what we searched for uh hort's children and we'll add it all them all of them in uh in the queue so if element is not uh not the end word which i stated push all its children in the queue if they have not been visited in the past also you need to take care what all children have been visited in the past so that you don't keep on adding elements again and again once all the elements have been pushed mark that node as visited let me just explain the visited concept here if a is connected with b and so that means there could be a case where you are adding pulling out a and adding b children again from b children you are adding a again so that generates a cycle kind of a thing uh we break the cycle using the visited concept within it concept so let's move ahead in the traversal so we pulled out hit we added hot and we marked hit as visited gets marked as this and level gets incremented to one and we pull out hot now uh since hot is not equal to cog uh what we'll do we'll add all its children uh into the queue so let's add all its children dot and uh lord gets added into the queue and this tells us the termination of level two and this is domination of level one so let's move ahead in the traversal what gets added into the visited array level increments by two this is a terminal state for level two and uh since dot we pull out dot and dot is not equal to uh the end word will add all its children into the queue uh only those children that are not part of the visited array since hot is part of the data will not add that uh we'll add dog and lot so the dog and lot will go here so dog and lord gets here and we just popped out this uh also let's move ahead in the next iteration we get lot so lot has horton dot hot and dot are already part of uh the visited so we'll ignore them and move ahead we'll ignore them and so next we have a dog in the attic and we pull out a dog from the queue we have log and cog axis children we'll add them in the queue because none of them is visited and we will move ahead with the iteration uh the blue line signifies the end of level three so we pulled out dog and we added dog in the visited area because it has been marked let me just take a highlighter here and let's move ahead with the uh next lot iteration lot has hotend dot lot hot and dot are uh already part of uh the visited i said we'll ignore it and next we have this tells us the termination of level three and next in queue is log we go to log and we see that it's still in a dog and cog we pull out a log from it and add cog to it so let's move on to the next iteration uh level is four so far uh cog we pulled out cog and turns out to be equal to the terminal word we found the terminal word and we returned level plus one as an answer because i told about transaction plus one gives us the accurate answer uh and hence a level act as the number of transactions that we have done uh from the root of the graph root uh being the start word in this case so let's quickly code this up uh all the elements that are given in our dictionary word so we will add set or define a new set new hash set and what we are going to do we will add all the elements in the hash setter that present in the list so for integer here in word list we'll add it in set dot add here and now let's uh define the helper method that tells us whether two strings are related or not so the return type of this helper method would be boolean and let's name a strings a differ by one so we have string a and we have string b and let's just check whether the length of these strings are equal or not uh if a dot length is not equal to b dot length if they have unequal length then return false otherwise let's continue with the a check let's define a boolean variable uh found one difference and initialize it to false for integer i equals to zero since both of them have the same length you can take any of the length uh or a that of a or b and let's uh pull out character of what a character vertical from is character from a string a and similarly let's pull out the b8 character from string b is character from string b and let's check if a cat equals to b if they are unequal then let's update found one difference to true also before the check let's we need to check whether we have found uh whether found one difference is already true or not that means this is second difference if that is the case return false otherwise will return true so this is one of the helper method uh that tells us where the two string differ by at max one character and let's define the map so map is of string comma list of strings new hash map and let's build the graph let's define a helper method build the graph and what we'll pass will pass the map into to the graph and our set data set also we need to add the begin word data set because from the begin word uh we need to gen we need to build that graph not the terminal word so say dot add begin word if it is there in the word list it's fine if it is not then you have to start iteration from beginner hence we have added into our dictionary or the data set up for word list and let's build a graph so building graph is also pretty simple exercise avoid the return type is void build graph and uh what are the two parameters that is accepting one is a string a map another one is a set of uh strings sorry it has to be strings word set and let's build it for integer i equals to zero what we can do we can iterate over this the word set array word set and a string and another follow for string let's call inert yell word set again so we are iterating over uh the string the array twice using uh order transfer time complexity and let's check if i el dot equals inner el or not if they are equal just continue otherwise let's build the graph because that means it is the same element how are we going to build it we will check whether they differ by a string difference by one or not then we have e l and inner real pass to it if that is true then let's add the elements into the graph so let's get whatever is being stored map dot get or default yield comma new adder list and this will be a list of strings that are that means connections and connections dot add in a pl pretty simple and let's just put this information back in the map connections so what we have done we have built the graph we pulled out the information from the map what all connections already existed and added the new connection to this and put back the same information back into the map so since this means that el is connected to in a real and similarly what we need to do we need to establish the connection between inner el toval so i'll repeat the same process connections for inner el and this time i'll the key would be in a real and we'll be adding el to it the element to it and inner el would be the key again and this would be connections to uh you can actually spot in real and this is how we have built the graph and we are successful and let's uh generally define another set which is of strings again which tells us what all elements have been visited so visitor is very important hash set for strings and this is a visited let's define the queue we have standard way of writing the bfs reversal queue new linked list and q dot offer from which word are we starting begin word we are starting from the picket mode and while q is not empty let's calculate the size q dot size and while size minus is greater than zero will pull out the head element q dot pull out the hello mint and if we check if head equals to uh the end word if that is the case we'll return level plus one so let's define variable level and return level plus one that's good and let's check if visited dot contains head if it contains it just continue that with the iteration otherwise if it doesn't contains head so that means it is an unvisited element we'll add all its children into the string while it's returning all its connections let's call it connection map.get or default map.get or default map.get or default what is the key head is the key and what is the default list and let's check if visited contain does not contain connection if that connection is not built in visited we'll add it in the visited q dot offer visited and let's mark since all the all its connections have been added we'll mark uh the head as visited dot add thread and once we are done with this logic we'll check if visited dot contains end word if that contains end word will return level otherwise we'll return three simple way of checking if it has uh the end word then we return the level if it doesn't have the inward built on zero that means it's not present also i forgot to increment the level so i incremented level head fingers crossed it's kind of a verbose code compilation error again some typo sorry for that oh sorry it has to be connection instead of it absolutely correct and let me just submit this code accepted this time the solution got accepted and uh let's talk about a time complicated time complexity of a graft reversal problem uh is order of n square slash order of v plus c which is number of vertices edges and uh also you are building a graph in order of n square complexity hence it is order of n the worst case would be order of n square the space complexity would be again order of v plus c are the number of vertices plus edges thanks for watching the video
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
455 |
hello hi guys good morning welcome back and assign cookies it has been asked by many companies xedia Adobe Amazon Apple Microsoft and so on and so forth let's see what the problem says uh I give you the C what the problem says you are given an AR G and AR s AR G is the greed factor of the children's what you are having so you are having some n childrens let's say these are n childrens and for every correspondent children you have a greed Factor what that greed factor means that the greed factor means that he can except a cookie which is at least of his greed factor which means if he has a greed factor of three and I have a cookie array this s AR cookie aray this cookie aray say okay I have a cookie aray uh let's say the cookie size is the cookie size one so a person or a child with a great factor of two will accept at least a cookie of size two a person of size a person of greed Factor basically a child of greed factor three will accept a cookie of size at least three that is what we are referring so basically we are saying that a child of a greed Factor like a greed Factor should accept more size of his cookie at least like equal or more size of its cookie so this is what we need to have and we want to maximize the number of content children output which means just maximizing the assignment of cookie to children we want maximum assignment for this to happen so if you look at the example what we will see that one of this child will get one of this cookie and that's it that's the only thing two and three need at least two and three as the cookie size which is not available so it will not work so answer is one here in this case one you will see it can assign let's say to two and two can assign let's say to three so basically the cookie of size three can be assigned to a child of two or we can also say that a child uh with a greed one can be signed with a cookie of fun and a child with a greed two can be signed with a cookie of two that's also a valid case and thus the maximum number of assignment can be two answer is to so very obvious thing which comes in our mind is Beya what I will do is um I'll just start from the very beginning of this and maybe what I can do is I can try to check for this specific child if he can get some cookie or not so what I'll do is in this example itself you saw that and it should work by right that for this child I go and check for in my S AR and I'll go and check okay if he can assign yeah he can get a cookie of his size he can get a cookie which means of his size or less he can get the cookie so he will be happy and I say okay my answer is increased by one then I'll go on to my next child then I'll go on to the next person from the like from the person who is not has like from the cookies which are not yet taken I'll take the next cookie which is possible so with this maybe I can work out because I just wanted my childr to get cookies so I'm just concerned about that only will this work maybe not let's see uh with a simple example that for this child two of a gred two he will firstly go to four yeah four is a cookie of big size so what he will do is child two will take the four cookie okay answer is increased by one then you will go on to the next child four greed then he only has a remaining cookie of size three which he cannot take okay that is not taken so it will just move on then okay my all the children's are ended and all the cookies are also ended so answer you will return is as a one is one the answer no why because the best optimal solution would have been that if you had assigned the child two with a greed of three and a child four with a greed of four because that can be a sign so answer would have been two and we want to maximize the output so one thing we got to know yeah we can assign the children's we can assign all that stuff but before that it is very good that the child having the smaller greed should be assign a smaller cookie size we try the child for the smaller greed should be assigned a smaller cookie size and the child with a bigger greed should be remaining with a bigger greed bigger cookie size so what I did was I plan okay for a small child which means a child having a smaller greed I will try to assign him with the smaller of this cookie size value why is that the case so that in future going forward whosoever child is remaining for sure the child with a bigger greed will be remaining he should be availing OB basically he should be having an option to Avail the bigger cookie size so I will simply sort my children's for the greed values I will sort my cookies with their sizes and then I can try assigning I'll try assign my child two with the like child two having a grade of two uh with the cookie of three which is possible then I'll try to assign my four with this four which means a child with a greed four with a cookie of four and that's how when you're G of I let's say here's the I pointer here's the J pointer and for sure uh why we have using pointers because we want to assign one cookie to one person so as this is assigned my pointer should move ahead and try for the next combination that's it so it's the reason if we have I and J as is it so we can just assign it else we'll just move on now move on for a what let's say move on for what let's say if this would not have been the case if this would have been a one so what you could have done is will you still move your I still move your J no you will still only move your J why because for sure you'll see I want to maximize the number of children and cookie combination that's it I'm not saying I should be getting the maximum combination having the maximum greed value it's not required I just wanted to maximize the number of combinations so a smaller grid value higher cookie number will still form a combination which I mean by that is if this specific four and this four is forming a combination then a smaller value of G of I which means a smaller value of G of I let's say I Dash is this and this is I a smaller value of G of I will always form or basically always at least if this is forming combination then this will always form a combination and we want to maximize number of combinations so what I'll do is I will try for this specific I to combine with the next J so if I cannot form a combination I will just simply move my J and not my ey okay cool uh let's see the example statement self uh simply try running a few example and then lastly will see our own example which we will make S to cover all the cases so here you will see that I firstly sorted my s n although it's already sorted so you might not notice that but yeah we firstly have to sort it and then start comparing small values of greed to a small cookie sizes now it is I it is J yeah it's less it's valid okay move both I and J move both I and j i is moved and my J is moved again so when I and J are moved you will see that greed size is two but cookie size is one that is not valid so simply in this case you will only move your J you will try for a more cookie size for the small child you not move your eye because for sure as my this cookie size is sorted so incoming will be a bigger size so I'll simply move my J oh moving my J reach to my end oh as soon as you reach to end which is meaning that okay I have no cook at all simply end answer is just a one if I go to the next example in the question itself uh it says inj again it's valid okay increase the answer by one now in again it's valid both increase answer by one again as soon as both simply increase both of them I has reached the end which means all the children itself are finished okay no more children simply end answer is two now for the custom example which we have made again to just to show you all the above cases which we have seen firstly it is not required that they are sorted so firstly we will simply sort them down so as to assign smaller G value children with a smaller cook size now when this portion is done I'll start assigning I'll have my J I'll simply start off okay this s of I if this is less than equal to my S of J oh it is not okay that's completely fine is just that simply move your J why not I have already covered that is just that I want maximum number of combination obviously maximum number of children to cookie pair and lesser the grid value and more the cookie like lesser the G lesser the grid value it is more chances to make him as a pair so I simply move my J uh forward and my I is still here itself okay great uh now B what if I would have moved my uh I also I'll show you what would have happened but yeah meanwhile let's see that you moved your J only so I is two which means the GRE greed value is two cookie size is three so for sure I can take it which means G of I is less than equal to my S ofj I can take it and when I say I'll take it here you saw when I cannot take it I simply increase my J only when I take it I'll first increase my answer I'll increase my I also because that specific child is taken and for sure cook is I'm always going on in the forward Direction now my I is here my J is also here this is also a valid pair which I can take same operation I will apply in this also answer as has been increased to two and then it has reached to I uh this has reached to n no possible thing because cookies has ended so I'll simply it's the end of the answer which means any of I or J's reaches to the end I can simply return now byya what if I would have taken uh I would have moved my I also okay so you if you would have moved your eye also which means your I would have here now it is three yeah it's valid then if it's valid you will move your I and J again now8 and it's not valid okay if it's not valid you will simply move your ing again so you saw answer would have been one but answer could have been two if I had made this pair and this pair answer would have been to that's the reason if it's not valid simply move your J not I because I want the grid value to be as minimum so that I can pair him with some of the cookie size cool now code is as simple as that firstly I sorted both my children G value and the cookie sizes now when this is done this I is itself to point to my child which is the greed value which is G for my I and to point it to S which is the cookie sizes I have my J now I simply move on to all the cookie sizes because I know that at every iteration as you will see at every iteration J uh now my J was here so in every iteration my J is moving one forward Direction so I just used simple this Loop that my J is always moving which means in my cookie I'm always moving one step ahead so I just got this and then I'll just compare if my G of I is less than equal to my S of J then simply increase the answer and increase the I itself as you saw that g is all J the value J will always increase so I just took it inside the loop that okay it will always increase for the I value I know it will only increase when the S of sorry when the G of I is less than equal to my S of J and also just a quick condition that I should not get a runtime exception that I should be less than equal to G do size if that's the case simply increase the answer increase the I also and that's the entire for Loop which you need to have for this question and ultimately return the answer time again of n log n plus M log M because you're sorting both G and N sorry G and S array which you have and also space in C++ which you have and also space in C++ which you have and also space in C++ Java is log M plus log n because of the sorting and also in Python it will be o of M n because python uses more space cool that's pretty much thanks for bye-bye-bye
|
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 |
219 |
Hello students of this question offbeat special contested to Ghaghare Ghee I have to do that if two elements are named ok and their index is captured loot which will mean different index which will be the difference please keep in mind if it is of this year then we will do Will give return proof even after full refinement if nothing like this is received please turn the phone to us ok then initially what will you do 2 follow has gone wrong answer will not come after running 2 follow is ok because its time complexity will increase. And the difference tax is very much, okay, so here our excise is very big, okay, so what we will do now, we will declare a map here, okay, today I will be on your left side, our number will be its value and What will remain for us on the right side will be the index, okay, the name will be and once we do the request, Varsha is 11.2 question officer note size Varsha is 11.2 question officer note size Varsha is 11.2 question officer note size and that is I plus okay, now I do this, if we already have an element present in the map, the name of Clear it is cold ever present on this notice store and water and meaning if it is already present then what will we do file its brother will see the difference good people will see the difference i plus one - name of people will see the difference i plus one - name of people will see the difference i plus one - name of hi main tere lad sahayak hua toh hum hain karna Returning true voice mail is to be set i am e-mail time karna am of numbers of my am e-mail time karna am of numbers of my am e-mail time karna am of numbers of my request i plus vansh hai statement agar faltu aa kam kar denge hum of norms of is meaning if it is in the elemental map otherwise it will have to set the day na So that Qawwali and its induction have been done, it has been inserted, if it is not found after searching the whole thing, then we will return it for you can see the description of it, let's color it on this website, it is fine. Let's submit the product bar, it was very easy in the complete description that if you use it, then like it, share the video, subscribe the channel, thank you.
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
209 |
hello everyone welcome back Shiraz van amsen and today we will try to solve a code in Python number 209 uh minimum size sub array sum so this problem is a great way to practice array manipulation and the sliding window technique as well so let's get started here is the problem statement we are given an array of uh positive integer uh nums and positive integer Target and our task is to return the minimum length of the continuously soup RI a dose sum is greater than or equal to the targets so if there is no such sub array we just return uh zero so let's look at example to understand this battery if we have the input array of 2 3 1 2 4 3. and the target is seven the sub array for free has the minimal length and its sum is greater than or equal to the Target so uh four uh three so the sum equals to seven so output should be a two because it's the length of uh this uh sub array so now let's look at the possible python implementation uh we have a solution with a method minimum sub rln and this method takes in the Target and the anomalies as a parameter and what we can do we will use a sliding window so let's Implement and I will explain everything right away so if not Nam so return zero and minimum length will be initialized to float of infinity and left pointer will be zero and current sum will be zero as well and four write in range land of nums what we do is current sum plus num right so while current sum greater than Target minimum length equals minimum length and right minus left one so current thumb minus num off left and left plus one so return finally minimum length if minimum length not equal to Infinity else it will be zero so we haven't found anything so let's run it for a previously mentioned test case hopefully it will outfit too yeah everything works and now let's explain so we initialize free variable mean length to keep track of the minimum length of the sub array we have found so far left to keep track of the left boundary of the our sliding window and current sum to keep track of the sum of the elements in our current window and we then iterate over the nums list with a variable right representing the right boundary of the sliding window and we add the current number to current sum if current sum is greater than or equal to the Target we update minimum length and subtract the number at left boundary from current sum so then move the left boundary to the right and finally we return minimum length of the element we have found a valid Subaru otherwise we return 0 because we have found nothing so let's run this code for Anson test cases as well to verify everything work uh so it's running and hopefully yeah uh it beats 76 with runtime and also with respect to memory 11 percent so it's all good as you can see the code works perfectly and to return the expected result and this problem is a good example of how to use sliding window to solve array manipulation yesterday we have solved similar problem also with uh sliding windows so that's it for today episode I hope you found this problem interesting and uh solution helpful obviously it could be solved in other ways and don't forget to like share and subscribe for more coding problems in Python and tutorials uh keep coding and keep practicing happy coding see you next time
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
350 |
foreign foreign foreign welcome to my channel this is quantum unicorn the lead code problem we are solving this video is intersection of two arrays two well the intuition behind this solution is to use a hashmap AKA dictionary to efficiently track the count of elements in nums 1 and by maintaining a count of each element in nums one we can accurately determine the intersection with multiplicities when iterating over nums 2 let's break it down first we create an empty a hash map to store the accounts of elements then the code iterates over each element num in nums one and if num already exists in the hashmap increment is count by one using this syntax and if Nam does not exist in the hash map then add it to the hashmap with an initial count of one after finishing the first Loop it iterates over the over each element num in nums 2 then check if num exists in the hash map and its count is non-zero the hash map and its count is non-zero the hash map and its count is non-zero if the above conditions are satisfied it means num is a common element between nums 1 and nums two then append num to the result list and decrement is count in the hash map by what finally we turn the results list which contains the elements that appear in both nums 1 and nums 2 with the correct multiplicities so in summary the intuition behind using a harsh map in the solution is that it allows efficient lookups and updates which are crucial for determining the intersection with multiplicities by storing the counts of elements in nums 1 we can accurately determine if an element in namsu is a common element and ensure that its count is correctly accounted for the approach of the solution can be broken down into four steps step one count the occurrences of each element in nums 1 using a hash map and step two Traverse nums 2 and check if each element exists in hashmap and has a non-zero commed step 3 if a common non-zero commed step 3 if a common non-zero commed step 3 if a common element is found add it to the result list and decrement is account a document is count in hashmap Step 4 return the result list containing the intersection of the two arrays at this approach efficiently handles cases with duplicate elements and ensures that the intersection includes elements with the correct multiplicities by leveraging a hashmap to track the counts we can accurately determine the common elements between the two arrays and their respective multiplicities with that set now I'm going to give you a breakdown of the code and key learnings which will help you understand the app which will help you better understand the approach well color is one understanding dictionaries which is hashmaps the hash map in is the dictionary that stores the counts of elements from nums one additionally is a data structure that Maps keys to values in this case the keys are the elements from nums one and the values as a counts of each element the hash maps are the hashmap.getkey default method is the hashmap.getkey default method is the hashmap.getkey default method is used to retrieve the value associated with a given key if the key is not present in the dictionary it Returns the default value in this case I right and two counting elements in nums one the first Loop iterates over each element num in num's one and this line of code updates the count of num in the hashmap dictionary if num is already a key in hashmap hash map noun retrieves the current count and increments it by one and if now is not present in hashmap dot get num zero returns 0 as the default comes and then one is added to it three I'm finding intersection in numbers two the second Loop iterates over each element num in nums two the nine um if none in hashmap and hash map num um not equal to zero and checks if num exists as a key in hashmap and its count is non-zero if num is present in hashmap is non-zero if num is present in hashmap is non-zero if num is present in hashmap and its count is non-zero it means num and its count is non-zero it means num and its count is non-zero it means num is a common element between nums 1 and nouns 2 and if the condition is satisfied num is appended to the result list indicating its presence in the intersection additionally the count of num in hashmap is decrement by one to account for it's uh occurrence in the intersection right and four returning the intersection the result list contains the elements that appear in both nums 1 and num2 with the correct multiplicities after iterating over all elements in nums two the result list is returned as the final intersection so we can say the algorithm behind the solution is that first create a hashmap to store the cons of elements in nums1 and then Traverse nums one and update that comes in the hashmap then Traverse nums 2 and check if each element exists in a hash map with a non-zero count if a common map with a non-zero count if a common map with a non-zero count if a common element is found appended to the append it to the result list and the document its count in hashmap finally we turn the result list which represents the intersection of the two arrays the time complexity of the solution is O of n plus M where n and M are the length of nums 1 and nums 2 respectively why is that because the first Loop which iterates over nums 1 to create the hash map has a Time complexity of O of M where m is the length of lambs 1 the second Loop which iterates over nums 2 and performs lookups in the hashmap has a Time complexity of O of M where m is the length of lambs 2. since we consider both Loops sequentially the overall time complexity is O of M plus M okay and regarding space complexity it has a space complexity of all of um minimum of M or n where n and n are the length of lambs 1 and lens true respectively because the hashmap dictionaries towards the counts of elements from nums 1 the space required by the hashmap depends on the number of unique elements in nums1 in the worst case if all elements are unique the space complexity would be all of minimum M or M and also the result list stores the intersecting elements and its space complexity depends on the number of common elements between num1 nums 1 and nums two in the worst case if all elements are common the space complexity would be o of minimum of n or M therefore the overall space complexity of solution is O of minimum of n or M okay all right well by understanding the use of the dictionaries which is Harsh maps and the logic of counting elements and finding the intersection you will gain a solid foundation for approaching similar problems and understanding more complex algorithms all right that's all for today I hope this was helpful if you have any questions please leave a comment and also please subscribe to my channel like the video and click the Bell icon on to receive the latest updates happy coding and thanks for watching goodbye thank you
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
203 |
hello guys I'm this video we see problem link list elements so given head of the link list and integer value remove all the nodes of the link list that such that the node value is equal to the given integer value and return the new head so what the question is given in a link list and they have given some value if any node in the node value in the link list is equal to given value just delete that remove that from the link list and return a link list without those values no values in which is present so if you see the given value is six here so if you delete a note with 6 six the link remaining will be 1 2 3 4 5 this is what we need to return if it's empty and the value is one no one is not present so we'll return the link list as such if you see the last example s so all the are so remove all of them which will which need toty list we have to so this is a question so normal thing what we can do so what we do is we will create node before to this let's say We'll create a dummy node and that dumy node be zero and let that dummy next point to head so we'll create a list node D equal to new node initialize it to zero and dumy do next equal to nothing but head so we created a dumo initialize it to zero and the Dum do next whatever you have let that point to head this so this is the head of the name list and this is D okay now we have two pointers current pointing to head and previous pointing to Domino okay so now start Ting in the link find the null pointer so check whether the value at the current position node value current position is it equal to Target let's say Target value here value given is 3 so is the node value 2 is equal to 3 no if that is not equal to 3 we have to move the current point to next but before moving current pointer to next if you move the current pointer to next value then previous will be this two so what we do is at first re initialize previous current equal to current value so this will become revious now current will be equal to current next so current will here so you do previous equal to current and current will be equal to current dot next why I'm performing previous equal to current because current is moving next means the node before to this will be previous so that's why initialize first previous will be equal to current now current will move to current whether the given value at this position is equal to the value which we need to remove yes three is equ to this so if you want to remove this that means the link from here it should move to four this is what we need to do so we have to break this link and put the link from the two to four here instead of like three so how do we do that so for doing that what we do we have previous point to here current Point here so as you can see previous do next no this is nothing but previous do next so previous do next it should point to where current next this is previous so this previous do next should point to current do next that means this no so previous next will be current do next okay and then once you move the previous next current next you have to reinitialize previous and current now so in this case current will be what this next current will be this because you'll be getting zero then two and four so current will Point here previous will Point here so previous is it at that position yes previous in the correct position it's pointing to two but current should be pointing to four how do we get that so current will be equal to delete the current first delete the current value whatever you have so current will be equal to but this previous whatever it is pointed to previous do nextt so current equal to previous you can say initially we can do the current equal to current next if we find no if you do that we will lose track of this value now three which we need to remove that's why what we do is first initialize previous next to current next so it's point to next number skipping the three now initialized current will be equal to the previous next that means four so current is pointing here prev is pointing here okay so now we have 0 to 4 we have this is what it is form apparently we remove three I can check whether 4 is equal to 3 no so previous should be point to First current now and current will be current again this is equal to three 3 is equal to 3 here so you have to move the pointer from four to five instead of three so what we do previous do next the next Val that will point to current next this number delete current now current will get deleted now current will be equal to what previous next that is this value so this will be correct okay now again Che 5 is equal to 3 no so again previous will become current and current will be current we just wanted n pointer on the loop so this is how we solve the problem so let's implement the logic at first we need to create a list node let's say dumy equal to new node initialize it with zero so next what we need to do so dumy is us so dummy. next first okay dummy. next so dot next do we use in Java here we have to use arer so D next will be equal to nothing but head value and then so it should be list now yeah the previous and current we to initial so list know previous will be equal to Dy and list node current will be equal to head so while current not equal to not pointing to null pointer here so if it is not to until beine so if in case wherever the current is pointing to current do Val is equal to well then what we need to do so first previous will be equal to current okay if it is equal we have to remove that now so for removing that what we do previous do next will be equal to current next so prev next will be equal to current next you delete the current so we can delete current now current will be equal to previous nextt okay because previous next is pointing here okay but that's okay instead of deleting you can directly give current equal to current. next that will automatically means you just skipping the element so because previous do next is pointing to have a current next so current will be equal to current next only so that's also works else what if it is not equal to l then previous will be pointing to current and current will be equal to current next yeah so once you're done with this but how do we return the answer we have to return head we can return head as you can see we have dumy note here right so what should be done so we have to return dumy do next before that we have to create a new head that be pointing to dummy. next and WR new head so list no star go head equal to Dy do next so now return the new head here also so and why is it showing okay reference have not yeah so we shall run this now yeah and Java also same logic applies you create a list node here you need not to give Aster here directly we can do if it is not equal to n until you have to there you have wrate if it is equal to Val what condition else other condition so return dy. next that also works directly you need not to return a new head because dy. next will be pointing to this head on so you can directly return I just created a list node of new head and returned it so we will submit this yes successfully submitted if you understood the concept please do like the but subscribe to the channel we'll come with another video in the next session until then keep learning thank you
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
1,465 |
okay we solved the code question in 1465 maximum area of a piece of cake after horizontal and vertical cuts this question came from weekly contest 191 I pause the video if you want to take a look otherwise I'm gonna continue with the approach so let's start from example 1 so the way to do this is by getting the inter getting the intervals of your cuts after sorting them so you can see after you saw your horizontal cuts you get 1 2 4 it's already sorted but in case it's not you need to sort them with your maximum cut at 5 you saw your vertical cuts with your maximum went at 4 so your maximum vertical cut is 4 and you can see that the interval for horizontal intervals is 1 2 4 is 2 and 4 to the maximum possible cut which is at the end is 1 and likewise for the vertical cuts as you get 1 because that's like 1 0 2 1 2 3 that's 2 and then 3 to 4 no that's 1 it's actually 1 my bed and we need to keep track on the maximum horizontal interval which is 2 and maximum vertical interval which is two and we can do this in a one space and at the end we just take the maximums and multiply them to get the max area alright let's begin so first as we discussed we want to sort so next we actually wanted after it's sorted we actually want to check to see if the last cut is less than the maximum possible cut given by H and W respectively and if it is less than those values we just append them to the sword cuts next we want to start finding out what our maximum intervals are now we want to handle the case where if the index is greater than zero we need to subtract the this interval from the I minus 1 value to get the actual interval now we need to check if your goal is greater than max then just set and we're gonna distantly similar for the vertical cuts and at the end we as we just return the product of the maximum intervals and so the problem does mention since the answer can be a huge number returned this modulo 10 to the 9th plus 7 alright let's test accepted all right let's submit and try hmm all right so you success I think that we made a little typo on there it's supposed to be asterisk for power not the caret symbol anyways I hope this helps see you next time
|
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
|
maximum-product-of-splitted-binary-tree
|
You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where:
* `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and
* `verticalCuts[j]` is the distance from the left of the rectangular cake to the `jth` vertical cut.
Return _the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays_ `horizontalCuts` _and_ `verticalCuts`. Since the answer can be a large number, return this **modulo** `109 + 7`.
**Example 1:**
**Input:** h = 5, w = 4, horizontalCuts = \[1,2,4\], verticalCuts = \[1,3\]
**Output:** 4
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
**Example 2:**
**Input:** h = 5, w = 4, horizontalCuts = \[3,1\], verticalCuts = \[1\]
**Output:** 6
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
**Example 3:**
**Input:** h = 5, w = 4, horizontalCuts = \[3\], verticalCuts = \[3\]
**Output:** 9
**Constraints:**
* `2 <= h, w <= 109`
* `1 <= horizontalCuts.length <= min(h - 1, 105)`
* `1 <= verticalCuts.length <= min(w - 1, 105)`
* `1 <= horizontalCuts[i] < h`
* `1 <= verticalCuts[i] < w`
* All the elements in `horizontalCuts` are distinct.
* All the elements in `verticalCuts` are distinct.
|
If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2175
|
32 |
hey everybody this is larry this is day uh 24 yeah of the may lego daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem longest valid parentheses hard okay so give it a string contain just a character find the length of the longest routed parenthesis sub string okay um yeah i mean i think there is for this particular problem it is just about formulating another um set of logical things to test for um and really uh it's i wouldn't necessarily call it a case analysis as i usually would but you can kind of maybe do a proof by um like proof by exhaustion is that the word no i don't know if that's the phrase but basically you prove by going for every possibility right so they're really only um and some of this will just require or at least you know uh has a lot of practice with similar problems right um and what this means is that um first is you try to figure out what is a valid parentheses right um so i mean that may be as obvious in that you know in order to find the longest one you have to first have valid ones so then the idea here is let's see right anything about this um well like how do i express this i'm trying to think right now how to kind of prove to be honest um but because the idea is kind of okay but i think the idea that i would have is just by um using a stack to calculate um to calculate like basically how um like how things match up i suppose maybe that's one way to put it and what i mean by that is that let's say you so there were only two cases or two weird cases maybe with your will because i guess the dirt case is just you know everything match up and it's okay and you know there's some like you know uh and you know that's everything matched up and that's easy right or at least you know the longest isn't the entire thing and then the other thing is basically there are two cases one is basically example case one where you have some uh something that got matched up uh but not all of it right so then now but let's say you end here that means that you're trying to figure out how far to go to um you know how many characters you have left and that number of count doesn't mean that's the number of unmatched things and then of course the unmatch goes the other way as well which is basically uh in example two where you know i mean maybe you have something like this but you may also have something like that and then now this can the rest of it could be really long for example but everything to the left of it is uh you know not the longest or it's not a possible routed one and then of course from here there like from this idea of this disconnection um you know it does it doesn't have to be just a lot last part it could be somewhere in the middle as well right so then you have to take the longest component of all these components um so i think that's basically the idea you know i don't think i said it very well to be honest but the core part of this idea is you know using a stack and part of using a stack is greedy and then figure out all the invariants of this problem so let's get started let's play around with it um yeah so okay so as we said with stack uh let's say we have best as you go to zero say so i think one observation to maybe notice is that um as part of the writed parentheses the character has to be to close parentheses right i'm trying to figure how to use that in a good way the edge case being that if i have something like this um even though this right parentheses would match this one the longest rounded parenthesis is actually up to here right so we have to figure out how to kind of you know be just be careful about it but uh okay then for c is you're gonna ask if c is uh i'm trying to think and one thing that i may be doing is um and i'm not i'm trying to think over right now is whether i am prematurely optimizing because definitely you know there's a stack and you can put some stuff in it but for the most part no you only have two things and on the right one you always pop anyway so maybe you'll represent the stack using a number um and then maybe but maybe that's a premature optimization so let's ignore that for now so anyway so we have these two cases one is this and one is this right um what do we do if it's this then we push it to the stack which is fine let's see i think you can keep track of a few things all right let me give it a try um i'm trying to prove in my head that this is okay but maybe this is a little bit weird but yeah but uh let's say depth is equal to zero and then maybe the current one is equal to 0 right and then what we can do is now um is so weird given what auto uh completing for me anyway so here then we increase that by one right and here we go okay if depth is greater than zero then we can match them um and that means that if we match then our current one increases by two right because now we add two to the longest step um and a lot of what i was doing to be honest if you see me pausing it's just me thinking for these cases before writing them to be frank um so i don't know that's a great thing but um else if that is zero that means that if dep is equal to zero then that means that this one um chops it off so curtain one is equal to zero because now you have to start over on the next one um and also and then here that minus one otherwise this is good right and of course this is the only case where um we can improve best so we just do best here okay i don't think i did a great job illustrating how i thought through this uh but i also don't know if this is correct to be honest so let's see um because i think what i don't i cannot or did not show anyway is that how i come up with this is just really going through all the possible cases in my head um and they're only really a couple of cases like i said like there's this case where you have extra one and then you have this case where um you know you cut it off and so forth so you know so then now we may let's uh try more cases say i don't know to be honest right now i'm not 100 confident in this one but i think i'm okay in giving a try so let's give it some apparently i've got it wrong oh no i got it one four times before uh okay uh like i said i uh this is why i wasn't confident about it is because now there's a lot of silly things apparently the first time i tried four wrong ends or three wrong answers and last time i got it right on the first try but this time uh this year i am a little bit worse than last time so let's you know put this in here um okay so this is wrong because now um that is tricky isn't it huh how do i handle this case was basically two is going to be the longest one which is either here or here but i'm also trying to do an over one space which is maybe why uh you know i'm a little bit silly today uh i think if i did it with stack this is probably okay so let's maybe just do it with a stack um then we can kind of you know keep track of the states and then we can do the if statements a little bit more intuitively right so okay let's but i think this is just going through all the cases i don't think there's anything conceptually impossible per se but yeah maybe something like that and then what does that look like now um okay so if length of stack is greater than zero yeah and again i'm doing the thing where i'm just drinking food a lot um okay if this is greater than zero that's good otherwise uh well we just start this over so what do we want to keep track of man i'm a little bit off today well if this is matching a zero what does that mean that means that we want to find the last unmatched parentheses right and the last unmatched parenthesis it's going to be the thing that's on top of the stack or it goes all the way to the left which is fine right um but then the other thing that we have to keep track of is that the last break right because there's two cases where is this and if we have to be mixed and i kind of focus on this one on my test cases back for i don't know why i didn't keep track of this one i should have tested it i mean i uh yeah um okay so man that means that the top of the stack is the last known thing um so okay maybe we just have to keep track of the uh and this feels a little yucky but if it works then maybe that's okay right uh last um yeah last is you go to none right say otherwise this means that last is equal to i meaning that this is the last good thing um so then otherwise we keep track of um so the current one is you go to well first we pop and then the one that before that is the one that um so here now after we pop if length of stack is equal to zero then we use last so actually let's use slices zero maybe yeah um so just then one is you go to i minus last else one is equal to i minus stack of negative one and then out best is equal to max of less than one i feel like there's a lot of potential off by ones here so let's give it a spin for a quick second um hmm do i feel good about this one not really to be honest um and the reason is because i'm just feeling a little bit shaky about the off buy ones because um i'm i didn't in my mind i didn't define exactly clearly um the increasible exclusiveness and i think you're having this as the last thing is actually lucky and in a sense that um yeah actually let's make this negative one and then now last is you go to i as in this is the one that you don't include and then is this plus one and this plus one i think this maybe is a little bit more precise um we'll see if that's true nope uh oh because i also includes itself so maybe that's why but yeah as you can see changing discipline he didn't change my inputs so i don't know that works but so my test cases are weak is what i mean so that's why i was sketchy about it and i think the case that mine doesn't have is just something like this okay and that looks good um so let's give it a quick submit again a little bit yolo okay so this one's a little bit better 784 day streak a little bit embarrassed to be honest linear time linear space operator it makes sense why um let's see what past larry did because i'm curious um but i can do an all one space as well um don't know i don't have an immediate answer to that one uh let's see what i did last year uh okay last year apparently i did what i did this time i wonder how i came up with that one because i actually missed maybe i just tested that case and then that it didn't work because i just forgot about because if i tested this case or this one rather i would have figured it out but i just it's a little bit um sometimes you missed it on here as well uh what did i do the first time oh i did the same thing with no that's not true but up to the depth i just see the last time this is a very funky thing i'm doing i don't know i try to fix it still try to fix it i guess that's way funky but i in the end i did it the same way i suppose um but in a more weird way okay i mean um yeah i mean i think that's all i have for this one let me know what you think um yeah i don't know uh yeah that's what i have stay good stay healthy to get mental health i'll see you later and take care bye
|
Longest Valid Parentheses
|
longest-valid-parentheses
|
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_.
**Example 1:**
**Input:** s = "(() "
**Output:** 2
**Explanation:** The longest valid parentheses substring is "() ".
**Example 2:**
**Input:** s = ")()()) "
**Output:** 4
**Explanation:** The longest valid parentheses substring is "()() ".
**Example 3:**
**Input:** s = " "
**Output:** 0
**Constraints:**
* `0 <= s.length <= 3 * 104`
* `s[i]` is `'('`, or `')'`.
| null |
String,Dynamic Programming,Stack
|
Hard
|
20
|
152 |
right so today we are going to talk about nickel question 152 maximum product summary the question says given an integer very news fire continuous non-anti sub array news fire continuous non-anti sub array news fire continuous non-anti sub array within the array that has the largest product and return the product the test case are generated so that the answer will fit in the 32 integer into in a 32-bit integer a sub array is a in a 32-bit integer a sub array is a in a 32-bit integer a sub array is a continuous subsequence of the array so the first example we have two three negative two and four to three will gives us the largest products in among of the summer rates and um the second example we have negative two zero negative one and the result is zero so um how we are going to approach this problem we need to consider two situations one is when our current product is zero that means zero times any of the number to give as a zero and another situation is a negative number so if the previous product is a negative number times the negative number will give us a larger number but if our negative number times or positive number will give us our negative number which will be smaller so I'm going to so that's been said we need to use we need to record our current products for every single step we are moving forward and you also need to record minimum products better moving forward so I'm going to show you an example which is the someone that we have right here is negative oh it's two three negative two four so I'm going to use max or not Max uh current um I'm going to just use max make it easier and I'm going to use Min and now our result so when we are here our number other thing will stop is the value of the first number in the red true and here is two now when we are here we need to use our previous Max times this number and our minimum number times this number and then compare this three number and take the maximum one so we have two times three get six two times three we get six so six Compares six and three so six is the largest now then here the how we get the minimum for the current index so we are used our previous Max which is this one times three in our who is minimum times three and then compare so if it's that true number we got and uh so 2 times 36 6 2 6 and 1 3 the 3 is more then we take um let me take our current maximum but our previous maximum and take the largest one which is six then we have two here negative two here so we use our previous Max and proves mean times this negative two so six times negative 2 we can negative twelve three times negative two we get negative six and negative 12 and negative two negative 2 is the largest so we take negative two then for the smallest number we have uh six times negative 2 we get negative 12 and 3 times negative 2 we get negative six and negative two so negative 12 is the largest uh no mega trophies to smallest then we compare with negative two and six we take six then here we have our 4 times negative two and four times negative 12. we get Negative A and negative 48 and 4 so 4 is the largest and we have uh we use previous Max negative two times four negative a so negative 48 will give us the smallest and um we have six compared with four we take six so at the end our output will be six now let's go to the calling first we need to vary three variables so current Max call uh the first number in the array and current events called the first number in the rate then we have um our output we call also it goes to the first number so when we check verse to the alright we are starting index of one to the end of so then we need to remember since we need to use the previous Max when we buy the current name so we need to um somehow store it in case it got updated for the in the current Max so previous Max equal current Max and then uh current next or Max of uh first come here with current number and we use current Max times current number and we use a current Main times tons of current number then we find the current Main comment of a current number and um so permanent as news right and we use previous Max and right remembered me so I'll put so equal to maximum of current Max long words the previous output and at the end we'll return assignments so let's run it yeah six the first one this one oh it don't let me copy good yeah so it looks all good so um so in terms of the time complexity for this problem we only Traverse to the array one times so it takes a bit of n for time capacity for the space complexity we use three variable to stores three variable to store the current Max chromine and outputs so the space complexity is roughly below of one yeah so that's this question thank you so much
|
Maximum Product Subarray
|
maximum-product-subarray
|
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.
**Example 2:**
**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Dynamic Programming
|
Medium
|
53,198,238,628,713
|
558 |
hey everybody this is Larry is November 15 and this is me trying to do an extra apartment I'm gonna try to do a medium today just because I am trying to do a little bit better about sleeping already I don't know if that's true that's why I have these uh nerdy looking blue glasses let me know how you feel about them uh Diane says I hope these are kind of cheap it'll be okay um I do want it a few times because I don't have premium but anyway today's prime is 558 logical or of two binary grid represented as quad trees that's kind of funky let me get my soda real quick uh quiet trees are kind of record like part three is a thing that I haven't done in a long time but you can think about um and this is off my head so I could be really wrong because I don't think that I've I mean I get the concept I remember the concept A little bit but I haven't touched them in maybe 10 15 years maybe longer um so I don't know we'll see if that knowledge is necessary okay let's focus okay uh a binary Matrix is a matrix in which all elements are zero and one given quite trees one and two you have an N by n binomial Matrix okay two of these return a question about logical bit wise or of the binary what does what uh hey yeah that's what I was gonna say so well hmm I guess it depends on how um I think that maybe I'm also confusing definitions as well to be honest because I think the variations of because there's also hmm maybe I'm thinking okay well there's KD trees as well because I think there's one where it's not a perfect quad it's um you could it's a variable thing and then you kind of rebalance depending on where things are instead of like a perfect half and then perfect quarter and so forth but maybe that's not important the important part is that it's uh for me anyway it's kind of like a tree and that is a recursive structure and in each and it's really just like a four in every tree it's like a quaternary tree whatever right so it's just a tree with four nodes and that's pretty much it um okay I see what are we supposed to return okay so basically I see are we supposed to return a quite true of The Matrix okay you have to return a quad tree that's a little bit more annoying hmm okay I guess that doesn't matter okay fine um okay so that's kind of I mean the way that I would think about this initially is and stuffing about a quad tree think about binary tree right what would I do if it's a binary tree in the same structure you have a one-dimensional structure you have a one-dimensional structure you have a one-dimensional plane um you have you know left goes left or zero goes left one goes right and then you have this like intersection of them right what would you do well you would just kind of um recursively call them so I think that's basically what we would do and this is an or okay um so we'll just do it step by step and then try to see how things um kind of go um I think the one thing that I have to try to think is very we have to minimize it what I mean by that is if for example here do I have to minimize it hmm maybe I do maybe I don't I guess it doesn't really matter it shouldn't be that hard so okay so let's kind of go let's have a recurse we have a node one no two this is just no the two trees and then now we just have to break it down right so this is just honestly not super interesting but you have to be super careful I think that's the tricky part about this one and yeah okay so if self dot is uh if node one dot is leaf the um yeah I had to do other cases that's what I'm trying to think about right so basically if and we could write it a little bit right so we then we return a new node uh or yeah new note where the value is no one dot value or node two dot value um its leave is going to be true it's still a leaf and then zeros for the rest I think I don't know how this initialization work it should be none but maybe that's fine right okay so this one should be easy right if they're both nodes uh okay then if the both not Leafs then we just have to do a recursion on it right so we can do something like uh and I know that I'm doing the Yeezy ones first but that's okay and the value doesn't matter so switch zero they're both not um foreign so technically this would be Force but we have to actually think about this right so I'll talk about what I mean in a second um so then now we recurse node one dot top left node two dot top left oh this should be zero then right this is none because these are the nodes not zero one zero they should mention these a little bit the definition is a little awkward here okay so yeah then oops no two of course um and then top right oops that's one um okay so we have this node right the reason why I instead of returning it immediately is because we want to propagate it up right so yeah if we die top left is leave and okay also if node one is none then we return node two right I think I missed some cases here um base case um well we want to be okay well uh if no two is none then we return none otherwise we return technically you could return no two but maybe that's just not good hygiene so top left know that way no to that bottom left no two dot bottom right something like that right that's a little bit awkward yeah um and then if no two is none then we return the same thing but for node one right and this of course assumes that node one is not none because we checked for it earlier okay ah maybe I shouldn't have done an extra plan I'm tired okay wow a lot of negative downloads or whatever anyways so yeah so if they all is leave um and the value is the same explode the order of operation here so that's why I'm doing this but when in doubt okay then we actually won V to advise then we want to set the leaf is to go to true and then we want to set we um maybe we could just set V as you go to a new node maybe that's easier to type uh then this is if they're all leaves and they're all the same then we can yeah the value uh it is a leaf and then just nuns right because now we get rid of the leaf okay that's a mouthful but and then basically now we have to do the other case of which is very annoying if no um thank you okay fine if notice leave and no two is not leaf then what happens right um Dan what we want to do I guess is the reason I'm gonna do it is a little bit weird maybe we'll see if this works but basically what I'm going to do is do a recursion and then just create split this up into four in a way so we curse the value doesn't matter because we need to leave uh oh I'll have to do this thing okay so we should I should put this into a helper function um let's do that hmm maybe merch I know I had to do a lot of fixing this is not a hard problem but it is a grinder and just going through the cases I'm a little bit tired I woke up very early today actually I'm very proud of myself but I think I underestimated uh you know as a result um so yeah so then now we can just return maybe merch of this man and then now um yeah now we could do this recursion but maybe merge and basically what I'm gonna do is um let's see right so is this a leaf I guess not because of the node one and if it is then we can merge anyway we want to recurse what do we want to recurse right so we can actually we curse node one again in a weird way I don't know if this is true to be honest but the reason is because if you think about or the way that I think about it and maybe I should just use a sent to no instead but the way that I think about it if no one is it's a leaf whatever value it has you can almost think about it as recursively going down to all the other values and this is just me being lazy because I think that is maybe a kind of a dubious code and logic but I'm sticking to it so yeah uh top right bottom left bottom right and then lastly the other one is just no one is not a leaf and no two is a leave right so yeah so we're gonna do the same idea the order doesn't actually matter so it is easier to keep track um and that's pretty much it so now we want to we curse um what is it what do they call it tree one or something quad tree one I don't know if this works because I don't know that um this is good but let's give it a spin it may tear you because I don't know that I missed a case or not um okay oh what am I doing um oh so the left note it's going to what am I doing here huh that is weird I use the weird syntax but basically I want something like this okay I messed up so we want to say the left note is going to be oh no this is right I just kind of did I don't know if I have a recursion here actually that's too I meant to have a note I mean this is right because now you're creating a new node okay fine that was just me maybe I just got confused because there's a lot of stuff to type in a mode old and tired I need you know my beauty sleep okay that looks okay for these two cases that doesn't mean anything but I am lazy so I am gonna it's good enough for me to submit and let's see what wrong answers oh there you go good try on the first try I kind of did a lot of hacks on this one to be honest so I don't know that I recommend it but this is linear in the size of the input and that you know we only look at every um every node once so this should be good um did a lot of edge cases so I think like I said from the beginning the tricky part is being clean and making sure that you know you go for the cases like I knew there are four cases here um and then I also knew that the four cases here just because that's how two to the two Works um and luckily um I did a maybe merge thing so I don't know if this is necessary per se but it definitely helps I guess they didn't did they have an example I don't know that they have an example with this well at least I didn't know if you have to minimize it but yeah this is gonna be linear time linear space and that's all I have for this one so let me know what you think um yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Logical OR of Two Binary Grids Represented as Quad-Trees
|
logical-or-of-two-binary-grids-represented-as-quad-trees
|
A Binary Matrix is a matrix in which all the elements are either **0** or **1**.
Given `quadTree1` and `quadTree2`. `quadTree1` represents a `n * n` binary matrix and `quadTree2` represents another `n * n` binary matrix.
Return _a Quad-Tree_ representing the `n * n` binary matrix which is the result of **logical bitwise OR** of the two binary matrixes represented by `quadTree1` and `quadTree2`.
Notice that you can assign the value of a node to **True** or **False** when `isLeaf` is **False**, and both are **accepted** in the answer.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
* `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's.
* `isLeaf`: True if the node is leaf node on the tree or False if the node has the four children.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
}
We can construct a Quad-Tree from a two-dimensional area using the following steps:
1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop.
2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo.
3. Recurse for each of the children with the proper sub-grid.
If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree).
**Quad-Tree format:**
The input/output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`.
If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**.
**Example 1:**
**Input:** quadTree1 = \[\[0,1\],\[1,1\],\[1,1\],\[1,0\],\[1,0\]\]
, quadTree2 = \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\]
**Output:** \[\[0,0\],\[1,1\],\[1,1\],\[1,1\],\[1,0\]\]
**Explanation:** quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.
If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.
Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.
**Example 2:**
**Input:** quadTree1 = \[\[1,0\]\], quadTree2 = \[\[1,0\]\]
**Output:** \[\[1,0\]\]
**Explanation:** Each tree represents a binary matrix of size 1\*1. Each matrix contains only zero.
The resulting matrix is of size 1\*1 with also zero.
**Constraints:**
* `quadTree1` and `quadTree2` are both **valid** Quad-Trees each representing a `n * n` grid.
* `n == 2x` where `0 <= x <= 9`.
| null | null |
Medium
| null |
119 |
design an algorithm to return the cave row index of a Pascal's triangle using only okay extra space how do you do that's about today's video that's I mean Cavani this is where my dream started what's up everybody this is Steve here today we're going through a very classic interview question not only interview but I'm suggesting general programming in very classic question which is Pascal's triangle this is labeled as two is there's another one Pascal's triangle one which is even easier but this one is very classic and the most ie I went to discuss ball and I found the most challenging part is how do people how to implement an algorithm how to optimize your algorithm that you used okay extra space that's the most challenging or confusing part ok let's start from the very beginning what is a Pascal's triangle here is a very interactive diagram to help have some to understand what is it Pascal's triangle so it's looking like this given an active and the question is asking us given an active in non active index K where K is smaller than or equal to 33 this is a constraint which simplifies the problem retain the case index row of the Pascal's triangle this is the definition or illustration of the Pascal's triangle see the row index starts from zero see this one is 1 and the second row is coming from the sum of it's to use is coming from the two elements that are right above it this one is 1 because it has only one element above it so it's coming from one this one is above one then the only one above it is 1 so but standing from this row say this one has only one above it so it's still 1 but this one has two elements above it so it's two because of its because it comes from the two elements that's those are directly above it so one plus one equals to two that's why this one is two the same case is equal is also true for this one three White's three it comes directly from the two elements 1 and 2 directly above it that's why 1 plus 2 equals 2 three that's why this one is a 3 here the same case applies to this one 3 because 2 plus 1 equals 3 and the same is also true for all of these 4 6 4 is because 1 plus 3 equals to 4 and here 3 plus 3 equals to 6 that's why this one is 6 so for example the API signature is like this row index we are passing saying the example the input is 3 where husband and the index front standing from 0 so 0 1 2 3 so that's why it's written in 1 3 1 less the result that's the result all right now we understand the question let's think about how we can solve this problem we'll just go with the very brute force solution first which is say what's that from let's draw something ok it's too small on the font let me change the phone to 14 is even smaller okay let's put some index here 0 1 2 comma I don't need that 3 4 is good enough so the this Pascal's triangle is going to be looking like it always starts from 1 and then the second one is 1 also 1 and 1 let's make it extract further easier you read and then this and row 2 which is the third row it's still 1 and this one becomes 2 because it's this one comes from the sum of the two elements that's right above it so this one is 2 and this one is 1 and for Row 3 and index 3 this one is still 1 but this one is 3 right because it's coming from these 2 right above it the same is true for this case and this 1 is still 1 all right I think that's good enough we don't need a fifth of row okay now we can think about how we can implement this as I said well just go with the very brute force solution first at least we can get it accepted and then we can see to go through the follow-up question see to go through the follow-up question see to go through the follow-up question and how can you optimize your algorithm to use only okay extra space in other words our brute force solution is going to be using more than okay extra space let's see the first one what we are going to do is if saying we just did we calculate well just have a folder to go through so we're given a row index so the row index is 3 we'll have to create initialize an array which is starting from one right and then we have one we'll continue to iterate through until we iterate through the real index up to 3 that means we're going to create and create real index plus 1 rows right in this case we're gonna have 1 2 1 & 1 this case we're gonna have 1 2 1 & 1 this case we're gonna have 1 2 1 & 1 3 1 so list we'll have one list and one list the very brute force solution of the most intuitive solution that will come up with is to you have a list the very first list is just a the simplest if row index equals to 1 we can just return 1 that's it but for a more generic solution because this one is asking K could go up to 33 but actually the solution could be very generic it doesn't matter so we're just to continue to boot on top of that and then the second list is 1 & 1 second list is 1 & 1 second list is 1 & 1 well just to add this one so here we can try to extend it to be more generic which is going to be this is a list size is 1 so for Pascal's triangle we always start with so looking at this given illustration this interactive diagram we can see a Pascal's triangle is always standing from one so as you can see here it's always 1 and all of the animals that's um that's on the very left end all the starting elements of every single row it's always one like this row here one all of these at once and all of the ending elements on every single row is always 1 2 1 so what we can do is we can always initialize we can always add m1 into that the beginning of the hanumant to this row say we initialize the very first row with that one and then for the second row ok let's see how we build this up and for the second row as I said well just a pop up one to the beginning on the end of the second row on top of this row so we have two ones here right and then we'll just continue keeping this like at one more one here but starting from Row three we also need to check because here it has two animals on top of this one we just add it here because we see on this row it has two admins right above this element which means we need to reset this one how do we reset it let's think about the index is going to be list set this is not correct syntax in Java but in Java it's going to be less just a right and real code in this Google Doc in it's going to be list add suppose this is at index 0 index 1 index 2 so this is going to be it's called yeah set is the true Java syntax set one to be left cat so suppose this is the index right this is the one we need to reset why we need to resend this one because this one is not the annamund at the at both ends it's not on the very left end it's not on the very right end which means this one has two elements right above it right above its head so this one's value needs to be deduced from the two elements right above it that's why we need to reset it right this one is not correct for this row the correct value is two so now how do we reset this list ought to be specific how do we reset this value that you ought to correct it compute this value based on top of the previous one we have added so we have added one more element at the beginning of this rule already and this one we know it should come from the tournament's right above it which is okay let's see let's do it here set we know the index of this one is one there's one so it should be from get one plus list get one plus one why do we do this is the index from here this one is this value its current value before we reset it to the correct value and list one plus one is this value which these are the two values that's right above the one that we are going to reset it which is say here this value this is the value and this is the position that we are going to change it and it's correct a value should come from these two value add up so how do we the problem right now comes to how do we use the proper programming code how do we translate this into the proper programming variables our code which is going to be we use list set this variable we add a 1 we always add a 1 to the kind of the list and then we used the current value at this position plus one and the position plus one which is going to be the two notes right above this one that's going to be the correct value for this position that's how we can reset it the same is going to be true and so after this reset it's going to become here it's going to become one to one which is the correct row for row at index two how do we get here so set one in Java oh well we'll go through that very quickly once we span running code so list and get one is this one its current one and let's get one plus one is which means let's get two which is an index here and at this value so one plus one is two so we set this guy and this index to be two so that's how we get you here the same is going to apply to this case so first we are going to boot let me highlight this we're going to build the correct row values on top of this one on top of this so we're going to add a one here as I said at the top and at the beginning of this row so we add one here first and then what we're going to do is okay let me it's going to be two steps we know do the value reset for all values that's are in between right that's what we did because this is the one than if that's in between for these two rows there they are all add values which meaning the either on the very left hand or on the very right end so we don't need to do anything but for anything else that the value is in between which means they're not on the very left or on the very right we need to reset its value so for this row the two values there are two values we need to reset which is this one and two and how do we deduce the correct values to reset them to we'll just kill them set them by orders so the first one we need to reset is this right go from left to right so it's this one and index one the correct value is going to be one plus one this is the one that we need to reset okay we need to reset two places this is one so after resetting this it becomes 1 so this one becomes 1 plus 2 so it becomes 3 so this one becomes 3 and this one we haven't changed yet and this one is looking like this and then so at this moment we have successfully reset this value to be it's correct letter which is 3 I like this which means we have gone through that already we have gone from that and next up we said we need to reset this value to its correct value what do we do here we're going to set it to be this one index is 2 so we'll set in here to list cat this one is 2 this index is always the same as this index because it's the two elements were right above this one it always has this 1 is the same as this one's index well we'll go through that into more mattias details and things will be more clear once we start running code and maybe set at the bad point in IntelliJ then your things will be even more clear so here we plus 1 so 2 plus 1 is here this one so at this point this is what we have current or just copy it copy here but after this one this value is going to be reset you how much research you this value plus this one which is two plus one which is going to be free you see this is the correct value we have in the very end which matches in here let me highlight here highlight it and okay this is the correct value I hope this all makes sense the key strategy is we want you we always try to add we insert in one at the beginning of the previous list that we just built on top of and then were just for all of the elements that's in between what just to keep resetting the value to its correct one that's this is the algorithm if it's all clear we can start writing some code I know some of you might not have completely gone through this with me but that's fine well we'll go through this in more details right now okay let's put this code and get it accepted first or call it a result array list and then here we'll have to master it for loop I is smaller than or equal to row index because let's say 0 1 2 3 input is 3 this is the room that we want to return somewhere boot up to 3 and Row starts from 0 so here is smaller than or equal to row index and I plus so as I said we always add an e 1 is a special value because Pascal's triangle is always starting from 1 so we always add 1 at the top of the annamund how do we do that in Java so it's going in Java and the ArrayList this list interface has a handy API called add if you just add a value to this say 1 so it's just going to add 1 to this list which is to upend it I don't recall but we can look at that Java API in a second but there is in another API which has the overloaded API for this one you can have specified the index of where you want to add this index so if we take two admins to put two parameters here which means the first one is the index where you want to be the second one is the value where you want to insert value to into this list what take a look at the Java if you have the resume so here we as I said we always add one prefix one into this array list we build on top of the previous one so we always add one here next what we are going to do is that as I said we always need to traverse all of the ones that's in between that are not at the Asch this laughs - this private right we Asch this laughs - this private right we Asch this laughs - this private right we need to reset all of these values to the correct one so let's see here which means we are going to use J as the second index and we'll start from one right why not zero because zero is all of the ones that are on the Left which is one we had it already right we add in one here which means we don't need to go through and also J is going to be smaller than remembering this is going to be a row size minus one why let's walk through that very quickly this row at this moment is going to be a row size of one because we only add them one element right but here as you see this list we're going to get 1 + 1 + 1 this list we're going to get 1 + 1 + 1 this list we're going to get 1 + 1 + 1 here this is 1 + 1 and this is 2 + 1 so here this is 1 + 1 and this is 2 + 1 so here this is 1 + 1 and this is 2 + 1 so we always need to get one more here right that's why we need to put it through J smaller than row size minus 1 so let's row set here too to generalize it this one and this too is going to mean this J here row set this number which is which means we're going to build on top of the previous list all it's not technically correct to being the previous to previous list because we just added one more one at the top and the head of the list so all of the elements in the previous list technically the previous list is going to be shifted towards the right end towards the right that's why we can use this row get J plus 1 here yeah so this is the plus one here this is the plus one key this is the reset and we don't need to go through the end because the N is the remnants these elements we don't need to go through in the end all right that's it that's the entire one and we need to retype return the result let me just quickly run one and see if it works run code cannot find single interesting Oh row sorry this is the result not row result thinking something else okay there's one more Rory's out pending hmm a lot of people running on this question so there's a long queue this is a popular question come on it shouldn't take Zola judging okay finally all right it's accepted now I feel more comfortable to you just submit it let's see submitted it's accepted okay this is the algorithm and is accepted all right I know there might be more confusions so let me fire up my IntelliJ and we can step through this you have a better understanding all right I've just opened my energy the question that we are going through is 1 9 I think so let me open 1 9 yeah this is Pascal's triangle - 1 9 yeah this is Pascal's triangle - 1 9 yeah this is Pascal's triangle - so the very optimized solution is using ok place which is the one that we just went through to go through that in more details and to go through the Java C next to you help us to better understand it we can like say I remember I have a test case ok cool which is this which is exactly the one that we see on the code which is one given real index 3 and we should return 123 or 1 we can even set a breakpoint here do you understand as I said we always add anyone ok no we can just open this Java doc and take a look seeing here the first one is the index the second one is the value or the admin that we want to set it to you look at the Java doc we can have a better understanding so what this a API does is inserts the specified admin and the specified position in this list look at this is very important shifts the animal currently at that position if any and any subsequent admins to the right which means add one to their indices this is what's happening behind the scenes let's go back so what this does is so a very beginning role is just initialized we've emptied a realist which means and its size is one if the size is zero there's nothing there and then we add one to add index 1 and this moment the array size is just one so it's not going to go let's actually set a breakpoint here so that we can better I understand what's going on how the code is actually being executed now let's debug this oh by the way this entire setup I have put it up on my github a link in the description below so feel free to check it out and play around with it on your own and I have you can see in my project structure all of the leak on problems and problem solutions are here so super handy feel free to check it out link in the description below so here we set a few breakpoints here so right now row is initialized with an empty row is just an empty object in Java and size is 0 and the row index is 3 we start from I equals to 0 okay let's step through this row now we come in right we come in we right now Row is still 0 it's still 0 here we just add 1 into this index and here so now you see row right now oh okay so right now Row is we are adding one element at row at index 0 so with value 1 so it's 1 over here now will you come into this in the for loop no it's not why because row size is 1 right there's only one here so row size 1 minus 1 is 0 so J at this point is 1 because as I said we only check the middle elements that's not on the and on the both edges right so it's not going to come into this in the for loop so let's stop for that you say it didn't come in I said a breakpoint in here as well so he didn't stop you which means they go back it doesn't the requirement to enter the in the for loop so now is going to increment I okay I is incremented to one estas started with zero so as I said which we just keep adding once toward the previous list so at this moment this row is still the previous row the previous one that we just built which is still having one element and we just add one more element and that at the head of the list so it's going to become 1 let's see yeah what we're here so at this moment it's still not going to end is still not going to end you this in the follow of Y because row size is 2 minus 1 is 2 and J is 1 so 1 is not smaller than 1 so it's not coming in let's see yeah it's not coming so now if we're going to continue to increment I yes so I becomes 2 here and then we'll just add one more one at the beginning of the road right now the row is 1 so we're just at now the room becomes 1 right this is exactly what we just saw over here in my sketch notes we built as 1 we just always add a 1 to the previous list and then we'll reset the values of the elements that's in between right so here we're going to end with the folder before the very first time why because the row size is 3 there are 3 elements here 3 minus 1 is 2 and J starts from 1 is smaller than 2 which is 2 this condition holds so we're going to enter the second for loop let's see yes it comes in here so at this moment J is 1 the row is looking like this 1 so it has 3 ones so we the value that we need to reset is this one right so J is pointing at this value and this moment row get J which is I is this one I and J plus 1 is 2 so 2 is this 1 so 1 plus 1 is 2 so this API let's take a look at this API lets just quickly open that set we just did oh yeah the one that we just went through is not set oh it's at yes but this one is set is to you as you can see it's very descriptive method API just to replaces the animal at the specified in position in this list with the specified element so it's going to replace this admin which is at index J which is now J is I which is an index I this guy is going to be replaced with these few values added up which is going to be 1 plus 1 is 2 so after I start through this one 1 is going to become 1 2 1 let's see so yeah as you can see it's it becomes 1 2 1 right this is after going through 1 2 3 I think we should have a very clear understanding of what's going on so the final answer that it should return is 123 1 okay we can just there's only one more it doesn't matter we can just bear with me we can just go through the final round which is ok increment I again so I becomes 3 which is the input that we were given so really index is 3 okay so this is the one that we're going to return and which means we're going to break out of the outer for loop because 3 is smaller than and equal to really next after we increment that is going to be equal to 4 which is going to break out in this follow and we're gonna return ok let's see in here again it's going to just to strengthen your understanding of how this works let's see so here we'll start from the middle elements again the middle elements so stand from 1 let's see so J at this moment is 1 so 1 here and 1 plus 1 is 2 u 1 plus 2 is 3 so we're going to reset this value to be 3 so after I clicks this is going to become one three two one let's see yeah one three two one okay then it finished this it just went back to the in the for loop and then we're going to increment J that's C so J becomes two Jane became blue which means in this variable value just to changed and so we'll continue so which means J equals two to you and we'll reset the value at index two which is this one to which value which one is the correct value which is going to be two is here two plus one is three is here this value combine two plus three is three so we're going to reset this value to be three so after I click start through again it's going to become 1 3 1 okay let's see yeah 1 3 1 all right at this moment J becomes 2 and J is smaller than row size is 4 minus 1 is 3 2 is still smaller than 3 but then we'll increment it so incremented it became 3 is not smaller than 3 so it breakout at this moment we're going to increment I again let's see I right now is 3 so after we increment I is going to be 3 is not smaller than or equal to O 3 after we increment 3 by 1 is going to be become 4 so 4 is greater than real index so it's going to break out so now we're going to return this row is becoming 1 3 1 right this is exactly what we were expecting 141 all right we'll just finish this boom okay test passed yeah so I hope this single step it's kind of verbose and lengthy but I think it helps people understand how this algorithm marina works the algorithm is straightforward but it's just how we can implement this in using programming languages to really simplify the to really put this into actual working code and how we can do that in Java using which list on which API sub the list interface this will be handy okay now with that single step through in IntelliJ we can have a bit much better understanding of how that actually works at least in Java programming language then we can talk about the time complexity how did we implement the algorithm to make sure that is using only okay extra space why do we only use okay extra base extra space because we are only initializing one single ArrayList that's it right instead of keep initializing new so instead of like say there are 33 years we want to return the 33rd row of this Pascal's triangle instead of initializing 34 ArrayList we only initialized one a realist but we start from the very first ArrayList we keep adding one to the very beginning of the previous ArrayList and we keep resetting all of the values that's in between and then after we reached the 33rd row we can just return that's why we were only using we're always only using okay extra space at max and which is the very final generation which is using okay we have K elements in the final and realized in previous iterations is always smaller than K elements right this is the workflow of this very classical question not only in interview but also in general program email in math so I hope you guys can have a better understanding of this and if you do don't forget to leave me a like button I'll really appreciate it and don't forget to subscribe to my channel as we continue to go through a lot of interesting new code and programming in interview questions that's it for today's video see you guys in the next one
|
Pascal's Triangle II
|
pascals-triangle-ii
|
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** rowIndex = 3
**Output:** \[1,3,3,1\]
**Example 2:**
**Input:** rowIndex = 0
**Output:** \[1\]
**Example 3:**
**Input:** rowIndex = 1
**Output:** \[1,1\]
**Constraints:**
* `0 <= rowIndex <= 33`
**Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
| null |
Array,Dynamic Programming
|
Easy
|
118,2324
|
688 |
hello guys welcome to deep codes and in today's video we will discuss liquid question 688 that says Knight probability on chessboard so guys in this video I will try to explain you this question in very simple manner so that you can quickly understand the code as well as the approach also I will try to uh draw the chess board and try to explain you how uh this Knight will move on the chessboard right and yeah we would go through the dry run and say the complete uh explanation part so yeah guys stick with the end and watch the complete video now here you are given n cross and size chess board so you would be given one integer and that denotes the size of the chess board and of the night starts at a cell row and column so these two integers would also be there in the input where this is the starting position of the Knight further Knight will move only a k moves right it means Knight will try to move in uh move K times only so you will be also given this integer okay so for uh integer would be there in the input and row column and k is the total number of moves Knight can make so ah these are the a detection right you might know that how the night moves it moves in this eight direction from if it is a center here it will move in this eight Direction now here we need to find the probability that an uh that after K moves 9 it is on the chess board right see it may be possible that after Camus Knight will go out of the chessboard right it is possible but we need to find the probability that night remains on the board after uh it has stopped moving so it has stopped moving after K moves right we have to find that probability okay got it the occasion is pretty much clear that we simply need to find probability so what is probability of is nothing but favorable outcome upon total outcome so favorable outcome is what the night remains on the board so that is a favorable outcome here and by using the simple formula of probability we would calculate our answer okay so if you take a look at the first example here we have n equals to 3 K is 2 and rho column is zero so let us try to uh draw a chess board to understand this so a chessboard would look something like this so chessboard is of size three cross three and initially it is overnight is presented row 0 column zero okay and here we have k equals to two moves here we have two main okay now let's say this is these are the eight homes that I have already drawn here so this is the r minus two c plus one R plus r minus 1 C plus two so this way these are the eight possible moves that Knight can make here now out of this eight possible move we can see that these two moves are uh are inside the chess board or we can say these are the favorable outcome of uh success moves right so uh from out of this eight there are two moves by which we can get a success okay now at this point uh here we have made one move we need to make second move so either what we can so either we can make a second move from here so this is second move or we can make a second move from here right we have two choices here right make a move from here or from here so let's say if we make a move from here our Knight would be at here now from this these are the eight possible detection in which now it can move and from this eight there are again you can find that there are two success possibility here so if Knight is presented here then if Knight can move to these two so that it can stay inside the chest board so these two are our success similarly if the Knight is present at here then there are two success chances right in these two moves Knight we would be inside the chessboard so guys uh in total like after performing K moves what we can see is there are four parts what four parts are there paths I'm talking about path so initially Knight is your okay so one possible path is from here it goes to here and from here it again comes to here so this is path one now what is second path it moves to here and then from here it moves to here this is second path the third path is it the Knight moves from here to here and from here it moves to here again so this is the third path and the fourth path is uh from here it moves to here right so after two uh rounds we can say that there are We There are four paths by which Knight would say inside the chess board or itself right so after K moves we can say there are four parts by which we can get a success and what are the total Parts see it is 64 because uh in the first move there are eight possible moves and in the second move there are eight possible moves right uh because C because k equals to K is 2 here so in the first move there are eight possible moves and in the second move there are also eight possible moves so total it is eight crosses 64. so this way you can find 64 different parts here okay so what is the probability here probability of success is 4 by 64 that is favorable outcome upon total outcomes so that is nothing but 0.0625 nothing but 0.0625 nothing but 0.0625 so guys that's how we reach 0.0625 here so guys that's how we reach 0.0625 here so guys that's how we reach 0.0625 here because we have found four paths by which we can by which the 9th would say stay inside the chess board and similarly there are 64 total possible uh paths okay in two moves so I guess the probability is nothing but 4 upon 64 and that's 0.0625 so that's how we reach to that's 0.0625 so that's how we reach to that's 0.0625 so that's how we reach to this answer here okay so I hope you guys have some what understanding of how we are calculating the probability here now if you take a look at the second example here n equals to 1 K is 0 so K is 0 and that means we Knight won't uh take any more zero number of moves Knight will make and at the initial stage Knight would be itself inside the chess board right will start from any other cell of the chessboard itself so that's why the probability of one means there is no chances that Knight would move out of the chessboard because total number of move is itself was zero right you can you won't be able to make any moves here so yeah guys that's why the probability is one here because the Knight would stay inside the chest bone only and if you take a look at the constraint the constraints are very favorable we can say it's very less 2500 K is up to 100 and these both are up till n minus 1. so guys uh based on this what we have concluded is for each move we have to find a eight different uh we have to try to find the answer in eight different direction okay so uh that same thing we can apply while doing recursion see because in let's say in you are performing okay so let me try to explain in this way let's say k equals to three okay that means we have to do three moves so in move one we will try eight Direction in mood uh second move we would try a direction try to find answer in a direction move three we will also try to find answering a Direction so this thing is repeating right we have to find answer in eight Direction so uh what we can do is we can write a recursive code okay and in the recursive code uh this thing would remain the same for all the recursion right for all of them move one move two more three so that's why we can easily write a recursive code because there are choices right choices to I move in a particular path or not and the base condition is also very much intuitive that if you have moved out of the cell out of the chess board then we don't do anything we simply return and if we are inside the chess board and total number of moves is zero right we have completed all the moves that we want to do that means nighter completed kmos and after Camus if we are inside the chess board then we will simply increment our success that means we have found one path by which after K moves we would stay inside the chessboard so we would simply do success plus that means we have found one successful path right and these are the eight different direction in which we are ah moving the Knight right so this is the recursive function that we call here and what are the total possible paths that is a to the power of King so that's why we find this way and yeah at the end we simply return the probability that is Success upon total right so this is very Brute Force approach to solve this question that we have tried to solve this recursively now guys uh this since this is a recursive solution our next step is to make it optimal by using a memorization approach right so to memorize this approach we would create a 3D DP and initialize it by 3D DP because there are three changing variables variable one two and three changing variables are there so we have to create 3D DP further what we would do is we would store probability of each step okay now here so what we would do is we would make this solve function uh solve function would give us the probability at each step see guys uh you might be wondering that here uh we were trying to find out of successful paths upon total path right we were doing this but if you look at the constraints K is up to 100 okay case up to 100 and a to the power 100 is huge number right it's a huge number so that's why if you try to go in this way like if you memorize this approach memo is the this approach then it won't work right because simply if you see that power of 8 comma 100 would be so large that you won't that it won't fit in the integer or long int or any right so yeah we cannot go by this approach instead what we would do is same here let's say this is a move one and let's say this is Mo nth move and inside and move we are trying to find a probably uh we are trying to find parts at eight different direction so instead of just fine trying to finding the path what we would do is we would find the probability and pass on the probability so instead of finding this success we would pass the probability so that inside this DP array we will we would store the probability at of each step now you might be wondering that how we will show the probability let's make it right and to understand that so to get the answer what we would do is we would call the solve function okay now the solve function with initially K9 is presented here now from here we would try to move in eight possible Direction okay so this is step one now this step one we could say that there are um there are two possible valid answer then what since this is a recursive call from here we would uh we would make a recursive call to step two right this will make a decrease equal to step two okay now at this step two our all recursive call would end because if you see these or recursive calls that move outside this would this all would return what this all would return 0 and these two this both way will not return one this both will return one right this both will return one and others would return 0. so all possible uh paths would come to an right at this after this we want to move to any other step because we have uh covered all the possible paths and there is no recursive call from that uh path right no because they call remaining so at this point we would end now what we would return to its parent right what we would return so this step two will return 0.25 return so this step two will return 0.25 return so this step two will return 0.25 how 0.25 that is how 0.25 that is how 0.25 that is because there are two success we got so if the Knight is here we would get two success out of it so probability 0.25 so success out of it so probability 0.25 so success out of it so probability 0.25 so this will return 0.25 to here okay got this will return 0.25 to here okay got this will return 0.25 to here okay got it similarly this would so if the Knight is zero then we would make a recursive call again right because K is remaining so if you make a recursive calls it this all our this all that are moving outside the chess board would come to end this or recursive call would come to end by returning 0 and these two would also come to it because K is 0 so these two also uh would come to end but they would return one so out of eight possible direction or eight possible paths we would get two as our answer that means we have found two successful path from eight so this would also written 0.25 eight so this would also written 0.25 eight so this would also written 0.25 right this thing so we have uh so that means we have 0.25 coming from here 0.25 means we have 0.25 coming from here 0.25 means we have 0.25 coming from here 0.25 kilometer from here now this step one would have to return something to the answer right to get the answer to the main function call right so that would return what total uh Total Choice is if it means total uh probability sum of all the probabilities that we have found here up till total is eight at each step total uh probability is eight and this is the favorable one 0.25 and 0.25 and we would add it right 0.25 and 0.25 and we would add it right 0.25 and 0.25 and we would add it right why we were adding each thing in a probability there is a one uh rule that if we are performing end then multiply if you are performing or then add right this is a simple row why we are adding because there is a possible path from here to here so if we if Knight moves through here or if the Knight moves to here then it will reach to some successful path so here we are using our term and that's why we are summing up the probability so this is a simple way to understand why we are summing up so if you sum this up and divide by its and you will get 0.625 divide by its and you will get 0.625 divide by its and you will get 0.625 that is our desired answer right so guys uh here we have initialized this 3D DP array of such 26 and 101 with minus 1 and we call this all function now inside the solve function as we know that we are checking in all eight Direction and the base condition also Remains the Same this is additional one for the DP that means if we already calculated as a probability at a particular State then we would return that answer so this is that step now uh let's say we are uh so uh what you can see is we are trying to find answer in eight possible reduction so initially this is one step one so after this step one will call to step two right because they see this one recursive call will come to end this odd would come to end but these two won't come to an as k equals to one it's K is still remaining K is not zero so we have to make a recurs record from these two so these two would reason some answer right this uh so whatever we answer we get from eight different stages or a different direction we would simply sum them sum data right so here uh we what I have told you here we are summing up right our answer from eight different direction zero so and then DB divided by a because a t is the total number of detection for a particular position from a particular position there are eight detection so that's why we divided by it and which store the probability inside of our answer okay and yeah also note that here we have made the return type to double because we are returning the probability in terms of double right so again that's how we are solving this equation and talking about the time in space complexity so the time complexity here is you can easily see this 26 101 and that same would be the same space complexity plus some recursive stack uh would also be uh used in the space uh so yeah guys that's all for this video if you have still any doubts then do let me know in the comment section make sure to like this video And subscribe to our Channel thank you
|
Knight Probability in Chessboard
|
knight-probability-in-chessboard
|
On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly `k` moves or has moved off the chessboard.
Return _the probability that the knight remains on the board after it has stopped moving_.
**Example 1:**
**Input:** n = 3, k = 2, row = 0, column = 0
**Output:** 0.06250
**Explanation:** There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.
**Example 2:**
**Input:** n = 1, k = 0, row = 0, column = 0
**Output:** 1.00000
**Constraints:**
* `1 <= n <= 25`
* `0 <= k <= 100`
* `0 <= row, column <= n - 1`
| null |
Dynamic Programming
|
Medium
|
576
|
1,835 |
hey what's up guys uh this is chung here so today uh 1835 find x or sum of all pairs bitwise end okay so you're given like a two arrays right and our task is to find the xor right among all the pairs between those two arrays you know where the uh the result of the pairs will be an end right basically so what this one is trying to ask us to do is that you know for each of the numbers you know for each numbers between those two arrays you know we're going to get like an end uh about all the pairs basically we have one and six right and then we have one and then we have two and six right and we have three and six and then we have well one and five right two and five and the three and five so that's the uh that's the that's a that's the value right for each pair and then amount of those values you know we're gonna do a xor right among those two among all of those pairs right so pretty straightforward right of course you know the brutal first way is that you know we simply do a loop right we loop we do a nice little loop here we try to get each pair and then we do an end and then we just do xor uh for all those kind of pairs right but obviously given the constraints which is ten to the power of five you know that will be uh that will lead to o of n square time complexity which will be tle right so how can we solve it right i mean actually there are two solutions here for this problem you know the first one is the one i used you know during contest which is a little bit uh a longer to implement second one is like a very easy one by using the distributive uh property so let me uh describe the first um my solutions first right basically you know since we do we want to uh decrease the time complexity how can we do it you know so every time when you see this kind of acts or on an end you know always try to think it in a bit wise way right so which means that you know let's say we have this three uh one two three and six five okay so what is six five is so we have one two three zero one right one zero one and then zero one zero and then zero one that this is already array one right and now ray two we have 6 and 5. 6 is what 6 is 1 0 right 5 is 1 0 1. all right so that's basically the six those numbers so as you guys can see if we only consider the values for free for each bit right let's say for this bit when we do the when we compare the pairs right we're going to do the pairs right basically we're going to do like the uh the end right we're going to do the end uh for each numbers uh on this array and we do another uh two with the other number with all the numbers here okay so which means that you know on this bit wise here so here we have a one so one do a bit end with this two here right so we have what one bit wise with these two numbers we have zero and one right because one bit one bitwise n zero is zero one bit wise one is one right and then we have one we have the second one zero of course zero bitwise with anything with bitwise n will be zero so that's why we have a two zeros here right similarly for this one here we're going to have like another zero and then another one and that's the uh that's the result for all the pairs for the speed value right and then what's next we're gonna do a bitwise or right among all those values right so what does this one get we have we're going to get zero right you know for b twice or right i mean say two because you know so first you start you know if this uh two number two the same numbers do a bit wide we'll get zero right doesn't really matter which number it is as long as they are the same and then we'll get zero okay and since you know the possible values between these two between the end right b twice n for this bit wise it can only be either zero or one so that we can ignore zero because you know if they're all zeros you know we do a bit doesn't really matter how many zeros we do a bit wise or there are there will still be zero so and the value for this one can be either zero or one right and so when we get zero oh sorry when we will get one so when the total number of ones are odd numbers and then we'll get a one right because you know for example we have two ones in this case that's why you know since all the zeros what we do after doing the uh xor with all zero there's still one zero so depending on how many ones here because if we have two ones then the value will be zero if we have a three one right let's see we have another one here you know the value will be instead of zero it will be one so if but if we have another one here this one will become to zero that's how we do this right so now the problems comes down to what to uh which we simply need to count how many ones we have i mean after doing this kind of uh finding all the pairs right and how can we fi how can we calculate all the ones right after doing this kind of uh pairs combinations for array y and array two we can we simply need to count the ones at each bit for array one and array two and then we simply do a count one times count two that's gonna be the total ones right we will get after doing this kind of a pair combinations because in this case for example we have two ones uh you know real one and one in every two that's why the ones we have on this bit will be two times one equals to two right similarly for this one we have two ones and one ones here that's why we have we also have two on the second beat and when it comes to the third one right even though we have two ones here but since we have zero ones in a ray one so when zero times two we have zero it means that you know we will have zero ones in this case because you know since as you guys can see so every time we have a zero uh bitwise end one will have zero right okay cool so i mean now we simply need to just need to uh create like a counter for once for both array one and array two for all the bit values uh right and then we just do another like for loop right to just to check each bit value and check the uh the parity of ones and if the parity of one is odd we simply add that bit value corresponding bit value and since the constraints the biggest number is 10 to the power of 9 so we can simply use 32 size of beat to represent this 10 the biggest value right cool so like i said we have a max bit right it's going to be a what 32 right in this case so i'm going to create two uh arrays counter rates here you know so first one is the arrays count once one right so it's going to be zero times max bit right and then we have like count two to store the uh the bit count for each for both array one and array two right so for num in array one right we do a four i in range of max right we check if we check each bit right if the bit is one we increase the count for that bit so if the number and one shift i right does not equal to zero it means that bit is one right so we do a count once one i increase by one right similarly for the for array two right uh we simply change this one right and then in the end we have answer equal to zero we use we just check the parity for each of the bit right the parity of ones for each of the bits so in range of max right so we have total ones equals to the count ones i right multiply by the count once two and if the parity of the ones is equal it's odd we're gonna we know okay so this value will be this bit will be one what means that you know we need to add this value to the final answer right and then we return the answer that's it yep oh i use max okay later on so okay i'll change this one to max accept it yeah and it passed right so the time complexity obviously you know we have what so this is n right it's n times 32 right yeah so this is also uh this is also 32. basically time complexity is also it's all of n right and the space complexity uh is one actually right because you know we only have like up to 32 sides of a rays here yeah so that's basically the first solution and there's like a easier one you know but that one requires a little bit observation uh for the uh because we need to use the distributive property to solve it so what is the distributive property so the distributive the distributed property is let's say we have uh a1 plus a2 times b1 plus b so this one equals to what equals to a1 times b1 right plus a1 times b b2 right plus a2 times b1 class a2 times b2 okay similarly for the uh for x4 and the sum so for x1 sum so it means that you know we have so basically if we have a1 uh x or a2 right and then we and the b1 x or b2 this one equals to what similarly for this one we have a1 and b1 xor a1 and b2 and a2 x or b1 last one a2 and b2 so this one as you guys can see is exactly what this problem is asking us to do all right we have two arrays right a and b so for each of them we're gonna do like the pairs combination of pairs for each pair we do an end and then in the end we do x work that's why you know so this one as you guys can see we simply just need to get the xor for both array a and array b and then we do an end between those two numbers that's it you know but the one thing to be noticed that you know same thing for this uh class and the multiply thing this property distribution the distributed property only works in one direction so which means that you know if we change this one to uh times this one turn into times and then we do a plus in the middle this one does not you cannot work you cannot use a like distributed property in this case you cannot do a1 times b1 plus a1 times b b2 and so on and so forth right this is known right so same thing for this x or and b on the end so if we change this one to uh to end and then this one to the or we cannot make this uh transformation just keep that in mind okay it just happens to be up for this problem it happens to be we can uh just use this one yeah and okay so let's try to implement that in this case you know it should be pretty very easy you know so we have uh what we have num one right we have num2 equal to zero right and then for num in array one right we do a num one two xor of num right for num in array two we do a num2 x or num and then we return num1 and num2 yep that's it run the code submit cool see it simply works you know and yeah the time complexity is it's also o of n you know but as you guys can see this one is faster because we are removing the inner uh inner loop comparing to this to the first one but you know anyway uh yeah i think that's it for this problem i'll stop here and thank you for watching this video guys stay tuned see you guys soon bye
|
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 |
376 |
hello coders welcome back to my channel let's solve lead code medium problem 376 wiggle subsequence uh let's see the description a bigger subsequence is a subsequence where difference between successive numbers strictly alternate between positive and negative okay and a sequence with one element and subsequent uh sequence with two non-equal elements are trivially bigger non-equal elements are trivially bigger non-equal elements are trivially bigger sequences means if there is a one element then it's a bigger and if there is a two element different element then it's also a vehicle subsequence and uh if there are multiple elements then the differences successive differences should be alternate means if the first is positive the second difference would be negative and third should be positive and therefore and uh if the first is negative the second should be positive there's there should be alternate okay and what we have to do is given an array of integers we have to return the length of the longest bigger subsequence okay like for this example uh as we have seen here it there is a six length of six subsequence and for this uh there is a seven subsequences with the differences 16 minus seven three minus three and this all let's see the solution in java what we have done is like we have taken two variables like positive and negative it just like we are storing the last like for the array of length one the answer will be one okay that's why we are it's a variable which is storing the uh positive length and negative length of sub vertical subsequences then what we are doing is we are looking through the array which is starting from one uh and uh to nums length and we are checking like if num psi is greater than my minus one means the difference is positive then we are increasing the positive variable with negative plus one else what we are doing we are checking if it is the difference is negative then we are increasing the negative variable and if differences are same then we are not in doing anything like positive and negative uh variables will be same and at the last what we are returning is the maximum of positive and negative this will be the result of maximum length of vehicle subsequences and this is the complete solution if you like this video please hit the like button subscribe to the channel and press the bell icon thanks
|
Wiggle Subsequence
|
wiggle-subsequence
|
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative.
* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`.
**Example 1:**
**Input:** nums = \[1,7,4,9,2,5\]
**Output:** 6
**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
**Example 2:**
**Input:** nums = \[1,17,5,10,13,15,10,5,16,8\]
**Output:** 7
**Explanation:** There are several subsequences that achieve this length.
One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8).
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6,7,8,9\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
**Follow up:** Could you solve this in `O(n)` time?
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
2271
|
350 |
That good morning all of you today and world tour discussion with your interests of 217 and in this add ML and in this question and just give a truck and van 102 both are random note easy ignorance pocket 100 on list start that a first form VHP That test is a little bit The all elements of the sequence are mapped to these So first of all let's take a measurement An Ardha Namaskar How toe I have explained more about before and toe Of color of Country will have to get to disrespect answer confusion that and let's start to that If that % A pimple came in the hair, % A pimple came in the hair, took an inspector and we stored this mark in this match and after coding its frequency, now second Namaskar travels, it is through the look on it, so that we have finalized that app, then in the map. Is it available or not? If so, then its sequence should be that end pregnancy - - - - and we have that end pregnancy - - - - and we have that end pregnancy - - - - and we have asked it in the answer, so let us continue till the last till now that we have returned the answer, then thank you so. If people on the side of Much Life would have understood this, then this playlist will continue in June, I am targeting to complete 60 plus questions by June and in a few days we will start adding more questions to Deepika, thank you for that. Share this video with your friends everywhere, thank you so much.
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
116 |
hi everyone i'm bihan chakravarti and today i'll be discussing the problem number 116 from latecode that is populating next right pointers in each node so in this problem we have been given a tree and this is the structure of its nodes so along with the value left and right nodes we have an additional node that is next so what does next do as you can see populate each next pointer to point its right next row next right node if there is no uh next node it should be null so uh let me open it in another tab as you can see from here so the next of each node should point to its right element that is two should point to three two null uh four to five like that so this should be done now this problem can be done in various ways using bfs dfs like bfs means i mean level order traversal and another way is that is using level order traversal but without q that is of one space so i will be discussing that approach so let's see here first of all let me add this is the code if you want to go through it you can just directly check it out and i'll explain the uh intuition first so here let me start with this section one two and three so suppose one is the root okay i'll write it down here 1 is the root so how can we write 2 in respect of 1 in respect of root we can write it as root dot left 3 can be written as root.right okay so since we have to connect this edge two to three what we want to do is stay one level above it because if we are using bfs at two i cannot access three to access three i know need to be at a place where uh through which i can access both two and three that is their parents like to connect four and five i have to be at two to connect five and six i also have to be at two or three like that so given that let's see so if i'm at 1 and i want to connect to n3 what i can write root dot left that is r2 dot next equals to three that is root dot right so i can write this root dot left dot next equals to root dot right root dot left is two its next points to right that is three roots right so we have an edge here pointing like this is the one after this let's move in this case now four and five can be done in a similar way well we are at two we can directly connect four and five but what about 5 and 6 so let's see this one suppose i am at 2 okay so let me write down again here root is 2 okay so what's 5 is root dot right now we want to connect 5 to 6 so what is 6 and how can we relate 6 to the root what we can do is like check the relation of 6 from 3 what is 3 so let me write 3 first 3 is root dot next right this is root now and its next points to 3 and where is six is three's left child so what we can write six is root dot next left child root dot next dot left root dot next is three its left is 6 so now if i want to connect 5 and 6 what we can write what is 5 root dot write dot next equals to root dot next dot left root dot right that is five it's next will point to where it will point to roots next and that's left that is six so this is the two conditions let me keep here so using this condition and moving down the tree we can connect all the edges so now what should be the approach of moving down we will have two loops the first loop will continuously move down it will start from 1 then it will go to the next level that second levels left most node then it will again move to the third levels left most node so we can do that by writing root equals to root dot left so it will always move through the left most nodes like that okay and while we are at the left most node at a level at that point we will run another loop that will cover all the edges one after another sorry uh let me replace it will cover all the nodes present in that level one after another like we are at four then we will uh go to five then we will move to six and then we will move to seven now how can we jump here we can jump here by let me erase this we can jump here because this edge already exists when we reach this level because while we are at 1 we are connecting 2 and 3 so when we are we arrive at 2 this 2 3 edge is already there and while we are at 2 we are connecting 4 5 6 7 and 7 to null so after these are done while we are at the third level we can easily jump from 4 to five by doing root equals to root dot next then again root equals root.next to jump to again root equals root.next to jump to again root equals root.next to jump to six like that because these edges are already here and we can use that to uh like connect the levels down below as well so here no levels are given below but yeah this is the intuition so uh the code is already there let me show it to you yeah so this is the head node what is head node is the one that moves down the level okay so as you can see at the end after all this is done let me cut it head initializes from root that is one and while head not equals to null head equals to head dot left so head will jump to two to four to something else here it is null so like that now let me paste yeah so inside the uh inside the loop while we are at the leftmost node of a level what we will do we will copy uh the address here in p now we will run another loop and inside that loop what we will do let me cut this part okay so inside that loop we are doing p equals to p dot next that is we are jumping from this node to this node now this is the whole traversing part now before jumping we have to connect the below edges as well like why what we are at two we will connect four and five and six then we will jump to three then we will connect six and seven and null okay so these are the conditions if p dot left equals to null we will break because else we can't do this one so these are some necessary conditions here now we are doing the same thing p dot left dot next equals to p dot right if 2 is the root p is left is 4 and why uh p dot right is five so we are connecting p dot left dot next that is force next to five and this second condition ensures that we connect five and six p dot write dot next equals to p dot next dot left p dot right is uh five who's next is connected to where p dot next dot left p is next is three and three is left is six so we are connecting five and six so after that we just increment it increment the p pointer that is move from two to three so this is the problem now there are two loops but the time complexity is o of n because we aren't revisiting any nodes we are visiting all the nodes only once so this is the problem if you have any doubts on queries please comment down below i'll try my best to answer them and if you have liked my video please like and subscribe it will definitely keep me very motivated to make further videos thank you
|
Populating Next Right Pointers in Each Node
|
populating-next-right-pointers-in-each-node
|
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[1,#,2,3,#,4,5,6,7,#\]
**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 212 - 1]`.
* `-1000 <= Node.val <= 1000`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
117,199
|
435 |
hi everyone let's look at a legal problem today it's called non overlapping intervals given an array of intervals where intervals I equals start I and I return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping rest of the intervals non-overlapping rest of the intervals non-overlapping two keywords minimum and non-overlapping two keywords minimum and non-overlapping two keywords minimum and non-overlapping let's look at the first example one two three four and one three we can see that 2 3 and 1 3 are overlapping so we can remove one three in and after removing it our intervals are one two three and three four they're not overlapping so our answer is one which is the number of removed intervals the second example one two all of them are the same so all of them are overlapping we can remove two of them and we return two in this case the third example one two and two three they are not overlapping so we just output 0 in this case so how to solve the problem let's first take a look at an example 6 7 5 9 and 8 15. we can see clearly that some of the intervals are overlapping such as six seven and five nine so we have to remove one of them and keep the other but which ones keep my strategy is to keep the one with the smaller ends in this case I will keep six seven and remove five nine but why because the problem demands that the number of remote intervals be minimum which means the viewer overlappings the better if we keep the interval with the smaller ends and remove the other that kept interval will have a lower probability to overlap the next one in our example if we keep 5 9 and remove six seven five nine will overlap 815 then we should remove another interval again so in this case our result is 2 because we removed two intervals in the whole process but if we keep six seven and remove five nine six seven won't overlap 815 so the results will be one in the in this case because we only removed one interval in the whole process as you can see choosing six seven which has a smaller and then five nine would be a better choice its answer is smaller if you still don't understand I will draw these intervals for you and go through the process step by step okay let's first draw five nine and seven and eight fifteen okay as you can see we should keep six seven because it has a smaller end if we keep five nine it will overlap with the next interval 8 15. and when that happens we need to remove one more interval again our results will be larger in this case which contradicts the problem's description it requires a minimal results so keeping six seven would be a better choice it's won't overlap 8 15 and we can get a smaller answer so we will figure it out which interval to keep with overlapping happens which is we should keep the interval with the smaller ends the next question would be how to find overlap intervals one obvious strategy would be to check adjacent intervals one by one our previous intervals as an example if we have five nine we have six seven and we have 8 15. we check the first two intervals first and then we find that they're overlapping we should keep six seven and remove five nine because six seven has a smaller end then we check six seven and eight fifteen and we find that they're not overlapping so our answer will be one which happens to be correct notice that I said it happened to be correct it only happens to be correct because our strategy won't work for all the cases it only works for our case because our intervals happen to have the optimal order I can give you another example where that strategy doesn't work the example is one two three three four and one three okay let's follow our previous strategy We compare each pair of adjacent intervals one two and two three no overlapping two three and three four no overlapping three four and the one three no overlapping so our answer would be zero because we remove zero intervals is that correct no of course not you can see that two three are over two three and one three are overlapping so what's the problem here the problem is that we didn't sort our intervals we should sort our intervals by their ends the intuition is that by using this method we put overlapping intervals next to each other so that we can find them just by comparing adjacent intervals just like this we should put this behind and we get this and this as you can see we have already sorted the intervals by their ends the ends are 2 3 4. and they are sorted then We compare these intervals one by one first we compare one two and one three they are overlapping so we just remove one of them we removed one with the bigger ends which is one three then we compare one two with two three they're not overlapping so we keep them both then we compare two three and the three four they're not overlapping either so we keep them both so our answer in this case will be one because we only removed one interval which is correct so in conclusion the process of solving the problem is first Source the intervals by their ends and the second we should compare each pair of adjacent intervals and if they're overlapping only keep the one with the smaller ends that is how you should solve the problem okay let's code let's first sort the intervals by their ends then we are going to Define two variables called first index and the second index they represent the indices of the intervals we're comparing we need to check if the two intervals are overlapping so the initial values of the two variables are 0 and 1 respectively first represents the first and the second interval and we also need to define the return value with charcoal which is going to be returned in the ends since we're going to repeatedly compare adjacent intervals we need a while loop and the wall Loop continues while second index is less than intervals don't let and the inside while loop we need to check if the two intervals are overlapping if they're overlapping like for example five seven four nine and the 10 15. suppose first index is zero and the second index is one and you can see that the two pointers point to the first two intervals five seven and four nine and they're overlapping in this case we need to remove the second interval for nine because it has a bigger ends notice that it's also possible that the second interval's end is equal to the first one like five seven 4 7 and 10 15. in this case you can remove either of them and we can still choose to remove the second interval so in conclusion we only need to remove the second interval when overlapping happens because we're going to remove the second interval we first increase the results by one because it stores the number of removed intervals the second interval will be one of them then because the second interval is removed we increase second index by one so that the second index will point to the next interval and in our example the second interval will be changed from 4 9 to 10 15 and we will compare five seven and 10 15 in the next iteration and if there is no overlapping such as 5 6 and 8. in this case suppose first index points to five seven second index points to 810 and we have another interval 12 15. since 5 7 and 8 10 are not overlapping we will compare the next period of intervals in the next iteration which are 8 10 and 12 15. that means we need to assign the current second index to First index and we also need to increase second index by one so that we can continue to compare the next two intervals in the next iteration and that's the basic structure to complete the code we need to implement is overlapping which is pretty easy we just return intervals one is greater than interval to zero and when that happens we think that the two intervals are overlapping so this is the complete code
|
Non-overlapping Intervals
|
non-overlapping-intervals
|
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104`
| null |
Array,Dynamic Programming,Greedy,Sorting
|
Medium
|
452
|
968 |
Hello hello brother is welcome to my video phanda seerte baikunth problem magical ko rona vaccine so give the native vaccine for coronavirus i want to for no7 glad to have access to get government where is not representative house England final minimum number of houses of 26 apply the Bed Scene Ketevan Vaccine's Application Form House Paint House and Its Immediate Childhood Itself Example to Understand So Let's Take a Very Simple Small Example to Then Starts With Under One Vaccine 6 December 10 201 House to House On That Hindu Spotter Equal To How Many Vaccines That Do You Need Plate Think About Weather You Can Provide Excellent Hair Its Provide Vaccine To The Eggs Also Provide Vaccine Shares This Will Also Cover For Child Rights Both of them will gather vaccine is sufficient or you can provide to the son the child in this is it will cover all aspirants who will give the answer is the answer ok what do you need to provide to the Child and parents will provide a child parents and mother that in 10 follow what is the answer in this case let's you provide for some files where provided vaccine kittu child which studied for parents go into great cover rate vis isi provide invited to Child Will Share With Both Of Them Are Getting Award But What About Than What About 3digit Not Getting But It Is Not Getting Award Vikas You Provide In Vaccine Kittu Yah Wedding Vaccine Ki Tubelight Cover For One But What About Three Last Not Getting back singh get solution provider for three also in this case the unit to provide will be to is you provide 2012 its property to the not to you need to vaccine ok what this page provide about three withdrawal to the note 3 is in That Case Also The Will Cover For One But What About Two Students Too Front For Itself Will Need To Tube White 4151 Rate You Need Only One Vaccine K Vikas In That Case One Will Cover 431 Will Cover All To All Of Them Will Be Protected From Co But All Of Them Will Gather Vaccine Kit City Provide To Parents Day This Matter With Spirit Will Cover For Both Children At Fennel Big Confusion In The Place Where The Way Want To Provide To Parent Child Should Always Beneficial To Provide To Parent In The Case When there was confusion because parents will be able to provide for its spirit will also be able to provide and four cloves in a plate see more examples to validate and kaleem plate if you have something like this Elaichi 4850 Ki Let's get started decide on the sets of What They Thursday * * * Notice Rice's Research Ongoing Other Child E Don't Have Any Children and The Truth About Being Fit Independence Parents Water Singh and Child Right What Will He Be at Its Needs Vaccination for Residential Vaccine Sweets and Child But Want Subjects in Two The Parents Word Parents Go Into Parents Want To Provide Such Yuvan Vaccine Parents Want To Provide Excellent For It's Okay So Let's Suresh Supply One Vaccine Kittu So What They Are Doing Is Supplying One Vaccine Kittu Redmi Market With Circular To Draw A To Supply Vaccine To Record Tourism Guide 2012 Protective Shield 2012 Protect Foils Ruk Notes That Go To Tire 2012 Products Chal 2012 Product For It's Always Protect One To Will Protect Salute Oo Will Protect Style To Will Also Protect Its Own Parents To Will Protect All The Three Let's Rate Provide About 3 Free Loans Vaccine Three Want Vaccine Note Three Days Went For Watching 312 K Parents Provide To Three Parents One Rights Will Need To Give Vaccine Ki 213 343 To 351 Also Provide What Is The Child Will Give Vaccine 2012 301 More K Examples Reflective Vo Examples In the logic so a piya 1st love you good night are using this example ok bhaiya one should not mean that will take more examples k flat se vihar 8 and it's a wave no knowledge start with building this example saunf 125 is very simple steps from the Best Rates Notes So Let's Know What Is Not To Say To Child Something Parents Above Tips Number Nine Whole Months She Will Be Seen From Its Parent To Provide Provided To Avoid 293 And 294 323 Model Of Lutelute To States Notes In State PSC Exam And Want Vaccine And Not Can Provide Vaccine Trailer Addiction To States Fennel Example 9454 Subjects In And Out Of Parents And Provide The Vaxing But What About The State 3-day 3 Idiots Readers Do Not Need A State 3-day 3 Idiots Readers Do Not Need A State 3-day 3 Idiots Readers Do Not Need A Question Because Why Does Not Mean That Works In Developed Already Been Provided For Adults Protecting Free Apps Protecting 364 Serving Vaccine And Want To Share With Parents Protecting Frill District 323 Not Want To Vaccine Is Point To Point Question Ironing Going To Provide Vaccine Cacl2 Cylinder Want To Provide Free Water After Waking State Which Provides a Wide Awake All Night Away for Three Days as a Gold Cover for Married Sisters For Its Products What is Doing It's Protecting Its Effects of Protecting Them Not Need to Vaccine Serial Status Not Need to Provide About Seeing What is the State of Three Lately it's a state of ok three ok record getting award button not ever wanted and didn't even want to provide ok tidy edit ok sled almost as well as in three states like a girl child whatsapp vaccine here respected provide in the vaccine and someone else Insted O's Par Don't Want Never Be Provided To 130 Staff Okay So Number Vaccine's Slice One And Destroy Depot's Bus Go Forward In This Example Of All H Less Meaning Because Latch Is Less What About One Vote One Lapsi Soft One To Decide Anything 192 First Look At Very This Children Worship Them From Near This World But 400 Then And Cigarette For That In State Of Want For Want Of Vaccine Okay To Have Provided Excellent For Backs * HP Price Number For Backs * HP Price Number For Backs * HP Price Number Vaccine Ke Tattu Hai Sapna 2012 Provide 2012 Cover for Professionals 125 What is to Prevent Provide About Scene OK Not Just Wedding Look at Least One Capsule WhatsApp 1212 Service Provider for Wedding Oil Su 2515 Vaccine 151 Mid Day Neetu Provider Vaccine 10 One Needs to Provide Vaccine No One Needs to Provide Vaccine Because Notice Children Nirav Vaccine OK See Very Important This World Has Not Want To Vaccine Because One Has Already Getting Covered Boys Already Getting Up At All Should Not Need To Provide About Chandra Bose Notice Children Need Vaccine All His Children And OK Subah In Wallapt One should win the state ok let's go ahead knowledge come list decide for 5 to decide 512 at that time morning weekends 500 vs decide for that by 7 boeing 737 vaccine subscribe 65th number also subscribe 505 getting provided for getting rid of water in prithviraj Let's discuss the example hoon to alerts from the very basic base note slideshow play list start with no tan ok what is the state of note 0 infection to sunlight and gets back synthroid protective 01 singh tuteja will set witch parents whatsapp vaccine list that they ribbon Number Of Units Not Only A Student From Its Mother Child Will Decide So Let's See What We Fight Seen Them Do Not Lose But Still Want To Provide A Child Parents To Provide Wedding Levels And Should Not Be Provided To 12v To Provide A Child is that this child wants to right style warns what is the parents to Style Destroyed in Guinness World Record Okay That's Grade What One of His Children Wants Such a Big Boss Is Channel Bond Spirit Provided Listening to Them to the President The President Will Not Get Covered and Sleeps Unfortunately Not All Most Vikram The Provided to Stay in One Survey Note 349 Also IS TO PROVIDE A PLATFORM FOR CHILDREN WANT SO IS PLATE MIDNIGHT FOR CHILDREN WHOSE PARENTS TO PROVIDE OK CO SPIRIT HAS TO COVER ALL THE CHILDREN'S PARENTS TO PROVIDE FOR PUNE WEST'S ALL RECORD BREAKING PLATFORM AT NIGHT FOR NOT TO FAR AWAY NOT WANT TO PROVIDE NO Wash Your Knowledge 400 To Have Only One Child Does No Other Is The National Slider Channel But What About One Should Not Want To What Is The State Of To Subscribe 9910 To Back To 999 Provide Enough To TOO OK WHAT DOES NOT PROVIDE THIS OK WILL NOT WASTE NOW WE TIER TWO INTEREST FOR QUITING AWARD FOR IT'S OK KNOWLEDGE 2012 DECIDE The Video then subscribe to the Page if you liked The Video then subscribe to the phone number vaccine picture earthquake three main one who provide chhattisgarh cover for it's going to cover for it's good to cover a put ok what is the state of 851 child were destroyed in this box in it's not the Child Rights on This Date of OK Special 110 Not Want Vaccinator Not Want Vaccine Vikas Getting Ours It's Getting Award Best and Adults Only To Provide Active Voice and Dignity Pride Vikas Notice Children Want Vaccine Only Children Want Any Instrument Sonth Na OK State It's OK Now In northwest vaccine characters knowledge decide versus from 7 m and just make little bit of a wide variety of 11th president 00966 217 files ok since one channel bond all active window into effect from the provide is because deprived youth from vaccine well educated vikramark provider six Strong Subscribe Discovering Research Covering For Sit And Good Cover For 8n More Cover Flip Ke Election Ladoon Sallu-Cat For Cover Flip Ke Election Ladoon Sallu-Cat For Cover Flip Ke Election Ladoon Sallu-Cat For Forest Getting Provided By 6116 Forest Navodaya Children What Is The State Of And On This Occasion Advocate Phase Country Note 510 Boxing Swar 3315 Vaccine Ventures her neat only one channel wars than he to provide such s to provide a is to iron profile picture unwavering back cover for party cover for one what is the number of china solve that provider switch off and virus more than 12345 favorite suicide providers in som They can servi 12345 price 167 condition is see a child and parents to provide ok mails and support this will decide the state of parents provide when is the child don't see the child actor award ok but every child is in which is protecting details in child that This protesting ok style squaring off of parent what is the state of parents ok a girl who tells you are too return value of tourist unwanted ok so what is this si ki saugandh kaise clear for first how very simple style want parents to provide Scene for a child soil in parents its just visit to return want to know which children of president for example it's ok love you of parent and say that children flat se bodh children are returning ok bodh children rodi good tightening ok indicates what will happen In such children not provided important dance class children and ok birthday not provided in this water but parents mil raha tu cover for itself but superhit full of written taste and don't ok parental of written taste and only take one example hokar late se dress Hum Note Like This Us Net Se Whatsapp Hindi Status Hai Laxative Want In Great Swapnil To-Do List Will Want In Great Swapnil To-Do List Will Want In Great Swapnil To-Do List Will Return State Provide Ok What Will 8525 Also Want Water For You For Evil Returns Set Karo Bhai Ok In This Case 2012 Cover For Researchers And 123 Forward Cover for researchers and scene part and marry one month and savior of one month flat also 100% savior of one month flat also 100% savior of one month flat also 100% equal it's something 12323 increase state ok I'll return set ok right activists ok questions getting provided for by both assistant 1483 military getting award for what Will Speak To What We Say To 9 6 What Will 606 Will Say It Won't Say Vaccine Bigg Boss 6 Of 6 Return From Previous In This Post No Destroyed In Riots Infosys' Very Destroyed In Riots Infosys' Very Destroyed In Riots Infosys' Very Important Ones And These Are Is Style Se Tanning Okay Is Style Us OK But Styles Not Provided For It OK Child Not Provided To Six Sworn In All Things Sweater Sixes Wanted Cases Will Co-Operate Unwanted Sponsor Cases Will Co-Operate Unwanted Sponsor Cases Will Co-Operate Unwanted Sponsor He Got To Coordinate Su So Have Made Available Vaccine Shrink 207 College Function OK It's A Lip Simply Qualification Function But will return the number of excellence award father root that and finally after returning from the is function Twitter number vaccine facility available option at midnight number of Galaxy S2 ghrt so let's write the function works in solid state chemistry function note star as superstar all Very simple country's best this roots null indicates what is going to happen in that case weakness return what we can be done in return to this channel as a result there is a problem put ride through tunnel ok what will oo first form will get input number child Will see what is the what are the children requiring pathetic vaccine superhit absolutely we children in the a spring left with inputs from the left and were quite left with inputs from the like share calling bright ok no weir check is military for children want to vaccine here Left Advanced Vaccine and the Right Channel Bond Subjects in That Case How to Provide for What We Can Do in That Case Number and Vaccines E Will Be Intimated Because They Are Going to Promise and They Also Written Provides Relief in Your Mind And Want To Give Back Synthroid OK What Is Wealth Case And Shifted To Water Residues Cursed Child Want You To Provide Style Stroll In This Case And Sacrifice Will Provide And The Right Way To Provide Any Five Children Must Provide Information In That Case I'm OK In That Case How Can Return Okay What Is The Last Cases In The Last K Swarnim 12812 Return I Need Active Voice And Want To Bed Scene I Safe Second Sample Code State One More Thing In This Crops Cheese Walking 200 Give Natya Rate Bhi Root Bus Simple Spelling Mistake Pregnancy A Co Switch Working So Patient Cases Note Handling What Is Not One Simple Case C Water Sample K Select A Ka Very Simple K This Show What About 10 Simple K Just One More Night She Wandered What Is Going To Happen That's Why Seven Mode What Will Function Tourist Destinations Custom Input Late Se Uses Of One Month Pregnancy On WhatsApp Main Ye Soch Returning To Problem For This Is My If Output Is Robot Expected To This One Was Not Working For The Very Simple Case See What's Happening Is In This Case Water Between Vijay is that simple want equal to college selected for B.Ed college life to college selected for B.Ed college life to college selected for B.Ed college life changes and both office children also assured return ok very office children are turning ok rate in this case was happening bodh children returning ok bhaiya returning want to CEO children are ok morning returning Minute Want Let's See What The Fish Children Are So Friends That Is Channel Were Returning Okay Know What Will 121 Toilet Right Visarjan Simple Best And Worst L Into His Parents Want For Watching Per Dres No Apparent From One To Provide Detoxification One Simple Single Road Sugandha Not Have parents one is and favorite superhero draw your parents to provide for you in this case you also how to check quick indicator country check just my channel bond all excellent system God father has to provide for rent in that case will also increase number and vaccine for Child Stars Then And Now He Will Return To This Case You Still Want To Vaccine Rights In That Case Will Help Innovation And Not Be Perfect 102 Yesterday Morning Office Aapne In This Case This Year Greeting This Is Give me your WhatsApp number to cross the given semi this year let's tell him madam situation in Facebook in scientific soon good
|
Binary Tree Cameras
|
beautiful-array
|
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0`
| null |
Array,Math,Divide and Conquer
|
Medium
| null |
44 |
hi guys welcome to leeco 44 um we're gonna do wild card matching today so I actually think that this should be one of your first DB questions that you try especially if you have not yet tried number 10 regex matching because this is a bit simpler so given an input string s and a pattern P Implement World Cup better matching with support for question marks and asterisks where question mark matches any single character and asterisk matches any sequence of characters including the empty sequence the message recover the entire input string not partial so s will contain only English characters P only lowercase English characters including question mark and asterisks so some examples AA and this matches because this one can match any sequence a and a does not match CB question mark a question mark lecture C but B does not match a okay so this is a dynamic programming questions and basically the asterisk makes things a little bit more uh complicated and that's where dynamic programming really helps because effectively if one character is an Asterix all you have to do is just either match the current string including the asterisks with the other string minus the last character because the X-ray can match any sequence and you the X-ray can match any sequence and you the X-ray can match any sequence and you can keep repeating that process until the other string is basically empty uh or consists of only like one character which match yeah basically when it's empty so you just keep reducing the characters on that front or you can pretend that this asterisk doesn't exist and you compare the remainder of the string pattern p with the current string and see if it matches so those are the two possible ways and effectively once you get that there's really not much else so let's just go ahead and Implement that really quickly and I'll explain along the way so what am I doing here so I'm creating a 2d DP array and the starting position 0 will be true what does this mean it just means that it um the starting position is true so uh basically because empty string empty button is matching so now let's look through the uh string and um s is the input string and uh what we need for the input string is um to measure the empty string and basically uh you can just add false DPS because you'll always be not matching now let's add let's do it for the pattern now for the pattern if it's equal to the this is a slightly tricky but if it's equal to an asterisk what you need to do is just pretend the Asterix doesn't exist so it was just an asterisk and an empty string it will actually match so you just need to match it with the preceding character of the P string before index I so if okay and in fact you can just add it here and dp0 and I believe it's I yes it is because we're adding the I plus one position sorry very important don't get this wrong now apart from that just push Fox okay the thing about this question is that it can be a little bit tricky if you make a typo error because I and J look rather similar so do be careful about that so as again represents the string so now we're gonna do a double for Loop to populate the rest of the DP array so just remember we're always adding the I plus one and J plus one position because we already have the initial vertical and horizontal columns filled out so that can be true um and basically uh now that we have that what we have to do next is this is true hang on relax wait sorry this is supposedly false so if so are the conditions that can change this to be true or to another value that's not false so basically if s at position I equals to P at position J or P at position J equals to A question mark then we can just set this to the proceed the preceding value minus uh minus the current value because the current value is going to be matching effective because question mark would match any characters and or if the seven characters single characters I'm matching so we just remove that and then just take the ones remaining fairly straightforward so the tricky thing is what happens if PJ equals to a Asterix so you match any sequence of characters if it's equal to asterisks right so what would you do in this case so effectively again same thing fortunately for us this is quite simple but before we write the code actually what we should do is try to understand what's going on like I said at the start earlier if you have a asterisk character you can remove it pretend it doesn't exist so you can just compare it with the J position so DPI plus 1j because that is the existing s string with the better minus the asterisks or you can take out the last character of the S string and compare the current pattern P because you can just effectively assume that sequence is matched so you just need to match whoever's preceding it with the current pattern P if they were all the same character let's say AAA and then you have Asterix the S3 can match the whole thing because you can match any sequence or characters but even if it was ABCDEFG so you can just compare minus the uh the I plus one character of the S string so it can be i j plus 1 or what we mentioned just now DP I plus 1 J and that's basically it so now the final value in that VP uh to the array the very last value will be the answer so let's run it on our test cases first and that's basically it thank you so much have a good day bye
|
Wildcard Matching
|
wildcard-matching
|
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where:
* `'?'` Matches any single character.
* `'*'` Matches any sequence of characters (including the empty sequence).
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "\* "
**Output:** true
**Explanation:** '\*' matches any sequence.
**Example 3:**
**Input:** s = "cb ", p = "?a "
**Output:** false
**Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'.
**Constraints:**
* `0 <= s.length, p.length <= 2000`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'?'` or `'*'`.
| null |
String,Dynamic Programming,Greedy,Recursion
|
Hard
|
10
|
406 |
Hello viewers welcome back to back design this video will see the curious construction by height problem wishes from list co de take of the june challenge so let's not look at the problem statement the problem yes-yes that is supposed to have randomly problem yes-yes that is supposed to have randomly problem yes-yes that is supposed to have randomly stop people standing in A Q and Subscribe Where is the height of the number of people in front of the record to my channel Subscribe Number of people in order to get list of years ago When and Where is the number of the Subscribe and do you want To convert others appear in its correct order Fennel User Defined David Value or Elements of Obscuritism subscribe The Channel and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Page 20 This is not address correct position so they want to Make the come to the correct position after which make a call to the current position Answer and Result You can see the first elements of elements The Video then subscribe to the Page if you liked The Video Understood Problem Statement Notice Simple Approach Which Comes To Mind After Reading This Problem When Most Of You Might Think That We Need To Short To Find The Solution So Let's See How Can They Apply For Doing So Will Solve Verification Se Veer Is Not Increasing Order Cancel Simply Not Giving Say This Is The Current Elements And Subscribe Button To 110 To 120 Subscribe Will Not Take Care Of The Position Of So Lets You Watch Technique Can They Apply For The Next Question Is How To Play The Element And The Current Position Sovereign Debt Simple Shopping Will Not One But Will Need A Two And Three To Make Corrections In Order To Find The Song Of The Way We Must Be Thinking Will Welcome To My Video Have No Place For Elements Half The Number To The Laptop Subscribe Skin Problem Remember R Problems Can see this element subscribe button 68 your show this is it correct position also want to place all elements correct position in the second value 10900 coming into picture processing elements in ascending order where what is the future events will have to think what is the Current Element This is the most important Important observation and you will come to know which will give one another in ascending order The Video then subscribe to the Page Second element day in this case for the person having same hurt but boys take and valued for 100 off The Person Having Same Value And Listen This Is Value Ander Least One Person With Great Benefit Video Please subscribe and subscribe the Shyam Or Shyam 250 Setting On The Pending Voters Member Shopping Computer Function In This Case Ponting The Repair In Ascending Order No Latest Channel Ko Subscribe The Channel Processing Very Carefully And Welcome To 9 4 Process In Which Is The Elements And Will Have To The Answer Is The Position Subscribe Will Contest Which Will Win Weather Second Wali Cheez Heroine Discuss Novel This Post Element And Wear Dresses So Can We Please 3000 Subscribe Position Placid Under 10000 subscribe to the Page if you liked The Video then subscribe to the Page Position Zero Vacant And Wakefield Bhai Software Element And Yours And That Is In Ascending Order And Displaying Specification Future element Sincere processing from left to right in the air element will be capturing disposition and 16 2009 2013 The number of element subscribe in this post will be consumed by a great value subscribe The Channel subscribe position and subscribe now to receive new updates reviews and News 500 first of all the second value will be stored in this account and account will be to 910 indicator of but exactly to elementary ghr think they should win against three from the element so will this element places where already subscribe 4,320 299 places where already subscribe 4,320 299 places where already subscribe 4,320 299 plus 2 and this Position in the Twelve Rubs in this Person Was No Significance for This Element Rule 231 Amity and Need Exactly Two Elements Greater Request 400 Will Have to Script Deposition Before This Will Be Occupied by the Elements Including All Elements of Obscuritism Subscribing This Cream and They Will Have Already listen subscribe button this position is this position number 90 element two click subscribe button on front side investment or skipping no veer montu jis position 39 can they play this point to 8 this industrial so they can directly twenty-20 industrial so they can directly twenty-20 industrial so they can directly twenty-20 width correct position after MP And Values 06519 Will Give One To Three Do Serving Process From The Big For One Element The Left Side Of This Current Position Is Velvet Dainik Musaddas Element Versus Account Is Vansh Will Decrement The Mountain Means That disposition to move to the next position no this and tourism place so 1200 placid its position 1280 subscribe The Channel Please subscribe and subscribe the Channel Time People Shopping Operations in the Time Complexity of Apne Soldiers So Let's Not Look at the Code Source Code Wear Give us tears in these people here nor will find the number of people to return and will be taken away all the positions of the way do subscribe my channel element from sydney with love for all elements in the answer key value other element which is the current Do n't forget to subscribe to the element and you will also come to 90 countries 80 places where you can place the current element at index of the answer OK and placing limits Thursday Must Subscribe Like Share and Subscribe
|
Queue Reconstruction by Height
|
queue-reconstruction-by-height
|
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`.
Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue).
**Example 1:**
**Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\]
**Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\]
**Explanation:**
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue.
**Example 2:**
**Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\]
**Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\]
**Constraints:**
* `1 <= people.length <= 2000`
* `0 <= hi <= 106`
* `0 <= ki < people.length`
* It is guaranteed that the queue can be reconstructed.
|
What can you say about the position of the shortest person?
If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
|
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
|
Medium
|
315
|
1,707 |
Welcome Back Price Today In This Another Problem From Liquid Maximum Which Ribbon Element From Railway Sudesh Problem Appeared In Till Hottest Flat Solving Problems Aa [ Hottest Flat Solving Problems Aa [ Hottest Flat Solving Problems Aa I Soft Paul Will Replace Yagya Ne Chief Secretary For Negative 2000 Introduction Of Intelligence Hey And Festival Maximum It Well exam value one side element option names and not fixed amount yadav what is the answer is maximum 600 website for all ji sach ka number chahiye 10.27 equal elements sach ka number chahiye 10.27 equal elements sach ka number chahiye 10.27 equal elements in the mi-8 dabang jabardasth hit aur end jerry in the mi-8 dabang jabardasth hit aur end jerry in the mi-8 dabang jabardasth hit aur end jerry answer don't like very short and soil Parliamentary Affairs and Shows In this problem we have basically made two tractors, one is named sweater and one rains. Poonam has given us number of elements in sweater and given elements and one has given only one in various factors. Leave a Comment What we have to do is that we have to take all the numbers which are Ladakh like and from all those numbers we have to take out a coin and from it the maximum value is coming Maximo 1000 which is coming with numbers of I want that. If the problem is basically Shimla then maximum 1,000 and two elements are shown in all this 1,000 and two elements are shown in all this 1,000 and two elements are shown in all this Vaseline with upon its very easy doctor sir, this problem is otherwise you should be familiar, I have already made a video on this, I will put its link in the description, you can watch. The video the year and compact is the problem okay so this example dekh lata hai so what is in the example that we keep less more and this is that Z inside this we have this excise a second mobile okay so first of all what we did is that Tension from Vansh is equal to two, we have to make all of them ignored then one to glue gun and equal to two numbers are in tap 07000 exam free and 103 so our maximum in this is three either Ansal [ __ ] our maximum in this is three either Ansal [ __ ] our maximum in this is three either Ansal [ __ ] husband alum ok now second Korea Harivansh So in this, whatever numbers are smaller than three, we Aghor to Ra-One, this dynasty has we Aghor to Ra-One, this dynasty has we Aghor to Ra-One, this dynasty has 124 1811 maximum felt, one Sutan Services per second billing, now there is no third person, what is there in this, we have fiber anger, so whatever numbers are smaller than six. No. All of them in a 100 g with five to the maximum level of them is the tunnel for America and 5105 2 eggs and 5305 volume the maximum value is strict 2600x and example respond so example so clear how to do it so it is soaked Mintu and the solution is very easy, that is, if we are looking at the idiot insulation, that is very simple that you have given in the question, then we have to solve it in the same way and the wicketkeeper has to do it, so what have we done for each quality, it seems that the most First of all there is a request and for every query we have picked up all the alarms which are smaller than my mobile and we have picked up all those elements which are smaller than the above and MMS is so many elements in one. By uniting them all, Alia, we have got one white of ours, this is one of ours, eggs are the number one thing, which has given us the song of this mission and of these two, and of these, we have kept the flowers intact in the answer. Keep that gas problem love yourself into his approach skin is very easy but is this video approach is it a better approach than this then better approach is given stand solving and end login plus b Gautam login suicide of end login facebook login solution So for this, first of all the prerequisite is we should know how to solve this question of Maximum But a video has been made, you first go and watch that and then after that, if you do this video in quantity then you will understand the hundred percent solution. Price is 220. You will get the link of the full video. Soft toys in this video which are blood to elements in an all in internet are 250 you. To understand the solution ok so first of all what do we have to do so first of all we have to leave the number then ok you send it to Korea and there are streets inside turn it on so that Hindu hairs are destroyed then after that we have to What has to be done is to add that value of salt in the rent, let us see our respect, that is, if we are looking at the check very, then in that case ML left saver mode of Junior Kudi is required, respect, loot, mosque, all the elements smaller than that. Phone number is five that they will insult us in their fare. Okay, we tried to insult the elements which are smaller than us, so basically what is left, just like we have calculated the maximum in two elements, the brighter it is for us. For this, a jeweler, because we get the question grace, not all the number elements which are smaller than white, find the maximum number of letters in all the elements from for the volume, so we tried all the numbers which are smaller than us. After making those tracks, we made a variation for the two elements in the matches, like if there is zero, then we try to see if one is available in the note. If one is available for that note, then we first try on this note. Okay, and if one is not available, we will go to the zero one. Basically, we have to see the video on this wicket, so we have got the model of daily life, but if we are not getting the bit, then in TRAI we have to see the video. What will happen if we grind it in the middle? Our Max was engaged and ours was getting it, so let's see its example of quarter inch, the solution which we had done earlier, has given us weakness and has given us a career, so we can convert poison into nectar. If you shift then short and they are this 0123 will you do like this, we have made the very face also soft for the pages Buddha value is ok so by presenting them on thank you, we have made it soft, this is what we have muted this volume, to the sun Now what will we do with us, first we need to run, we have a problem, okay now what happened in school, we spent a lot and my friend's growth in this was tied to whatever number was left, we have weakness 30 minutes 2018 Loosening 121 That Time Got insulted like this, so when we tried in it, a lot of minutes, time triangle of life, now from the try of this life, we have been ignored, method is max, so just we are maximum pride to elements class like we had solved that now okay we have spent the last 30 okay so We check whether one beat is available with us or not, if it is then it is ok. Give vote to draft bill. If not, in the morning it is our compulsion. We will have to go towards zero. We will check one beat. For that weather we have zero also available or not, if yes then it is ok Birbal most do, if not then he will have to go to tweet with similar cases and while doing this, if we get to Mexico, then I will stay with Akbar in So Guys. Feet maximum which raw two elements in were dollar question you clear will noose soldier this approach side for Kantakari of this we saw that also we need point is number because from three we know that we closed all first inside get it basically that review Twenty years but have tried so we had 0123 its mileage again the work that we were doing in The Times and you can approach that photo was all Vivo Adventure Okay so now we set two three and we Have ₹ 1 Corresponding waxing will be taken out Have ₹ 1 Corresponding waxing will be taken out Have ₹ 1 Corresponding waxing will be taken out similarly, what will we do for the third one, we have listed Nikul training element witch mins that get the crime, try all the elements on these sites now and for us five, we will take out the maximum which will verify our Now let's see the code of the problem and call more teams in it. Tell this problem here so let's start. First of all we have a class 9th chapter note asli 102 and listen if you want. Notes on kar do the states of matter bhind tools for issuing write ok so thank you need but try food tester ki tunisia is the child into na ho on kar do om ne Bigg Boss note classification first of all give us an inch and function ignore time which Will also refresh the value, interest time, fix, install 2 green chillies, 1, then the person who wants to join and the sign which is the main tagore, start the torch, play the song, make 432, it needs to be inserted, try to make it on the 32nd. All this understanding is set in the first of all not at all he is busy with this Child of Bell, if it is not that this thing is a tap, then we have to make a new note here and keep it prohibited from it. Okay, and make the roots stronger, go in the next month, turn off the chart of dry father-in-law, go in the next month, turn off the chart of dry father-in-law, that this is ours. The duty of the letters is very simple, now we have to write the verification which will give us the maximum for the particular value of Now we have a point, don't support, that the film is almost a festival, that I will leave my mehendi, then we started the iPod 231, that soon, first of all, we need that Bhagalpur Two Tech School will take extra, we will scan it from above. Now if we have a forest, we have a bed, then we want this Jio, only then during the maximum period you can get 100 respect, and if that is the meaning, then we should become a video, then we should search not work well, this is a height letter that Child of North Side this Yagya is condition form, so we are still in the same, if you give us Lakshmeshwar in it and click on it, the sacrifice will be increased by taking power off, then we will just make improvement on 154 Brahma items left right. If you shift the side then you will be given 125 idiots. Okay, and we will make it more so that one will be erased, so basically till and back incremental power of back to come, ok but if the condition is such that if we do not get it at the point, then our Those boys and you, that ours did not benefit, but we have to pay the opposite bill after some time. MP3 Song - Father Shekhar Suman and MP3 Song - Father Shekhar Suman and MP3 Song - Father Shekhar Suman and according to the scriptures, up to the elements in Paris, right from here, now from here we just use it. To the functions, first of all we treat the anemic one English, the tax officer service was the guest, he did MP3 ballia chat is loot lo hai with this and I make a vector that we sir install it in the examination date sheet for the etc. Akwari that We will sleep the intake is that we have a verified took her inch extra cloth now skirts and do it and do this now we inquiry this mue 200 banging pints for the second person sam personal for her we a new You will have to go to the mission and hand over the thing to Karke. You will know that now some separate modification has to be done in making this point setting, this ballia. Inside the short function, we can create a separate question and pass it like this and in the function and that. According to that, the result of 200 kings is okay, so let us see, we have put the function, tell the obscene mail from left, text and being to Luta Gandhi, so whose old is it to us that this wave is the lab assistant professor, absolutely soft drink verification upon and drive a The speed of this park us here right no our quality second blast or Ram Charan think just now solve the question let us follow so much to listen to the results and song for full MP3 and many more questions ok and one we have in I Nisha, apart from this, all the numbers of positive elements, lunar qualities of lineage are different, what is this qualification, what is this well, Aamby Valley, okay, so all the numbers of eye lashes are the turning point to that they are from us, the tri-minute one among all of them is here. But if we tri-minute one among all of them is here. But if we tri-minute one among all of them is here. But if we do a mission call with you, then this effect was seen Swapnil Coma Give your suggestions to us too Mishra Don't make us do this and A Time After song is yes ji per we did the routine here especially and to I here we smoke cigarettes that now left Since none of our elements has started yet, then we cannot perform the function. Okay, so from his understanding - it will cannot perform the function. Okay, so from his understanding - it will cannot perform the function. Okay, so from his understanding - it will happen and we have already called the tractor - happen and we have already called the tractor - happen and we have already called the tractor - 110. This letter was coming, so there is no need to do anything. Yes, but if there are some values in our triangle, then what we have are some values in our triangle, then what we have are some values in our triangle, then what we have found out their maximum so far, then what should we do according to the qualities of the end of that second, in this, that mind is accepted because we had installed here earlier, okay, so here we have this index. But let's meet these rallies which make us smile with the verification, we wrote the verification so that this street of love of Sharif is gone, it will go to a nice golden store and here and it is making us a ringtone, our factor A, I will know and see. It is like that Suji Singh Shammi Colony is expected to do it, either let's do this compiler school and after doing this code has not been known or submit it on this that Surya contacted so guys date of birth problem is this. If you get even a little benefit from this video, then like this video and share it with your friends and like this, subscribe to see more videos. Thank you, nice, thanks.
|
Maximum XOR With an Element From Array
|
check-if-string-is-transformable-with-substring-sort-operations
|
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`.
Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\]
**Output:** \[3,3,7\]
**Explanation:**
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
**Example 2:**
**Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\]
**Output:** \[15,-1,5\]
**Constraints:**
* `1 <= nums.length, queries.length <= 105`
* `queries[i].length == 2`
* `0 <= nums[j], xi, mi <= 109`
|
Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering.
|
String,Greedy,Sorting
|
Hard
| null |
1,609 |
hello hi guys good morning welcome back to a new video in this video even odd trade has been asked by Amazon and Bloomberg it's a very easy problem I swear I have not found any easy tree problem than that uh than this one let's see the problem says the problem simply says that we are given a binary tree named even odd and it means the following condition will satisfy the root of binary tree will be at a level index zero which means okay I will start with a level zero then level one then level and so on and so forth okay great and it just say the same thing okay zero it's child one it's child two and so on so forth the level is increasing like this now for every even index level as you can see the level will start from zero then one then two in a simple tree how a level goes in okay I can have a tree like this right uh that tree like this so this is the level two this is level one this is level zero now uh for every even index level which means level which are having even index 0 2 4 and so on and so forth the statement is very important here that all nodes at the level have odd integer value in strictly increasing order so these are two conditions which both needs to be satisfied this question is only tricky because and only medium because of its statement that they are not having and they are having this in condition which is very unlikely that you will see it casually like this means that odd integer value in strictly increasing order which means that at a even level you need to have odd integer value that's the first condition and all those odd integer values needs to be in strictly increasing order again I'm saying all values at a level at a even level needs to be odd then that is odd okay next is that all the values if they are for sure they needs to be in the increasing order and the same way for uh for odd level index that all the values should be even which means in at this level one level three and so on so forth all values should be even and they should be in strictly decreasing order so for sure we talking so much about the levels and stuff and okay the ultimate aim is that m i mean the ultimate aim is that we are given the root of the tree and we have to return the true if it's actually a even odd else WR or false now as we're talking so much about the level for sure one thing stri in a mind that Arian we will go level wise so I will initially have a level of zero see to go level wise we know that we have a BFS algorithm now if we want to go levelwise if you have a BFS algorithm we will go okay at the first level I will have okay I will keep track of the level I am at because in BFS you go on the level wise so you can also keep track of at which level you are and if the level you will do a level more two right if that thing is a zero which means the level is even else it is a odd level now if in even level you know and in a BFS you always iterate level wise so you will have in the Q all the elements which you need to pass for that level then you would have all these elements which you need to pass for this level you just have to do one check that all these elements should be odd and other thing is that when you are iterating on all the elements one by one just keep on checking that it should be okay if the level is even then all the elements should be odd and it should be increasing which means that current element should be greater than the previous element right if the level is even if the level is odd because here the level was even here the level is all odd then all the values should be even and also it should be strictly decreasing which means current should be less than my previous R in what is previous you can by default put the previous as some like for even you can put the previous as by default very some very small value and for odd you can put previous as very high value again we'll see how this everything will happen but this is that okay it should satisfy for all the levels but I have to return true and false so okay we can have it one thing that at a even level which means when the level is even I can do and that's the reason like my writing is so bad that I have to write it prehend PR hand but that's but this question is pretty easy so we can actually see that now for a even level we saw that okay all nodes in that level should be odd and my current should be more than my previous so I can just simply say that either uh my any node becomes even in this level any node is even then simply return false or if my current is less than equal to my previous then I Al then also I can return a false and the same way for this specific when the level is odd I said that all nodes should be even and current should be less than my previous then I can say okay if any nodes become if any node become odd at the odd level then I can simply return a false or if my current becomes more than or equal to my previous then also I should simply return a false and ultimately if for every level which means even odd and go so on so forth if none of them return returns are false ultimately I can return a true and that's the only thing which you have to do let's see with the example itself so you can see in the first in the queue you will have these elements again you know how a BFS is traversed if not then just write on Google on YouTube that b graph series by Adon and then in that you will easily see that you have taught BFS DFS very easily and again if you have been following us so for sure you must be knowing BFS DFS for sure if even if it has been a month even if it has been a week also you must be knowing for sure now uh coming on back to that we will have we will simply push back this first value then in my CU and I will have to rate okay it is odd and also it should be strictly increasing okay next level I'll keep TR of the level itself okay level is odd okay all the values should be even and they should be strictly decreasing also that also good so here I will take previous as something as int Max right here I'll take previous as something as int Min and does I'll keep on checking okay for the next level I want all the Valu should be odd and also it should be strictly increasing so here also previous is inmen and then strictly increasing and for the last level which means level three again I'll keep of the level number also because I need to know what level it is at now previous is again uh my int Max and it should be strictly decreasing and you can see this decreasing so for every of them it never return a false again false condition to return is this one which we saw here it never written a false so for sure it's a true now uh what can be a case when it return turns fall so you can see for this specific level uh okay that's great it's odd value and strictly increasing uh it's even value and strictly decreasing H it's odd value good but it is not strictly increasing sorry bro uh answer is false okay uh for this value okay uh level zero even level odd values okay great strictly ining great uh okay level one needs it needs to have even values and stly decreasing okay even oh bro it is odd values sorry bro not false so anytime you encounter some a condition which actually makes your everything false simply return false itself now the code is exactly very same of that of BFS that firstly we grabbed the queue and pushed the front like root of the que which means the top node of the que and then I will have is even because I know that in the very beginning my level is zero so is even is true this is the level is even is true next time I'll just flip that I know the next level will be odd next level will be even then odd even odd so rather keeping the count of My Level I'll keep okay even and then you will see next time as soon as I will where it is going yeah next soon next time as soon as my next level will come in I will flip my even it is next level will be okay opposite of the current even is even if the is even is true in the very beginning next will become a false next will become a true next will become a false true false okay cool uh now when now we will do a simple BFS traversal in which while your Q is not empty you grab the size of the Q why the size is required because we want to only pass that specific level node that's it because what happens in a que is that if you are using a queue and at the current level you have let's say these three nodes for example these have all these childes so you want to only pass this specific level but when you will pass the first node now so you will push its child also in the queue when you will pass this note you will push all the child of this also in the Q so what you see is Q kept on increasing while you are parsing the Q itself so you have to firstly before even starting to pass you have to restrict the size of the que that bro only pass this specific thing this is the current level next thing whichever is coming in is for the next level not for this level so I will just simply make it stop now um I have the size I of the previous as I showed you but I also said that previous entirely depends upon if it is odd or even level which means um if my level or if my level is even that my previous is inin else it is int Max so I am keeping track of my level is even or odd by this is even so I can simply say if my is even is there then my previous is inin else it is inax right okay then I will iterate on the current elements of that specific level which means while my size is not equal to zero I'll grab the current element simply pop it out and then I told you the condition for fals can be that okay if it's a even level and the node is also even because you remember in the even level okay if I go above in the even level we want the node should be odd and the current should be more than previous so any condition which will not satisfy which means at the even level if the node becomes even or if the current becomes less than equal to previous then anything I will return a false so I'll do exact same stuff that if my current level is even and my current node value is also even or again this is or it becomes less than equal to my previous which means my current value becomes less than equal to my previous then proo simply return or false and the same way for odd if the current level is odd and again if the current level is odd I expect the values to be even and a strictly decreasing order but if the value become odd or it becomes in strictly it becomes in increasing order bro sorry bro return or false and if not then simply assign your previous node to the current node because you will simply move on so previous assign to the current node that it can actually move on because you cannot um now uh what will happen is that you will Che okay if you have a left just push that left node in the queue if you have a right just push the right node in the que and simply you will keep on moving and that's it's a simple BFS traval with a slight add like addition of a condition which we have put in here and here we need a previous which is a condition added we need a level for which we need to know the level is OD or even and we just need to pass that level and just to know okay previous and level we'll just use that to find out if it is a odd even tree or not and ultimately please make sure to reverse the sign of is even because next node will be opposite parity of the previous node and ultimately if you had never encountered a false above simply true and that's how you can see the time is o n space is O of n also again now this question you have solved it's the most intutive way to solve this because the problem screams of BFS why it can also be solved by DFS also if you want you can try it and comment down the approach below if you want to solve it by DFS but I did not teach the DFS approach because of the reason that it's highly intuitive not to even think about DFS in this approach cool thank foring oh yeah if that would be great if you can explain again not even just the code also a slight explanation of how the DFS will work because for the community people should know okay how the DFS can work and also uh how you can actually Implement that bye-bye
|
Even Odd Tree
|
find-all-the-lonely-nodes
|
A binary tree is named **Even-Odd** if it meets the following conditions:
* The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc.
* For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right).
* For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right).
Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._
**Example 1:**
**Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\]
**Output:** true
**Explanation:** The node values on each level are:
Level 0: \[1\]
Level 1: \[10,4\]
Level 2: \[3,7,9\]
Level 3: \[12,8,6,2\]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
**Example 2:**
**Input:** root = \[5,4,2,3,3,7\]
**Output:** false
**Explanation:** The node values on each level are:
Level 0: \[5\]
Level 1: \[4,2\]
Level 2: \[3,3,7\]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
**Example 3:**
**Input:** root = \[5,9,1,3,5,7\]
**Output:** false
**Explanation:** Node values in the level 1 should be even integers.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 106`
|
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
563,1005
|
1,248 |
hello so today we are doing contest weekly context of fleet code we click on tax 161 and one of the problems is this medium problem called count number of nice sub arrays and so the problem says that we'll get an array of integers nums and an integer k and we wanna and the definition of the sub array we call it's nice if there are K odd numbers on it and we get the number K as input and when I return the number of nights sub arrays with using this definition of nice alright so for example here with this array week a call to 3 so sub array is nice if there are 3 odd numbers and here the only three sub arrays with three odd numbers are this one where you have three ones in this one where you have three ones also in three odd numbers yes this one in this one so basically this one and this one doesn't have any odd numbers and so there is no separate with one odd number so return 0 this one there are 16 you can see there is this there is for example K equal to 2 so that is this one there is this one and that is this one you get the idea there are a lot of them so anytime you have the start and the end of the array that are different we need to count it so let's say how can we solve this problem so these are the constant and now let's see how can approach this problem okay so let's see how we can solve the problem with this problem so I think the first thing we should do is just take a look at some examples and see if we can get an intuition of what we need to do so the first example was the array 1 2 1 and K was equal to 3 right so if we look at this here what we have is that k equal to 3 right so we need 3 odd numbers so this array definitely has 3 odd numbers right and this array also has 3 odd numbers right so does this tell us anything well we know at least that we need to somehow count we need to count the number of from the number of odd numbers in a range right because here left is here and right is here and here left is here all right he's here and arrange some kind of wrench left and right now let's take one of the other longer example so let's take this 1 - 2 - 1 - 2 example so let's take this 1 - 2 - 1 - 2 example so let's take this 1 - 2 - 1 - 2 1 & 2 1 & 2 1 & 2 and k is equal to 2 so this is example 3 so if you look at this you can see that we are looking for 2 so this one counts as one of the sub arrays then we have this one and then we have this one containing the first element and then we also have this one because it has two and this one has two right is there anything else that is missing here yep so also this one the ones starting from here to here in this range and this range sorry you get the idea there are a lot of them this one and this one so there are sixteen over all right so you can see here the count here is a lot so basically one thing that we know is that so one thing you may have noticed here is that when we reach at this one where we have to add numbers we not only counted just this one or just this one right we counted all those that had zero add numbers as a possible start of our sub array but our ending has to be this but all those before it that has zero odd numbers had to be counted and so one thing that may help us figure this out is what we want is to find out so basically what we want is for every position so for every position I we want to count the number of sub arrays ending at that position right ending at I that have a Magnum LK add numbers that have K add numbers right so basically one account for this case one account for each position I want to count the number of sub arrays ending at that position that have to add numbers right and so ending at I but not necessarily starting at the zero right so they may start at one they may start at two like this one here and so to know how many add numbers in a range let's say left to right like this we will need less coal this one let's just give this one inebriation us a number of odd numbers in a range right let's call it this abbreviation left right so in the same way as prefix um this here is just equal to if I draw this like this and let's say we are at a range where we have here left and here right and here zero so to get the number of odd numbers here it's just the number if it was some it would be the basically if it was prefix Sam right let's say the sum here was 8 and the sum here was 4 right to get the sum here we just do 8 minus 4 right the same way with odd numbers right and so the kind of formula here is that the number of odd numbers in the range left right is equal to the number of odd numbers in the range 0 to our right in this entire range minus the number of odd numbers in the range actually just to simplify this let's just call this the F function f so the number of odd numbers in the range left to right L - L is the number range left to right L - L is the number range left to right L - L is the number of odd numbers from zero to R minus the number of odd numbers from zero to L minus 1 right the same way with prefix sound so this here we can keep counting the odd numbers so with a for loop for all elements in the array we can keep counting the add numbers right you can keep a variable that just checks if the number is odd counts it so that we get at each position I like which is the ending of the interval we would have count add as the number of odd numbers so far and let's call this one X right and what we want exactly is to find the ranges that have K odd numbers that what we want is all ranges that have a odd numbers so what we want is for this value here to be equal to K right since this value is the number of odd numbers in a range right so overall the formula work that we are looking for here is and we should check this only if the count of odd numbers is bigger or equal to K because otherwise we there is no arrange there is no prefix of the sub-array that will give prefix of the sub-array that will give prefix of the sub-array that will give us K here because in order to have like k equal to some number minus a number here you need this one to be bigger or equal to K so that here can be only 0 or 1 or 2 you can't have a sub array of with -1 odd numbers right so this one with -1 odd numbers right so this one with -1 odd numbers right so this one has to be bigger equal to K and so what this means is what we are looking for here is what is the we need to when we reach bigger equal to K we need to find the number so we need to find the number of previous positions that if we start from that position and end at I who will get K odd numbers if we start from it we will get care okay odd numbers right and this basically here means that X is just count odd - okay right and so just count odd - okay right and so just count odd - okay right and so basically what this means is that when we are looking for let's say k equal to 3 right and we are here at a position I and let's say our count odd here is equal to 6 right we want to find all the prefixes right all the elements in this prefix here that have what 6 - prefix here that have what 6 - prefix here that have what 6 - okay let's make this a little bit clearer so let's say k equal to 4 that have to add numbers and all this position if we start from them we will have a range so let's say here we have to add numbers but then here we start having one odd number right we want to count all these position all these sub arrays because all these sub arrays will give us 4 odd numbers right and so this is cut so you can see here it's very similar to the prefix some problem and so what does this mean so this means is that we need to keep track of the number of positions that have XR numbers right and this basically will help us in a way where when we reach a position that has I that has count of odd numbers bigger than or equal to K we can just say okay just give me all the positions that have this number of odd numbers and all these positions my sub array can start from and end at I and I could just add that to the result I'm looking for right I hope this is a little bit more clear so the code from that would look something like this so it would be really simple we need the map prefix so we need a couple of things a couple of variables so code so the variables that we need are counting the odd numbers so far right so counting the odd numbers so far which would start as 0 right so this here would count the number of odd numbers so let me just here put thee the variable definitions of odd numbers ending at i from 0 to the current position so this is basically odd numbers so far in the entire array so this what would allow us to get this here F of zero to our right and so and then we need the prefix map right so prefix here what would be so prefix would be the number so prefix of I would be number of prefixes of the array basically the number of sub-array basically the number of sub-array basically the number of sub-array starting at zero and ending at some position of the array that have I and I numbers that have I add numbers so this basically will allow us to just take prefix of count add minus K right and so we have that map now we just go through the array so for I in the range of the length of the array and what we'll do is we will say okay at this position we know that we have I add numbers right and so that would be what some so what I'm doing here I will not consider the current position right so prefix a number of prefixes of the array that have I add numbers and so here that means that my prefix of count add the number of odd number so far increases by one right so basically if I have an array like this where you have 1 & 2 so here so basically I'm have 1 & 2 so here so basically I'm have 1 & 2 so here so basically I'm doing I minus 1 just for the because array start at 0 but here at this position 0 so prefix at position 0 so at this position here my prefix of 0 add numbers so I have 1 array that has 0 add numbers before that position now when I go here now I already have one add number here so the prefixes just before that position that have 1 odd numbers that's just 1 does this here and then when I moved to this position I would have prefix at position so prefix the number of sub arrays that have to add numbers I would have this one right so that would be 2 so we get the idea and so I will increase that and then I will check if the current element is odd so that means equal to 1 in that case I will increase the count of my odd numbers so that the next time I can say that there is one more position that has for example two odd numbers so we'll increase this so plus one and then when we reach so as I said here when we reach a count that is bigger equal to K that means I need to count all the previous sub array or the previous starting position of the array and the odd position I that may give me K odd numbers and so I would say if count of odd is bigger equal to K then let's just keep a variable here of the result right so my result will need to increase by prefix of what I said here can't add mindscape the value X so all the when I'm at position I and I have let's say k equal to 4 and currently I have 6 odd numbers from 0 to I need to find all positions that have to add numbers in the left because if I go up until 1 add number here I would have 5 odd numbers and not four and so I need all those that have to add numbers so the range from that position to I has just four odd numbers and so let's call these so here let's call that X so my X is equal to can't add minus K and what X represents is just this possible starting position of sub-array such that basically the of sub-array such that basically the of sub-array such that basically the number of possible started with starting position of the sub-array that would position of the sub-array that would position of the sub-array that would make sub-array ending at make that would make sub-array ending at make that would make sub-array ending at I have K odd numbers and so that would mean here my result would be plus prefix of X right so X is basically for this case X is value 2 and so I want all the numbers of sub-arrays that have to the numbers of sub-arrays that have to the numbers of sub-arrays that have to add numbers because those are my starting position and anything in between those starting position and I would have four odd numbers and that's pretty much all there is to it at the end I could just return the result I hope this makes it a little bit I hope this is clear but the gist of it is that we'll have will keep a prefix array or a map whichever one you want that at each position would that would count like for like say it will say for one odd number there are two prefix array that have one odd numbers or let's say three prefix array that have to add numbers and then what I would use that for is this formula here where I'm looking for any range that has K odd numbers and to find those ranges each time my account add becomes bigger equal okay I will search for all the possible starting position that will make a sub range that has K odd numbers and the way to look for those is to look for all starting position that have X odd numbers and X is just the difference between the count odd numbers so far and K right because all those I can start from and have K odd numbers and X may be 0 for example if it's the entire array and that's pretty much the gist of this algorithm maybe let's run it on an example just so that it becomes more clear so if I take let me take this example 2 5 6 9 and let's say k equal to 2 so the prefix array here would be or the prefix map would be something like this the number of sub array that have zero odd numbers that's just this one right so one the number of sub arrays that have so this is just this sub array the number of sub arrays that have 1 odd numbers those are just this one and this one right so those are two five because it has just five as an odd number and two five six so that's two sub arrays have one odd number and the number of sub arrays that have two odd numbers those are two five six nine only that one so just one right and so if we were asked it k equal to 2 what do we need to do so we have the prefix here and so our result would first would start only if so we'll start adding to as only one count add becomes bigger or equal to K and that becomes the case here so in the iteration where we are exploring this one would say res plus prefix of X which is X's count add minus K and so count add at this point would be would have this one is add so that's 2 and k equal to 2 so that's 0 so we need prefix of 0 and so that will say just 1 right and that's the case right we have only one sub array that has 1 odd number if we take another example which is mistake for example this one that we have in the input which is 1 2 1 and k equal to 3 so what would happen here is that the prefix array would be something like this so the number of sub array that have 0 odd numbers that's just nothing the empty list nothing so 0 a number of sub arrays that have 1 odd number that's just number of prefix sub arrays that have 1 odd number that's 1 right it's just this one the number of sub array that have two odd numbers that's this position here we have one of them right and then when we reach this position now we have another one so that means here we have two and then when we reach this position we have the number of sub prefix sub arrays that have 3 odd numbers that's 1 2 1 so this one has 3 odd numbers and then now here also we have another one that has and then the when we reach so here it has 3 odd numbers that's equal bigger equal to 3 2 K right so now we need to add our result the prefix of X what is that in this case so prefix of X is just the count of odd numbers so far which is 3 minus K which is 3 also so it's 0 so prefix of 0 here is zero right so at this position we add nothing and then when we move to this position sorry actually this is one because we remember we start from this will start from the first position and so that would be one so we count it as one and then we will move again here and now we have four we have one sub array that has four odd numbers and so also bigger or equal to K and so four minus three for X here that becomes one and so we need to add two rez those of the prefixes that have one odd numbers right because those that have one are Trumble and so we have those that have one odd number so we can start and leave those that have one odd numbers and get to the last one that has four odd numbers so what's in between would have three odd numbers right and so that would be prefix of one that's just one so it would add another one and so at the end we will have our result equal to two which is the right solution here right so we get the I hope you get the idea of this now let's just type this an elite code and make sure it passes okay so I type it the exact solution that we just discussed it in the explanation so we have the count the total count of the result and we have the count of odd numbers so far and then we have the prefix that says at each for each odd number of odd numbers how many prefix sub arrays have that count of odd numbers and so at each position we say okay the current position is the end of a prefix that has count add odd numbers right and then we check if the number is odd we increase the count of odd number so far and if for each account are numbers that exceeds K then we need to look of all the possible sub arrays start that are ending at that contains Kahlan keh odd numbers and this the value here is what we called X right and so we'll look for all the prefix sub arrays that have X odd numbers because all those are possible start of our sub array that contains K odd numbers and we add that to the overall count and we return it that's pretty much all there is to it sort of from this and submit so let's call this a that's okay so that solution passes lead codes here and yeah so that's this solution okay so what's the time complexity for this solution so you can see here that we are doing only one traversal of the array and so the time complexity is just over them right because we are traversing the array only once and the space complexity here we are using this extra map prefix that will contain at most also the number of odd numbers in the array which can be at most and so there's also open okay so another way to solve this problem that is perhaps a little bit easier to understand this is to use the same idea of the prefix sum that we mentioned where when you have when you are looking for some for a certain range you can just take the sum up and from zero until that last index and then just - it with from zero to left minus one - it with from zero to left minus one - it with from zero to left minus one right so what we are looking for is ranges with K odd numbers exactly so what we can do is find all ranges that have at most k odd numbers so that have less or equal so less or equal than k odd numbers and then find all ranges also that have at most k mines odd numbers so anything less or equal to k minus one add numbers and so the value that we are looking for which is this one let's call it ranges so let's call them big are our let's just call them maybe f of so we can just actually let's call this one let's call the first one F of K so at most K odd numbers and let's call this one if K minus one so what we are looking for which is what's called DC J so J we are looking for is just F of K minus 1 right because if we find all the ranges that have at most K odd numbers and all those that have K minus 1 odd numbers what's in between is those that have exactly K odd numbers and finding F of K and F K minus 1 is really easy with the sliding window technique we will just do something like this so if we define our function that gets let's call it f of K so it gets at most K odd numbers then we can start counting so we need something to count the odd numbers and for a sliding window technique who need the start and ending position so let's make them both start at 0 and we need a variable to cut to keep the results count right and so while we haven't reached the end of the array we can just count the number of odd numbers so that would mean we add 1 if the element at position J is odd otherwise we add C we add 0 and then we shrink the window if we exceed what we are looking for right so here at most K so whenever you get a range that has more than K we need to solar say here is I and here is Jay right if this range starts having more than K we need to make K becomes make I advance here so that we can have a possibility to have less than K odd numbers but if we have less than K numbers at that point we need to keep expanding the sliding window so we need to advance our J and that's what we will be doing within this here so but here we need to shrink when we when the count becomes bigger than okay we churring the window so that we can have a possible window that has what we are looking for which is at most K so if this becomes bigger than K that means we need to shrink the window and that means we will need to say so count add we'll need to subtract one if we have an odd number that we are just moving the window away from it so we can subtract it right and so if this is an odd number otherwise we do nothing right and then we advance our window right and just before incrementing J here we need to count the range that we just found so when we exit this loop the count out will be equal to K or less than K right and anything less or equal to K we wanna count it so we need to include that in our range in our result and since we are taking anything that is less than K so anything in that interval AJ so I chain like this we need to get the entire interval because anything if this is like K or less than K so anything in between any interval in between would have also less than K hard numbers so I need to include it in our result here and then we can advance of J and this is just expanding the window and at the end ones who are done reach to the end of the array we can just return the result and we can just reuse this function and return the result we are looking for and so let's code this one and see if it passes Aelita code test cases okay so I typed the what we just saw in the explanation and we just need to call it here so this one will compute at most so number of intervals or sub arrays with at most K odd numbers at most k odd numbers and so we can just call it here to get the what we want which is exactly K odd numbers and that would be just those that have at most K odd numbers and those that have at most K minus 1 odd numbers and anything in between has exactly K odd numbers right and so that's pretty much it so let's run this okay so again a Alice MIT okay so this solution passes in terms of time complexity we traverse the array only once right only once for each color of F and so overall it's too much and because we do two calls to the function f and the function f just has one's traversal to the array and so this is just open in the same way as the previous function and it's better than the previous function because here we use constant space we use no extra space yeah so that's it for this solution and yeah
|
Count Number of Nice Subarrays
|
binary-tree-coloring-game
|
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] and \[1,2,1,1\].
**Example 2:**
**Input:** nums = \[2,4,6\], k = 1
**Output:** 0
**Explanation:** There is no odd numbers in the array.
**Example 3:**
**Input:** nums = \[2,2,2,1,2,2,1,2,2,2\], k = 2
**Output:** 16
**Constraints:**
* `1 <= nums.length <= 50000`
* `1 <= nums[i] <= 10^5`
* `1 <= k <= nums.length`
|
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
32 |
hey what's up guys uh this is chung here so today uh today's daily challenge problem right number 32 longest valid uh parenthesis so this one it's a very straightforward problem but you know it has a several like solutions now basically you're given like a string containing only the left and right parentheses and you need to find the length of the longest valid parenthesis substring so for example right i mean in example one here you know we have two because that and then in example two here we have four because that's the middle four parentheses are the valid substring and if it's empty it's of course zero so there are like several ways you can solve this problem you know you can either use stack you know a node you can also solve it by using the dynamic programming so let's take a look at the dynamic programming right so for dynamic programming you know the at a given location you know at the given like uh index here you know which we need to find like a state transition function so actually the way we define the state transition function is like this we have dpi here right so dpi means that you know the longest right the longest valid stream valid parenthesis right parenthesis you know longest values apprentices ending at i index so basically that's the definition of the i here so which means that you know this one actually starting is it means that you know the ice index has to be a dice string right lighter has to be a right parenthesis because only the right parentheses could give us like a valid uh a pair right so if we define the dp's state dpp function in this way you know so how about the state transition function you know so we have dpi so what is the how about how can we get the dpi from the previously state right so the easiest one is this so we have uh two scenarios actually uh i think two scenarios so the first one is that you know if the s i minus 1 is the left parenthesis right so if the previous one is a left parenthesis this one is pretty easy basically the dpi becomes what becomes a 2 plus dp i minus 2 right so this is pretty straightforward right because we have let's say we have a several parentheses and now we have a left and right so this is i right this is i minus 1. we know that this one can form definitely form a valid pair that's why we can do a two plus dpi i minus two and then this is the i minus two right this because we're getting the sub the longest valid string right because then you know if this one is like the uh the valid one then we can simply uh plus the previously state so the previously uh dp which is i minus two so this is the first case and then the second case of course is the if the s i minus one equal to the right parenthesis so this one is a little bit complicated because you know the so for this one actually we need to use like the dp uh i minus one to find us to help us find to come up with a state transition function so let's say we have this one here we have uh left this one right so for example if we have this one here and this is i right and then the i minus one is it's also a right parenthesis so in this case how can we uh come up with the state transition function here so basically what we need to do is that and we need to check you know with i uh so first we need to check so b with this i minus 1 we have the dp i minus 1 right so the dpi minus 1 means that you know ending with this like uh position what is the longest uh valid parenthesis right so in this case is what so one two three four five six actually dpi minus one in this case is six right so which means that we have like six valid parentheses from here to here and then actually so all we need to check is that you know we already have this one right so if we can if we know if this one is a left parenthesis because you know we already know that you know this part is six right so and the oh only and then if we only if we also know the previous one like in which in this case is this one is the left parenthesis then we know okay so we have another pair right outside of this dpi minus one then we can just do the state transition here because otherwise you know if this if there's nothing here if there's nothing where this one is like is that a right parenthesis then we cannot uh form basically ending with this i we don't have any valid parenthesis okay now only when we have like a left parenthesis like a pair on the other side then we can then we know there's like a valid parenthesis a valid like uh parentheses ending with this i here that's why you know the uh assuming that's the case right so the dp state transition function for the second case is going to be this one dp going to be first we have a dp uh i minus one right which is this part and then we plot we plus two right plus two means this one so we have the left and the right parentheses assuming we have find the like we find in on this position there's a matching left parenthesis and then we pass what we plus the dp of i minus dp i minus 1 minus 2. so what is the so dpi minus 1 is this part right and then plus 2 is the this left and right and this one is here this one is a dp this index is i minus dp minus one minus two right so that's how we uh get this the state transition function for those two scenarios and cool so let's try to code this dp solution first right so and if not as we return zero right else we have the length equals to s and then we have a dp right so at the beginning every place is everything is zero maybe the answer equals to we don't need answer in this case so for i in range of 1 n right because we start from second one because we need at least two parentheses to form like a valid pair right so like i said if the s i is equal to the right parenthesis this is the only time only case that we could possibly get a valid pair right and then the first case is that if the s i minus one is equal to the left parenthesis right so this is the easier case so this one is simply just a dpi equals to 2 plus dp i minus 2 right but be careful you know since we uh we do i minus 2 here you know if it's a if it is this case right i mean we're at i here you know if we do i minus 2 it will be um i minus 2 will become -1 right so that's i minus 2 will become -1 right so that's i minus 2 will become -1 right so that's why we have to do a simple check here uh we do this one if right if the i is greater than one l zero okay else right so else means that you know the previous one is also a right parenthesis so in this one we have to we need to check so if the s i minus d p i minus one is equal to the to this one all right and then we do this d dpi equals to dp i minus 1 plus 2 plus dp i minus 1 minus 2 right but we uh i think this one also have like an edge case here because you know for example you know this we have this one uh here right so we're at i here so this dpi minus 1 is 4 right and the index for i is what is also four right so four minus one equals to minus one that's why we'll so in this case we also need to do a simple check here so if i is greater than dp i minus one and right and this one we do this because you know basically in this case right if there's nothing on the other side we simply skip this right and in the end uh we just return the max of dp right so this one here actually so this is how we get the uh trying to get the corresponding uh position for the current one because we have i here and then we have dpi minus one right so i minus one in this case is four so i minus four minus one is this one it's the is the index for this one and we just need to check if this one is the left parenthesis okay yeah so if i run the code here so accept it yeah so it passed right um yeah basically that's the first solution which is dp you know the uh and obviously the time and space complexity are both often right okay cool that's the first one and the second one is that you know if we don't use dp we can also use stack to solve this problem and so to use stacks to use stack soft problem actually you know all we need to do is that you know we just need to use the stack to track the uh the starting point of the valid parenthesis because you know let's say we have this one uh this one right and then we have this one right so as you guys can see here you know so the first uh valid parenthesis is this one and the second valid parenthesis is this one right and we need to somehow find a way to find to i mean to know the starting point of this uh of each of the valid parenthesis string here right that's why you know we can use a stack basically to keep track of the starting point of the uh of each of the valid parentheses so the way it works is that you know every time we have a we have like a left parenthesis right we append that index into the stack okay and every time when we have like a right parenthesis we first pop that in pop from the stack so okay so basically this is how it works so at the beginning we have a we have the right parenthesis right so we're gonna have like a stack here so the stack at the beginning it will be uh it'll be uh zero okay and then for the for to the second one we have one here right we have one here so basically you know every time when we see like a left parenthesis right we push it into the stack and then when we see a right parenthesis we check if the top one of the stack is like is there is a left parenthesis if it is then we simply pop it out because no because we find a pair for that right and in the end right actually so every time basically when we find like a pair of current right parentheses we can always look for the top one of the stack because the top one of the stack will always be the starting point of the current valid parenthesis right because for example in this case you know we push the right parenthesis they of course the index into the stack right and then we push the left parenthesis and then we uh just the second time when we have like a right parenthesis this one will be popped out right and then the zero basically this zero will be the starting point of the valid parenthesis right so if we use the current index i when we subtract the top one from the stack then we have the uh the valid string right and then again set the second time another elapsed parenthesis pull gotta push into here which is the zero one two three which is three right and then the next one is four right so the next one is the right parenthesis so the right parentheses we see okay so the top one the left the top one of the stack is that like the left vertices so this one is gone and every time we like i said we find a pair then we know after popping this left parenthesis the top one the remaining the top one in the stack will be the starting point that's why we got like a four in this case right so again if we have like another one let's see if we have another left parenthesis in this case so in this case what we'll have we will have like this one we'll have like zero and then we'll have one right we have one and then we'll have two zero one two and now we have three right so three we check so since it's the right parenthesis we check if the top one is the left parenthesis it is so we pop this one out right and then we have three minus one which is two and then four and five again right so we have five in the end we have five minus one in this case one starting point of that of the uh of our the starting point of the value string that's and that's how we use the stack to track the basically the stack the top one of the stack will always be the starting point of the uh of the valid parenthesis string and we also need to be careful with this with the corner case let's say if the if everything is at least valid right so in this case you know this the stack will be empty right so to start to fix this we can simply initiate the stack with a minus one at the very beginning that can solve this uh this corner case all right cool so let's try to call the second one second solution right which is the stack solution so we have stack like i said that we're gonna use the minus one to handle that uh corner case and then we have the answer equal to zero right and then the uh for i dot c in enumerate s right so if this the current string is the left beneath this right and then we simply push it right into the stack else means that is the right parenthesis and then we check if the stack is not empty and the uh the top one of the stack is the left parenthesis since we're storing the uh the index we have to use the index find the actual string right so if that's the one then we do a we pop it out right so after popping it out now the top one of the stack will be the starting point of the stealth string so i've answered dot max dot answer dot i minus stack dot i dot minus one right but be careful so here we also have like a special case which is the minus one right because in this case you know the let's say we have this one here right we have if we have this one here basically you know the uh so okay anyway so basically here we since we have a minus one is another it's not a valid index that's why you know when we check this index this here we i'm also adding like another condition here and the stack this one where the top one is not uh minus one right and this one and then we can be sure okay that's the valid index right else what else we also append right pen i if we cannot find like a pair of pair for the current right parentheses we're also going to append the current i into the stack and then in the end we also return the answer so that's it right okay cool so if i run the code again so this one should also work all right cool so stack solution also works and as you guys can see this one is also like o of n for both the time and space complexity right and so what else yeah so actually there is like another uh better solution which can give us all of one space complexity and basically for that solutions we'll be using like a converse to count the left and the right parentheses you know actually so for this kind of uh valid pregnancy problem you know it's all it's a common uh strategy to count it to basically to traverse this string twice first time we traverse it look we look a little bit from left to right and second time we loop it from the right to left i think i have seen a similar problem for the valid i think that's the valid sub string something like this basically we also we basically we loop through from left to right and then to right from right to left so similarly for this problem you know we can also do a traversal do a loop from left to right basically from if we do a left do it from left to right we keep like two counters like a left parenthesis and the right parenthesis right and so if we traverse from left to right and then every when we just keep uh increasing the left and right parenthesis and every time when the left and right parentheses are the same then we know we find like the uh a valid pair right of the planetary string and so but how the question is so when should we reset this left and right parenthesis so if we traverse from left to right so we reset when the right parenthesis is greater than the left parenthesis which is in this case it's like this so if we have this one and now we have another right parenthesis so now so we have like a valid we have a length of four valid pair right but then if we see another right parenthesis now the right parenthesis is greater than the left parenthesis so which means that no the divided parenthesis stop here right so from here onwards we have to basically reset the left and right parenthesis because there might be another like valid parenthesis after this one right and that's how we do the left to right loop so similarly we also need to consider another scenario which is this one so let's say we have another one in this for this case to in order to find this 4 here we have to do the loop from in a reverse order right from right to left and in this case everything's the same except so in this time when the left is predicted counter is greater than the right parentheses we reset them yeah so i think that so that's the solution light here for the last solution so we have a left parenthesis equals the right parenthesis equal to zero right now we answer equal to zero so first we uh reach reverse from left to right current one is equal to s i right so if the c is the left parenthesis right we increase the left pointer by one right else increase the right uh right parenthesis by one right so if the left point is equal to the right parenthesis right then we know if we find like a match which means that we're going to do a max of the answer after two times either left or right is it works it's okay and then we reset if the right predictor is greater than the left parenthesis right and again right so we reset one more time before traversing from you know reverse order right so i can i think i can pretty much copy that everything except i just need to change the other condition the forward condition and then here right so left to right and then return the answer yeah so that's going to be the last solution here so if i run the code yep so it works right the last solution we only have two for loops so time is still of n but space is of one since we only we're only maintaining two variables here yeah cool i think that's everything i think for this problem see we introduce three solutions right i think for the dp one is a little bit tricky because there are like a bunch of scenarios you have to be considered i think the second one is the most straightforward one since we just need to use a stack to keep track of the starting point of each valid parenthesis string and the last one is it requires a little bit experience basically you know we have to be able to know for this kind of valid parenthesis problem we always do a two loop one from left and one from right okay and then during the loop we keep track of uh two counters and then we update the answers when the counters are the same and then we reset based on different condition cool i think i'll just stop here thank you for watching this video guys stay tuned see you guys soon bye
|
Longest Valid Parentheses
|
longest-valid-parentheses
|
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_.
**Example 1:**
**Input:** s = "(() "
**Output:** 2
**Explanation:** The longest valid parentheses substring is "() ".
**Example 2:**
**Input:** s = ")()()) "
**Output:** 4
**Explanation:** The longest valid parentheses substring is "()() ".
**Example 3:**
**Input:** s = " "
**Output:** 0
**Constraints:**
* `0 <= s.length <= 3 * 104`
* `s[i]` is `'('`, or `')'`.
| null |
String,Dynamic Programming,Stack
|
Hard
|
20
|
1,768 |
we are given two words to take characters from these words alternatively we will use two pointers I and J one by one these characters will be appended to the result paray until one of the pointer reaches the end of word and then the remaining characters will be appended to the result paray let's code the solution now we will create a list for storing the alternating characters and at last we will be returning it as a string we will use two variables I and J initially set to zero now until the end of one of the words we will Loop through the words and then if there are any remaining characters we will Loop through them and append them to the result let's run the solution it's working see you in the next video
|
Merge Strings Alternately
|
design-an-expression-tree-with-evaluate-function
|
You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return _the merged string._
**Example 1:**
**Input:** word1 = "abc ", word2 = "pqr "
**Output:** "apbqcr "
**Explanation:** The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
**Example 2:**
**Input:** word1 = "ab ", word2 = "pqrs "
**Output:** "apbqrs "
**Explanation:** Notice that as word2 is longer, "rs " is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
**Example 3:**
**Input:** word1 = "abcd ", word2 = "pq "
**Output:** "apbqcd "
**Explanation:** Notice that as word1 is longer, "cd " is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
**Constraints:**
* `1 <= word1.length, word2.length <= 100`
* `word1` and `word2` consist of lowercase English letters.
|
Apply the concept of Polymorphism to get a good design Implement the Node class using NumericNode and OperatorNode classes. NumericNode only maintains the value and evaluate returns this value. OperatorNode Maintains the left and right nodes representing the left and right operands, and the evaluate function applies the operator to them.
|
Math,Stack,Tree,Design,Binary Tree
|
Medium
| null |
917 |
reverse the string according to the following rules so all the characters that are not English letters remain in the same position and all the English letters either it can be in the lower case or uppercase should be reversed so written as after reversing it so what the question says is that the given a string press and it contains both the alphabetical letters in which letters and also some characters the characters can be anything whatever they say for any special characters so our task here is so we have to reverse all the English status and whatever special characters is present we have to keep as such in that place itself so if you see this example reverse A and D last and c and b but if you see the next example a with J they have reversed Okay then if you come see this is special character so we'll it will be in that position and yes it has been so next B and I they have reversed it so then C and H being reversed so then you find a special character keep it as such in that position only then B after that here also okay D and G it has been removed so you find a special character keep it as EF it has been reversed as Fe so all the special characters uh whatever we have keypad keep it access only the English letters whatever you find either it can be lowercase or Upper Keys just reverse only the letter from the string so that is this is a problem they have given so as I said when I was explaining the approach itself the problem itself I was pointing to the last uh end elements right so what we'll do is we'll have two pointers okay so on this point here let's say left another is pointing here let's say right so what we need to do until we left lesser than right Okay so until F lesser than right first check if the character presented left position is it a English letter yes how do I get to visit English letter or not is also function in C plus we use Alpha and uh in Java we'll be using each letter function so this is in C plus well this is the same job so first check the character at the position left is a English data yes it is alphabet then check if this is alphabet now check on the right you can check either first and right then left anything is okay I'll check on left first is it alphabet yes human right yes it is Alpha if both are alphabets now swap these two so first check if it is alphabet at right okay if that is the case then check is alphabet at left also if that is also true then what we need to do both are true means left and right both alphabetic means you have to swap these two so A and J will get swapped it will become J here and a will be here remaining letters we will keep as such so now once you swap it increment the left pointer foreign it is not alphabet at left position then left should be incremented why this is not a special uh English letter it's a special character hyphen so they should be incremental we should not um swap a reverse this with uh with the right position so just increment the value if you increment a minute it will remain as such in that position this will be hyphen next once this is done now once you found that this is not English filter you need not to check for right just increment that value now check is this alphabet yes in right also itself you can swap these two so it will be I and B here so now increment both equipment here so again check C and H yes both are alphabet so H will be here c will be here now increment I uh left pointer and decrement the right pointer so this is a special category form so in this case just increment the value now again here it is D here it is G both are English letters so swap these two this will be your special characters let me get it you have to put that hyphen acid now you found uh English letters d and g so G will come here D will come here increment left document right pointer so in this case left yes left is English letter but when it comes to write else if you have to check if it is not alphabet in the right position then what should be done right should be decremented because this is not English letter so because it will be as such so it will come here right so E and F both are uh letters so Swap this to so F comma so if this is not 2 if this is not to only then we do so if both are not true only then we do the swapping if both are not true in the sense if left is not pointing to alphabet that is not true means if you write is also not content alphabet that is also not true that means both are pointing to an English letter so then we do the swapping so you have got the answer equal to give an answer here okay so this is the approach so we shall quickly implement this so first we'll have nothing but length minus 1 the last and X so until left lesser and right we need to view equals to write it doesn't matter right so if in case a b c d in this case uh length of the let's say a b e c d length of string is on left and right increment we are decrement again swapping increment document ee swapping doesn't make sense so until the philosophy Knight is enough left equal to right not required if it is check if not of is Alpha of s of left if left is not an alphabet that means ref should be incremented else if that is not true we have to check uh what else if consciously part of a is Alpha of X of rate is left is pointing to an English letter then you have to check on right side if it is later if that is not particular English letter then write should be recommended else we both are not true that means both are administrators you have to slant them so you can directly use far function or else you can create a temporary variable so swap S of left we have input function in C plus or else how to swap so character temp equal to S of left store it in some variable so s of left will be equal to S of right and then s of right is equal to S of left which is being stored in them so apparently what are we doing so if you want to slap A and D if let is left is pointing right this particular in temp alphabet at left by T because a is being stored in M already so s of left will be equal to S of right is since a soft right value is being stored in s of left now s of light can be updated with s of left value which is CA but it's been stored in temp so s of right will be equal to m4b2 this is what I have written here or else uh this we have implemented Java in C plus we are directing input function but in Java it's not present so anything works so once you do that now to increment left right so return the same string because you are not creating any new string so we shall run this yes so and uh I'll go through the program logic in Java also so here what we'll do is since we know string is immutable in Java so what we do is we convert into array of character so that we can modify it so we estimate the convert into RF characters then left and right point the point into beginner end of the array if it is a the character each character means the other character in the array left is not a letter that means left if it is not a letter in the right part then right minus one is L due to the swapping so next you return uh the characters array into a new string we create a new instance and return it so we shall submit this also yes successful is submitted if you understood the concept please do like them and subscribe to the channel will come up with another good and relaxation until then keep learning thank you
|
Reverse Only Letters
|
boats-to-save-people
|
Given a string `s`, reverse the string according to the following rules:
* All the characters that are not English letters remain in the same position.
* All the English letters (lowercase or uppercase) should be reversed.
Return `s` _after reversing it_.
**Example 1:**
**Input:** s = "ab-cd"
**Output:** "dc-ba"
**Example 2:**
**Input:** s = "a-bC-dEf-ghIj"
**Output:** "j-Ih-gfE-dCba"
**Example 3:**
**Input:** s = "Test1ng-Leet=code-Q!"
**Output:** "Qedo1ct-eeLg=ntse-T!"
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of characters with ASCII values in the range `[33, 122]`.
* `s` does not contain `'\ "'` or `'\\'`.
| null |
Array,Two Pointers,Greedy,Sorting
|
Medium
| null |
421 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you've not liked the video please like it subscribe to my channel so that you get notified when i post a new video so without any further ado let's get started so the problem is maximums or of two numbers in an array very interesting problem so we'll be given an integer array and we need to find the maximum zoro of two numbers maximums or we need to return for example this error is given so if we choose 5 and 25 and we do 0 of that 5 and 25 then we get 28 and that will be the most like maximum zoro of two numbers so this is uh the problem let's see how we'll approach it so this is the input area which is given to us and we need to find out zor of arr of i saw a r of j and that should be the maximum this should be the maximum right now see one simple approach is that what we can do we have a nested loop i and j we calculate every times or of a r of i and arr of j we find zor and if it is maximum we'll update accordingly we'll have a max variable and we will update it so this is one approach and see this one up in this approach we are using nested loop so complexity will be n square which is not efficient right because if you see constraints it's 2 raise to the power 5 max length is 2 raised to the power 5 so if 10 raised to the power 5 is there into 10 raised to the power 5 this will be 10 raised to by 10 so that will give you tla right so this approach will not work here now let's see what we can do what other approach we can use see guys what we can see we need to find maximum zorna we need to find maximums or for example if we have this number i am taking this uh binary representation 0 1 if i have to find a number who's all i do with this so maximum i get so maximum what i can get with this what is or zor is 0 we get 0 1 we get 1 0 we get 1 and 1 we get 0 so whenever bits are different we get one so over here if i want to get one here if one is here then obviously it will be max now and this number which will be there will be maximum so if i want to get one here if zero is there i want override then i have to have one so then only 0 1 will give 0 here's all we are doing so 0 1 will give 1. similarly if 0 is here 1 should be there so that 0 1 can give 1 if 0 is there 1 should be here so that 0 1 can give one now if one is here it should be zero so that one zero can give zoro as one and similarly if one is here then zero should be there so that they can give one so this could be the max we can get so if we have this number in the array and if we have this number in the array these two numbers will give us the max or max lot so from this what we can conclude that if we have a bit 0 we have to find we have to ch we have to go for that number which will have at that place one bit so if zero bit is there we need to go for one bit and if one bit is there then we need to go to with the zero bit because then only we will get in cases one so our result and one obviously uh this if one is there then binary if we convert this binary to decimal it will give us the max result right so now for example how we will get to the approach let's see that i hope you understood this point now for example i have this number this is the binary representation of 3 0 1 i have to check for this 3 this is 3 i have to check for this 3 with every other these this is 5 this is 10 this is 5 this is 25 this is 2 and this is eight so for this three i have to check with every other number in the array i have to check for three and ten does it give me maxes or three and five does it give max or like that and then again if it then i have to do that the same thing with 10 right this we were doing when we were having brute force approach now if there is any way we can store all these numbers so that when we are finding out for three we check okay here it's zero so ideally we should have and we should choose a number from these rest of the numbers we should choose that number which will have one here so that this zero one can give us one so if i have to check for three i will find that number from here which will have one so one is here only 25 so i will go with 25 then i'll go to the next bit i will check for this zero i have to have one is there any number where second bit is one yes this one only so i'm going i have earlier chosen this so i next also i have to choose this now then what i'll do i will check uh for this 0 here also it should be 1 but here it's not 1 and we don't have any other option there is no 1 so we have to go with this only right then again we go here 1 here it should be 0 and we got 0 here so that is fine then 1 is here so we should get 0 but 0 is not there 1 is only there so we have to go with this because we have do not have any we do not have any other option so this was with the three for example now if we do it for let's say some other number um let's say we take five only so output of this uh test case is fives or 25 will be maximum which is 28 now so that let's do that let's have 5 is 0 1 right now i have to if i have i'm checking for 5 this is 5 i have to check if 5 if over here is 0 from these numbers i have to pick one that will have 1 here so that this 0 1 can give me 1 so here only one number is there which have one so i'll go with this number then i'll go ahead let's say over here we have some other number which is one zero like something like this we have right so we have two choices here right so one or one so this we go now we over here we go to zero second bit we check okay this is zero so here it should be one so one here also so we are going correct we go to one so and side by side will also calculate the answer so here two whatever the value will be two raise to per something and here also two is per something will be calculating in our answer variable something like that and then over here also then 1 is here so 0 should be there now let's see over here we have 1 right over here now we require 0 so here zero is there here one is there so we go with this one so we go with this number hence 25 will be the ideal number for this five so 25 fives or we get 28. so in this way we will be approaching this problem so see we know we need to store every these na so that we can check whether we should go with zero or we should go with one we do need to do that right so for that what we can use is we can use try data structure how to write data structure let's see that these all are the numbers 3 10 5 25 2 8 what we are doing we are making a try so see what try for this we will start from most significant bit and then we go to least significant so first of all 0 is there 0 then 0 is there then 1 is there and then one is there right then this is for three now we go to ten we see zero is there we have zero then there is one so here zero is there one is not so zero and one like this 0 1 we are done then 0 so 0 then 1 so 1 and then 0 so this is 3 this is 10 then we go to 5 we make its try so this will be 0 so 0 is there then 0 is here 0 then 1 one is not there so we'll make one then zero one now you might be thinking then how we'll get to know whether the bit is zero or one so for example you i have to you are here and you we are doing four five zero five is zero one and we want to know what is this bit this is our number zero one zero this is our number zero one and we need to find out what is this third bit so that we can write it over here right so how we find that we will do num we do num right shift i where i is see i is what this is your uh which bit zeroth one two three four so i is your second two so what you do num is this number right shift by 2 so if you right shift this number by 2 these will be go right these will be right shifted so this will become 0 means this whenever you do this thing whatever you beat you are trying to find this one this will go at the zeroth place so this will be become this will become this right this one will go at the zeroth bit then what you can do is you just do and with one sorry and with one and one is this so just do and with one and you will get to know that whether uh at this place there was one bit or not if this end result come out to be one means here it is one if it if here it was zero then this result will come out to be zero so you will get to know that if this result is 0 means here it was 0 so this thing if you want to know the bit what is the bit so how you can find it out i hope you're getting if you want to find the bit how you can find that if i want to find whatever bit is here at this place you will do num right shift by i and then do end with one so if bit this thing is 1 means here at this place it's 1 if this is 0 this whole result then it means here it was 0 right so this is the way we do that now we again make this try so here it for 25 it will be one so fancy one is there here earlier it was starting with zero so we'll make one zero and one this is done for 25 then for 2 it will be 0 3 0's 1 0 3 0 this one 0 and then 1 is already there and then 0 and then for 8 it will be 0 1 0 and then here 0 so this is your tree try which is created this is your try and for calculating for making the try we used to find the bit we use this formula right so we have created the try we have created we have inserted all these elements oh sorry all these numbers in our try inserted and created and inserted now we will check for each we will find out the max so let's see that how we do that so this question is bit tricky but once you understand it's very easy so i'm going to erase this so now what we need to do is what we decided that we will pick this number three and we will find its or with every other number now so we have to for example if we have this three we have zero one so what this three we have to find a like number which ideal number that for 0 here 1 for this 0 1 for this 1 here should be 0 so this will be the ideal number so we need to find this for this 3. i am going to find for this i am i'm doing for this five because that's our answer otherwise it will take a lot of time so 5 is there right 0 1 so how will proceed see we will check what bit is here how we check this is your zeroth bit first bit second bit third bit fourth bit right so we will find we will use that same formula which we already discussed in order to find what bit is here we do this is num this is our num we do num right shift with i is your index this 4 and then we end it with 1 so this bit will tell us what bit is here so this bit result will come out to be 0 because 0th is here so then what we do we saw that okay 0 is here so for maximums or here it should be 1 so that 0 1 comes out to be 1 so we will find a number whose bit is 1 so we will not go this side we will go this side because here 1 is there 1. right so similarly now we go to this one this bit we are currently here right currently we are here now for this zero again we check the bit what bit is here so bit comes again to be zero and we will obviously search for one and for this we have a one node so we will go to that so here also we got one so and side by side here we are getting one so we will have two variables answer and max answer will be for at each and max will be the max answer will be at each iteration and max will be the maximum answer so answer how you will calculate over here you are getting we are getting one so how we calculate answer it one left shift we do i so this way we calculate that so that means this what is one this is your x left shift y so this is your 2 raised to the power y into x right so this means every time 2 raised to the power i you will do so if you are see if your 1 is there here and your i if your 1 is 1 came here so your answer we will add what in the answer we will add 2 raise to per we will add this 1 left shift i and which is 2 raised to the power i 2 raised to i is 4 so like this 4 2 4 will be added in the answer similarly 1 came here so what will be added 2 raise to power i is 3 2 3 will be added in your answer so in this way your answer will be created along with your traversal right i hope you're getting now uh over here it's 1 so this bit will come out to be 1 so if this is 1 we need to find 0 whether 0 is there or not so for this one 0 is there 0 is a node so we will go to that so here 0 will come and here one will so here 1 is there so again in the answer what will be added 2 raise to power basically we are adding this now every time in the answer left one left shift i so one left side i is 2 raised to power 2 raised to the power what 2 raised to power 2 right i is 2 then again what we do we check for this if here it's 0 so bit here will come with 0 so 0 is there we need to find 1 but 1 is not there for this 0 there is no 1 so compromisingly we'll have to go with this only so we go here so 0 comes here 0 is there we will not do anything in our answer because here 0 is there right then we go to this 1 and we this bit will come out to be 1 which will tell us okay 1 is here so we ideally want 0 here but for this there is no 0 there is one only so again compromisingly we have to go with this one so one will come here one will be zero right and since compromise link we have done nothing will be added here so this door what this door is coming out to be 2 raised to 4 is 16 plus 2 raised to the power 3 is what 3 8 and this is 2 raised to 2 by 2 4 so this comes out to be 2 24 plus 4 which is 28 so this is your zor of three sorry zoro five this was your five number with 25 this number one zero one this is your 25 that's 28 and if you do with every so this will repeat with every three also 10 also right now we did what we did for five this will repeat with every other number and whatever will whatever answer will be the maximum that will store in the max variable so 28 will be the output so i hope guys you understood how try approach is working in order to calculate the bit whatever the current bit is we use this formula and in order to add in the answer we do answer plus is equal to 1 left shift i one left shift i is your 2 raise to power i so let's see the code once so if you are not familiar with try i will highly recommend just first get familiar with try then only you will be able to understand how try is working so see we have created this try and its children will be only two either every time it will be zero so or either it will be one so that's why we have taken two size area only and we are initially giving null value so this is our try no and then this is a main function this is a function which is given to us and what we are doing over here we have created a max answer variable this will be returned this will show the maximums or and what we are doing currently initially what we did initially we added all these numbers in the trainer so first of all we have to insert all these numbers in the try so we are inserting all the numbers we are inserting these numbers how we are inserting we have the root we go to each bit so what we were doing one by one we are going to each bit now and that we are we were adding 0 then like that so we are going to each bit we find what bit is there and accordingly if there is nothing there in that bit we will add that and we'll go to the next so that is over here first of all zero is added then we check this is zero and this zero has nothing added zero in place so we'll add this zero node here and now from here we go to here so that after this we can add so this is your insertion after that we have to calculate this max zor so how we do that what we were doing over here we have created an answer variable initialize it with 0 and current is our root this one then what we are doing we are finding the bit we are going like turn by turn we were going turn by turn and for each bit we are trying to find if there is the complementary of that bit so if we find the bit and we check if there is the not see not we are doing so if bit comes out to be zero we are finding that whether one is here there or not as its child for example over here um let's say over here zero was there so zero is here so we want to find now it's com sorry if like over here 0 is there and we need to find its complementary one so 1 is here right if one is here means we got the complementary bit and we will add in our answer because that will give us 1 if it's complementary then it will get us 1 so we will add in our answer but if we do not get it else we will not do anything in our answer we'll just move forward to the same bit not the complementary one same bit like one two zero we got compromising you know here we wanted to have zero um yeah like that so i hope you understood what i am trying to say so and at last your return answer and if the answer is maximum it will get updated here so guys i hope you understood the problem and the approach time complexity for this see time complexity we are going to every integer in the array and for insertion and finding out we are doing uh see for each we are going to each integer and we are doing log of m work for each where m is 32 bits so this is your time complexity and space complexity will be uh try we are using so o of n something like that they will be there so we are making if let's say max bits is 11 um max bit let's say is m is max bit right so for each number those max bits will be made so you can say it will be something like o into m if n is the total number of array elements right so these many tri nodes will be there try nodes so i hope you understood the approach and the problem if the video was helpful please like it subscribe to my channel and i'll see in the next video
|
Maximum XOR of Two Numbers in an Array
|
maximum-xor-of-two-numbers-in-an-array
|
Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`.
**Example 1:**
**Input:** nums = \[3,10,5,25,2,8\]
**Output:** 28
**Explanation:** The maximum result is 5 XOR 25 = 28.
**Example 2:**
**Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\]
**Output:** 127
**Constraints:**
* `1 <= nums.length <= 2 * 105`
* `0 <= nums[i] <= 231 - 1`
| null |
Array,Hash Table,Bit Manipulation,Trie
|
Medium
|
1826
|
350 |
all right let's talk about the intersection of two array two so you're giving two array and then you just want to return the intersection and this idea is pretty simple just using the map so if i have a map just stored in my number with the frequency so one two so and this one is two and then there's no one right so i need to make sure the frequency inside the number is actually good to the numbers too and if i don't have it i just take the one and a half right so uh this is supposed to be easy and it's quickly just dive into the solution and i will explain so i traverse the num swan i'm going to put my numbers inside my uh into my map right but anything making sure i have a username ghetto default and then the front and then i use i need to create a release interview right i2i and into array and i will convert it again for my nums to right and i need to making sure if my method gain now is not equal to normal and also vietnam is actually greater than zero so i have a frequency to decrement so if uh if there's a number inside the man if there's a number not inside the map i would get no right away and then this is making sure i heard i have a number inside my map right so i will just update my map and now i'm human beings right and this is pretty much the solution so yes all right so let's talk about timing space this is going to be uh what this is going to be a time for the nums one all of um one be honest and this is gonna be out of n2 right and this is going to be the minimum between i mean the intersection but in a sense so this is definitely what uh the minimum between all of um one and two this is for time and of space it's going to be what the maximum or probably the minimum should be the minimum right the medium will be doing all of m1 and m2 so this is pretty much a solution and now we'll see when it's time by
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
81 |
hello and welcome to another Elite code video today we're going to be working on search and assorted array 2. and so this is similar to the last problem where you have some array and it could be rotated it could not be so in this case it is rotated in an example so you have something like this and we are trying to find the Target in it so in this case it is in there and then for the three it is not in there so the difference between this and the last problem is here we have duplicates so let's see let's just remind ourselves again what we did if there are no duplicates so if there are no duplicates it's pretty straightforward well it's not super straightforward but essentially you can find the lowest value in the array because the array is going to look one of two ways it's either going to be completely sorted where it will just be strictly increasing like this or it will be rotated where it will be increasing and then there will be a drop and then it will be increasing again right like in this case it is increasing drop down to the zero and then increasing again so we are on the second one but either way if it's this or this it's going to be kind of the same for this you can just check right away you can just check this value in the last value and if the left value is less than or equal to the last value then you know it's this format otherwise it's this and for this format we what we basically did was for any pivot point we just compared it to the leftmost value in the array and then if it was greater that means we have to be in this chunk of the array so we haven't yet rotated so then we can check you know we can just get rid of this chunk and then check this chunk and so on so that's how we did it for the last one right and that worked and then we got some rotation point and then we just divided our array into two so we have divided R into this array in this array and then we knew like um because if you have this index you know the range of numbers in your two arrays so this would have to be zero to two so it'd have to be two well actually with no duplicates say there is no two here so this would have to be like let's say five to six and then you just simply find out like what array your target has to be in and then you just do a binary search of that array for your Target that's what we did for the last one but now for this one there's going to be problems and the problems are going to be with the duplicates so let's just say for example we have something like this it's something like just all ones and we're going to add a little bit to this but let's say we have something like this and we have a left and a right still and we have a pivot so here the problem is like you don't really know where to go right so if you think about it let's say you're let's say your target is zero we can just put a zero anywhere we want like if we get this pivot we don't know if our Target's on the left they're right or who knows because our Target could be here our Target could here at Target here it could be anywhere and these are all valid rotated arrays right because you just have it's increasing and then the ones are duplicate and you can even have like multiple zeros right next to each other and so on so the problem is something like this is you don't really know where to go you don't and it's pretty much impossible I mean I think well you pretty much have to just like linear search where to go because there is a problem on Lee code where you're trying to find like the start and end index of a number and an array right like it's you have some sorted array where it's like one two three and then you have like a bunch of fives let's say and you're trying to find like the start and end of a bunch of fives that's doable but the problem is here it's not sorted because you can have like zeros here or something which wouldn't make it sorted or zeros here or like just like hidden numbers that and you don't even know where they are so that's problematic you can even have something like this you can even have like two three four over here and then it's like okay what do you do with that it could also be over here you know so like it's not as straightforward so in this case we have to change the way we're doing our problem and we're no longer going to look for rotation index we're actually just going to look for the number right away and then we're also going to have a case where this is the case where our pivot equals our left you could technically check for both there's like a bunch of ways you could do this they all end up being the same time complexity because if you're in a loop and you do like left plus and right minus together that doesn't really save you anything you're still doing two operations so if you do two operations you know and over two times or one operation end times it's still the same thing so we need to figure out how to do this better and so we're going to actually break this down we're going to first do the problem that was given and then we're going to come back to one of these so for this instead of looking for a rotation index because we know we can run into some of these weird cases you and if you were like me you wouldn't you may have tried to like do this you may have been like okay well let's just see what happens with duplicates with my old problem and what are my issues and then you got one of these weird test cases or something like this you know and then it was like okay well maybe I can just linear search for my Pivot in both directions or something and it gets kind of tricky really fast so instead there's like a cleaner way to do it and that's what we're going to go over so essentially what we're going to be doing is we're going to be looking for so remember an array can either be like this and every sub array is going to be like the 2T they're going to be strictly increasing or it's going to be increasing and then there's going to be air rotation index and then it's going to be increasing again so for any sub array that's the case like for this it is increasing then we have dropped and increasing we can check some more arrays like this whole array increasing drop increasing and if we take like this subarray it's just increasing so those are the two conditions it's either you're going to be strictly increasing or there will be one drop right now obviously with duplicates it's not going to be I guess it's not going to be like strictly increasing you might have like similar stuff so you might have like a flat region and then it'll be increasing and then a drop and then like there might be some flat regions like this right with duplicates so that's the case but that's going to be totally fine for our problem like that'll be fine we really just need to know even with these flat regions there's still going to be like a left side a drop and a right side and that's what we care about or there will just be a left side and no drop so let's actually look at these pivot values and let's look at our condition so if we have a left here and a right here our pivot will be uh this value here and so what we need to check and let's say our Target's three in this case let's not do zero so what we need to check actually we missed one number so let's actually redo this and add uh there was another number here and I think this will work out better so there was a zero here as well there we go so yeah so we're gonna look for three because if you look for zero we're gonna find it right away so it's obviously not gonna be great so this is gonna be the pivot and our Target will be three so now we're gonna check for a couple cases so we're going to check is the pivot greater or equal to or less than or whatever so actually first we're going to check is the pivot equal to the Target right so it is not so that's what we're gonna do pivot does not equal Target okay that's not gonna be our first case then we are going to check does the pivot equal the middle value or sorry the left value so are these two equal and if they're equal that means you can have a bunch of cases and it's kind of hard to say which one right like for example you can have something like this whole array of twos and in which case you don't really know where to go you might be done but you might also have like a zero here you might have a zero here these are all valid so you're here you can have like a one you can even have like a four five six over here you know so if the pivot equals the left value we're just gonna say let's just move let's just increment the left value until it's not right so if the pivot is so like if we have this case or actually we're not going to do this one yet but yeah if the pivot is equal to the left value let's just increment the left value because we don't really know where to go so we're just going to manually increment the left value so we're saying like a binary search wouldn't be helpful here because we didn't know where to go so let's just increment the left value and the reason we can do that is we're guaranteed that the answer won't be the left value because we are checking for the pivot being equal to the Target to begin with so if the pivot is not the Target and let's say the pivot is two if the PIP if the pivot is not two that means this can't be the target so we're getting rid of numbers that we don't really care about so if we increment this we got rid of something we don't really care about and we can just do this until the left does not equal the pivot so we can just do that in a while loop if you don't do it in a while loop you can also just do it once and then move on to the next iteration it's all going to be the same time complexity really you think about it you can also like I think yeah in some other or yeah like you could also check the left and the right but it's going to be all the same time complexity it's the same thing so now that we did that our pivot does not equal the left value so now we need to check is the pivot greater than the left or is it less than and if you think about it remember ra looks like this it might have some flat region but it doesn't matter then it has a drop then has this so if it's greater than the left value left values over here if the pivot is greater that means the pivot has to be on this like left side of the answer if it's less than that means the pivot has to be on the right side right because we've hit the drop and we did hit the drop here so the pivot is less than left here now we're going to check for the Target is the target greater than the left or is it less than so the target is greater than the left that means the target is on so the pivots over here the target is actually on this side of the array and so because the Target and the pivot are on different sides we know that we can just like the pivots over here the targets on the left so the target has to be somewhere in here if it's in here at all right and so we can say okay well if the pivot's on the right side of the answer and the target's on the left side of the answer then let's just get rid of all this and let's make that right over here okay so hopefully that makes sense we have two sides of the array it can either have only one side which is going to be the left side it's strictly increasing or you know increasing with some flat regions or I will have this drop so if they are on different sides we just simply find like which side is the pivot on which side is the Target on and so if it was reversed if the pivot was on this side and the target was on this side then we would just take this right side instead now we took the left side okay so now in our next iteration we get a pivot again and we say okay is the pivot let's actually get rid of all this is the pivot greater than or less than the target so let's take a look so the pivot or sorry not the Target first of all we have to compare the pivot to the Target it is not equal then we have to say is the pivot greater than or less than the left so it's actually greater than the left and so if we draw this picture again the pivot has to be over here right so it's on this increasing side because the left is over here now what about the target so the target is also greater than the left right it's they're both greater than this two value so then now they're on the same side so now there's two scenarios they're not equal so the target either has to be here has to be in the right side of the pivot or the left side of the pivot and now we're just doing like a linear search like a binary search in a sorted linear array and so here our Target is smaller than the pivot right so pivot is greater than the Target because our pivot is five so if our pivot is greater than the Target that means the pivot is here and the target is here and so we're going to want to delete the right side because we're going to want to go left right and similarly if the target was on the right side of the pivot but they're on the same part of the array then we would delete uh this side right so that's two cases they're either different they're on different sides of the array and then you just delete whatever side the target isn't on or they are in the same side and you just figure out like where's the target relative to the pivot and that's just a normal search and uh like if you had a problem that this array was sorted it would be pretty straightforward all right like if you had like zero two three five six let's say or two five six and you've got a pivot value here and your target was three that would be a pretty straightforward problem if you knew the whole thing was sorted because then you could just say like okay my Target's over here let's just delete this and so that's essentially what we are doing for the second case where they are on the same side of the array like they are here so our target has to be to the left side and so we're going to delete this and we're going to say let's make our rate value here okay and now let's actually do the last one so our pivot is 2 is it less than so our pivot actually equals the left right so our pivot equals the left in this case and it is not equal to the Target so that's our case where if I remember if our previous value equals our left value we're just going to say let's just increment our left because we don't need to do it we can't do a binary search because like yeah sure in this case we're here and this is the first value but we could have easily been in one of these right where you don't know where to go so for pivot is 2 we're actually going to increment our left over here and now our left and our right are out of bounds so now we don't have any more values so we can return false so now let's go through this example and let's maybe find some like you know some small parts of it essentially do that so let's just get rid of all this okay so let's say we have this example but maybe we have uh you know let's say we're looking for a zero and maybe it's over here right now let's actually get rid of this pivot value because it might be something different but okay so we have zero one two three four five six seven eight total indices so our pivot values should actually be over here and so you're going to have something like this is like one of the test cases something along these lines so essentially what we're going to do in this case is we're going to say okay is our pivot equal to our Target no it's not is our pivot equal to our left yes it is so we're going to just say while the pivot's equal to the left let's just keep increasing the left because it's a value we don't care about and so we're going to say like okay and also we're gonna also make sure that the left isn't out of bounds right so we're going to do it until the left is out of bounds we're going to say like okay if it's equal to the left here let's just increase the left over here is it still equal yes let's keep increasing and you can see like even though we went past the pivot it doesn't really matter because all of these ones we don't care about this one can't be the Target because we check that first so we're going to go over here and then we're going to finally go over here and we're gonna have a value that we do care about and then we're going to say at the end of the while loop let's just continue on to the next iteration of the binary search so here our left is going to be here and we're going to say like okay we're out of the while loop let's just continue on like back to the beginning of the binary search so now we're going to check uh so we're gonna have a left over here actually so our pivot now is going to be this and we're going to check okay is the pivot greater is the pivot equal to the Target no it's not okay is the pivot yeah so the pivot is not greater than the target um is the pivot equal to left value no it's not okay is the pivot greater than the left value yes it is so that means it is on this part of the array which it is right for this subarray it would be and is the target greater than or equal to the left value so the target actually equals the left value right so it's not greater than but it is equal so it is on this part if it is on this part so for the Target we're going to check is it greater than or equal to the left value as you can see you needed to here so it has to be on this part it can't be on the right part actually sorry it can be on the right part but it doesn't matter if it's on the right part it has to be on the left as well because you would need some array like 0 1 and then you would need like zero or something right in which case it would actually be so you could have an array like this in which case your target would be on both parts but that doesn't really matter because so it goes like this zero one zero your target would be on both parts so if your target was Zero it would be on both but it's guaranteed to be on the left so if we can just say like well it's on the left and the right let's just focus on the left so it doesn't really matter that it's on both so our target has to be here and so now we just so if I pivot and our Target are both here right now we just say like where are they comparatively to each other so our pivot is here our pivot values one our Target is zero so our Target is smaller than the pivot so we need to make the left we need to take the left side of the array so essentially we need to get rid of this and we need to take this part of the array and we're going to make our right value here and then finally our pivot value is going to equal to the Target now so we're going to return uh true so that's like the main thing we have to do from this problem compared to the other problem is we're gonna if the pivot is equal to the left we're just going to keep increasing the left until it's not and we are guaranteed to like get rid of all these values and then finally once it's not you could also do this you could do this in an if statement either one works you could do in a while loop assuming it's the same thing the same kind of complexity like if you have a while loop for your binary search and you just have an if that says like left plus one and then continue or something it's the same complexity as having a while loop and a while loop in there to do left plus one right it's literally the same thing so there's a bunch of ways to do this problem and the reason I'm not a big fan of this problem is because actually if you I guess we have enough to start coding so I'm going to show you why um so actually if you can literally just say like return Target in nums and this is actually believe it or not should pass and it should actually be efficient according to leak code so that's why I like or at least sometimes it is so you can see like oh look you have a great solution here it's all in here but it's great so the test case is like that leak code gives you for this problem aren't the best and like it's kind of hard to test is your solution good so maybe they should have like made some better test cases to like test like for you know how often are you actually using a binary search and how efficient Your solution is because yeah this reminds me of when I actually made like a queue in JavaScript that was like faster than the JavaScript queue and then I tried some lead code problems over my queue uh my Q pops were o of one and the JavaScript cues Ro of N and it was still like giving me more time on the code so I was like okay is there something wrong Mickey where it's going on but then when I did try with like a huge data set it actually worked really well it worked like a python deck roughly so let's go through this so we have a left and we have our array so our left is going to be zero our right is going to be nums minus one then we're going to have the binary search and then we're gonna have a pivot and so we're going to check if the pivot is equal to the Target in the beginning so we're going to say if nums pivot equals Target let's just return true right because we found our value okay so now we're going to say if nose pivot is the left value that this is the part where we're going to keep incrementing the left value until it's not so we can just say like while and we are going to check to make sure the left isn't out of bounds as well because we could have a not Advanced area error like let's say this whole thing is like one you know you would go out of bounds so you want to make sure you're not out of bounds as well and nums pivot equals nums left so while they are the same let's just keep incrementing it and then when that's done we actually want to continue because we want to like when they're different we actually want to get a new pivot in compared to the Target and stuff so we're just going to do this while loop and then we're going to continue to make sure that we do this part again and yeah for like actual efficiency it doesn't matter technically I guess where you write this code because if this is the part that repeats a lot you're going to want that near the top as opposed to the binary search region and I guess those are like small things um you know if any of you have taken like a uh like computer architecture class you know that like you can have the exact same code and it's literally just like the order of your stuff actually makes a reasonable difference it's not going to change time complexity but it will change like for something like if you write like sword algorithms or something it will change it and the sort algorithm if it's like 1.5 and the sort algorithm if it's like 1.5 and the sort algorithm if it's like 1.5 times as fast as something actually makes a really big difference in the real world not another code problem okay so if the PIP so the pivot location is going to be like where the pivot is in the array it's either going to be in the left or the right and we're going to represent the left as a Boolean value so we're going to say if nums left is less than or equal to num's Pivot so I guess technically you don't really need a equal to because if it's equal we're just going to keep anchoring we're just going to keep increasing this but essentially we're just checking is our pivot in the left part like when for our array is it over here or is it over here and we're going to represent this with true and we're going to represent this side with false so that's what we're doing there so we're going to Pivot location and now we're going to have a Target location and as I showed you from the other problem the target can actually equal nums left so you will you do have to actually check for that so numbers left uh less than or equal to Target okay and then now we simply have two cases so first let's handle the case where they're in different sides of the array the pivot location does not equal Target location so we're gonna first check if the pivot is on the left side of the array so if pivot location so this should just be true so if pivot location is this that means this is on the left side of the array so this is on the left side of the array we want to go right so we're going to go right otherwise the pivots on the right side of the array and the targets on the left in which case we want to go left okay and so our other case is if the pivot and Target are in the same exact part then we just do like a normal binary search where we just check like if the target is greater than or equal to the pivot or less than so if the target is greater than the pivot it can't be equal because we check for that so let's make some more space here okay so if the target is greater than the pivot then we want to go right otherwise we want to go left we also want to return false uh if we went through this whole Loop and we didn't find anything right that means we didn't find our Target um yeah it looks like it passed so like I said it's totally random on like efficiency so I wouldn't worry about like these numbers like you'd see like it's all over the place okay so let's actually just go through the time and space complexity uh and actually want to bring this down okay so for the time um what are we actually doing here so obviously worst case scenario like you we are binary searching when we can but then when we're reaching numbers that are equal to the left we're not so actually worst case scenario it would still be over n because like if you're so if your numbers were just like a bunch of ones right if it was like this you would basically do this while loop n times so that would be open so worst case scenario it's ovan but maybe you can argue like average case it's of login because we are still doing binary searches when we can but then when we can't we are doing a linear search and for the space so we have a left and a right and a pivot but we don't actually have in like pivot locations and Target locations but we don't actually have any you know dynamic memory we don't have any arrays or anything so this is going to be of one um but yeah it's gonna be all for this problem like I said the complexity or the not the complexity but like this what it gives you only code is not going to be super descriptive of how well your algorithm is actually doing because first of all it changes a lot second of all like I showed you my linear solution was you know like it gave me something like this for a linear solution which is like doesn't make much sense right because that would be like the worst one technically because I think the tests that actually take the most time are basically in a linear solution so if you just have tests that are mostly like this then actually if you think about a linear solution would be the most efficient because it wouldn't have all these things in here so it would just be a lot less code so this would like if you had something like this then if you did have just like go through it linearly and look for the number that would be the fastest but if you had a lot less duplicates then as you know as the number of duplicates goes down and down then the binary search solution will go up so it would be some kind of graph of like where you know if it was all one number the linear solution would actually be a little bit faster but as you have less and less duplicates until you finally have all different numbers in a big array then this would start beating it by a lot okay but that's gonna be all for this problem hopefully you liked it if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Search in Rotated Sorted Array II
|
search-in-rotated-sorted-array-ii
|
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).
Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.
Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 0
**Output:** true
**Example 2:**
**Input:** nums = \[2,5,6,0,0,1,2\], target = 3
**Output:** false
**Constraints:**
* `1 <= nums.length <= 5000`
* `-104 <= nums[i] <= 104`
* `nums` is guaranteed to be rotated at some pivot.
* `-104 <= target <= 104`
**Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Medium
|
33
|
1,866 |
hey everybody this is larry this is me going with q4 of the weekly contest 241 number of ways to rearrange stacks of k sticks visible so actually i solved this with um with dynamic programming and i actually did it um if you watch me solve it live i'm gonna actually go through um how can i click on this oops i did as i did um if you watch me stop it live i'm actually you could actually see the progression of the full dynamic programming of top down then into bottoms up and then i even uh optimized to the uh what's my card to the uh space optimization trick um i'll go over it here as well but you can kind of see me do it live so that is an example um but yeah uh so for this problem let's read the problem first so this is the number of ways to rearrange the sticks with ku stacks visible so join me on discord hit the like button and that i always do a modular dance now by the way but uh but for this one um i'm not gonna lie i've seen this problem before it was on i still got a wrong on i still got a wrong on i still got a wrong answer because of memory limited exceeded which is something that i'm really annoyed about and you'll see why in a second and this is the you know this is dynamic programming so i'm gonna go over with the code but the idea is and i'm gonna actually let me do a little bit better and bring up my plate my trusty paintbrush but yeah but the idea here is that where's my trusty brain brush okay so now you have you know uh all these blocks you have a uh a ground um and now you're trying to put a block right for first block you could put it anywhere so let's actually you know do the blocks from the biggest block to the smallest box okay so now this is the biggest block so the first bracket can go anywhere so you know just it is what it is and then the second biggest block you can do the two ways to do it right i mean you could kind of see the two ways one is if it's in the front or in the back right makes sense if this is in the front then you um then you see two blocks oops that's the tail of hand whitening and if it's in the back then it's still one block right so that's basically the idea for now um and then now just kind of reducing this i spent so much time to write this but you think about this whoa how did that color change technology is hard mistakes were made but yeah but now instead of saying you know uh two boxes or whatever you could say this is you know in the beginning you want to see k box and here you if you put another block in the front then you're gonna you only need to see k minus one block right and here if you put in the back there's still only k left because this is hidden and then now you have you know now you do it recursively but let's only look at um let's only look at this side because if the block is hidden then you have the same state as before which is except for you have one field box to use but it's still the same and that is the same k right so let's actually you look at this case for now um and yeah and let's say now you're trying to figure out dirt block um and they're only now the three possibilities right as you can kind of see uh again you could see the one on the back really quickly that's also gonna be k minus one um but and also here it's all gonna be k minus one because um you don't change anything right because it is you know like it's getting blocked by the earlier box so you don't really see anything um the only time you see anything is if um this is all the way in the front so that just makes it k minus two um so yeah so then now look at that you know that you can kind of see that there are uh you know given n blocks their n minus way of getting blocked and then one way of putting it in the front and getting seen um and of course just to be you know uh that's basically the idea here uh and just kind of go back a little bit on the colors um that's basically the idea though uh and that is the recursive function just in the interest of kind of being exhaustive a little bit and this is a little bit yucky excuse me um yeah uh you know let's say we had that case earlier that was this and now you're trying to add the orange uh the thingy um and oh this should be shorter right note that in this case still there n minus one and there's only one case where you know this shines in the front right and of course this is gonna be in this oops this is gonna be k minus one uh where this is k from the top um so that's basically the idea behind this problem uh oh um this is it's offset i just noticed that the offset is a little bit awkward hopefully that was good enough oh hmm well that's a little bit awkward on the stream but uh but anyway you get the idea hopefully uh at least from this uh i don't know how it recorded out that's my bad but uh but yeah so now we can look at the code and that's basically what i do right if there's no box left if k is equal to zero we return one because that means that we all the k sticks are visible otherwise i say box because uh maybe that's y but um yeah and if k is not zero that means that we still have blocks that we have to see but we didn't get to see because well it is what it is right because uh yeah this combination just didn't lead us up to it and then that's pretty much the idea here total this block is so this is the count that goes in the of um okay if i put this current block in the front this is the number of count here and then this is the number of count if i put this block in a place that's not visible right um and then you still have to k that you know obligations that you have to do this is the already satisfied one that's k and that's pretty much it unfortunately so i did this in about three four minutes during the contest unfortunately this gives me where's my window unfortunately this gives me during the contest a five uh a memory limit exceeded for some reason even though you know you look at constraints and it's gonna be you'll get the constraints and it's going to be n times k um for reasons that we'll go over in a second and n times k is less than a thousand so i don't know so this made me really sad because a thousand this is pretty this should be pretty good but still sometimes leeco has his ways of uh disappointing you i guess but yeah so my second uh thing that i needed to do was converting this to whoops to top down um i did actually created uh an n by k array um and i set this to um yeah and this is you know if you look at this match the base case because if n and k is equal to zero then this is equal to one because that's how we throw this away which you know yeah and we just that we're doing in a different order um if x is zero then every y is equal to zero and this is of course this base case here and then now we just have to transcribe the solution i probably could have transcribed the solutions quicker but i was just too busy being annoyed to be honest if you watch the video you'll see me going and i grunt a lot and grumble a lot but yeah but that's basically this formula here and at the end of course we have to remember the mod and that's basically the idea um and to be honest uh when i was doing the contest i was a little bit tilted meaning that i was a little bit more annoyed because i know that this has the same space complexity this is still going to be n times k but it's a more efficient n times k instead of putting in a map so i was like yeah and i think if i was smart about it i would actually spend the extra minute to reduce the space um but i think i was just too annoyed about this i was like yolo and you know like another five-minute you know like another five-minute you know like another five-minute penalty i hate you already anyway lead code so uh so i don't know so that one even though this got accepted maybe tactically is a little bit off and then yeah looking at this i actually transcribe it to the oops to uh the current solution you could watch me do it during the contest um or like i actually stopped this after the contest if you keep watching the video where i basically changed this to this and it's pretty straightforward to be honest um because i also have a video that talks about how to do this optimization i'll have a link below or ask me and discord if you need um but the idea is that we just replace we replace every instance of dpx minus one with p dp which i say it stands for previous dynamic programming naming is a little bit about york but yeah but you look at that and look at this then it's gonna be um yeah you're gonna see that it is uh um pretty much one to one so yeah i'm gonna leave them both up so here is the space optimization one and in this case i'm just gonna go over um yeah i'm gonna go with complexity real quick but yeah but this is you know for each the only n times k number of inputs so this is gonna be n times k time which is n squared time in the worst case uh each one of these is all of one operation so it's gonna be of n times k space and of n times k time um and in this case as well because we just transfer it to bottoms up and but you can see the space part way easier because now we have an arrays or two-dimensional matrix and the time or two-dimensional matrix and the time or two-dimensional matrix and the time is also just too follow-up so you can is also just too follow-up so you can is also just too follow-up so you can kind of see everything clearly here we actually reduce the space to o of k uh yeah we reduced this space to of k and the running time though is still the same it's gonna be n times k uh that's all i have for this problem like i said uh i'm okay with this problem well i have seen it before but the memory limit exceeded kind of annoyed me um not only because i got wrong answer because i think you know you look at the oh i don't have to but you look at the timings i saved at least five minutes plus another five minute penalty so in this problem i would have maybe gotten top 10 maybe top 12 something like that top 15 ish at least at worst um like if you take 10 minutes off to like i've been you know so uh at least top 25 say it's always good to be on the first page but it is what it is uh you sometimes python gives you amazing times and sometimes the code is not sensitive to python and this happens let me know what you think and you can watch me sub it live during the contest next well people finish up the contest always i'm a little bit behind mod okay my computer is lagging not great thank so if i had to do this bottoms up i'm gonna be sad i mean it's a thousand okay fine that's come on friends okay let's so did i do anything silly no this should be right okay i don't know why that's just sad i think for me i need to practice this more to be honest let's see if this would work wait let me i don't know why this is so silly i mean this well okay that's a different case but i don't know why this like why doesn't that work do you that's not right tell me something okay much slightly faster but i don't even know it just gives me a limit again i'm gonna be sad i mean at this point i consider a moral victory and we'll see that's silly though really i actually was worried a little bit about this because i should have done the pre-optimization one as well the pre-optimization one as well the pre-optimization one as well um the space optimization after getting memory limited but i was just so doubtful about it that you know and i just really wanted to make sure i get it right first um i probably have to spend more time on it but i was just like a little bit frustrating maybe until to be honest where um i mean i'm telling that i was okay of getting a wrong answer if i had to make this optimization earlier uh and then i'll just do something like this uh and then now i'll start at one something like that this is roughly right i mean you could be a little bit better about the space efficiencies but okay maybe i have a typo somewhere oh right so i applied crepes just spent an extra minute on that but i was just so annoyed at this to be honest that uh top down doesn't work yeah see that looks good um so yeah let me know what you think about today's contest today's farm did you have the same annoyingness that i had on stuff uh yeah hit the like button hit the subscribe and join me on discord talk about these things i will i try to do most of these so yeah stay good stay healthy i'll see you next problem and you know to good mental health bye had the best to stop on
|
Number of Ways to Rearrange Sticks With K Sticks Visible
|
restore-the-array-from-adjacent-pairs
|
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it.
* For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left.
Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 3, k = 2
**Output:** 3
**Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible.
The visible sticks are underlined.
**Example 2:**
**Input:** n = 5, k = 5
**Output:** 1
**Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible.
The visible sticks are underlined.
**Example 3:**
**Input:** n = 20, k = 11
**Output:** 647427950
**Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible.
**Constraints:**
* `1 <= n <= 1000`
* `1 <= k <= n`
|
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
|
Array,Hash Table
|
Medium
| null |
238 |
we are looking at lead code number 238 it is a question called product of array except self okay and so there are two let's take a look at the prompt here before we jump into our strategy so given a number array nums we want to return an array answer such that the answer at the i-th that the answer at the i-th that the answer at the i-th index is the equal to the product of all the elements of nums except nums at i-th index except nums at i-th index except nums at i-th index and the product of any prefix or suffix of nums is guaranteed to fit in a 32-bit of nums is guaranteed to fit in a 32-bit of nums is guaranteed to fit in a 32-bit integer okay so here we have one two three four we can see that the product of four times three times two is 24 which we have it here the product of 3 4 and 1 excluding the 2 is going to be 12. the product of 1 2 and 4 is going to be 8 and the product of 3 2 and 1 is going to be 6 excluding that 4. okay here we can see that everything is zero except for that zero because if we multiply any number by zero it's going to be zero so we have zero nine zero and then we do have some follow-ups here and then we do have some follow-ups here and then we do have some follow-ups here could we solve this in linear time complexity without using division okay and could we solve this in constant space complexity the output array does not count as ac as extra space for the space complexity analysis okay so let's think about this there is an intuitive way to approach this problem that's not too bad but we have to use division and then there's a non-intuitive way to solve this non-intuitive way to solve this non-intuitive way to solve this that doesn't use division it gives you much better performance but we you know yeah you it's just not very intuitive so we'll go we'll cover both of these so let's go over the intuitive approach first with this question we have to account for three different edge cases okay so one of the things we have to look at is if there's more than one zero in the input array then every single number in the output is going to be zero we can either create a new array fill it all at zero or we can just replace everything in the input array with zero because everything will be zero and i'll show you what i mean let's say we have an input of one two zero five seven zero and nine okay so the product of anything multiplied by zero is going to be zero so if we're at this zero we're still going to hit a zero right over here and that's going to turn everything into zero okay similarly if we hit this zero and we exclude that we're gonna still have this other zero here that's gonna take the product of whatever else that we have and turn it to zero and everything else because there's a zero in the equation it's also going to be zero so all we have to do for the first edge case is just filter out all the zeros and check do we have more than one zero if we have more than one zero we just return the array we just go ahead and replace all the values in our input array with zero and just return that okay so that takes care of the first edge case now what if we only have one zero okay well what we want to do is we want to filter out this 0 so we'll have minus 1 minus 3 and then we want to get the product of this okay in this case it's going to be nine call this product and now that we have this product we just go ahead and scan our array and we say is this value zero it's not zero that means that when we try to get the product of everything else it's going to hit this zero and that means we're going to get a zero there okay is this value a zero it's not a zero so that's going to be zero is this value a zero it is a zero that means we have to get the product which we've already calculated by filtering out that zero and just replace it with nine okay moving on we'll check is this value a zero it's not a zero we'll replace it with zero and if this value is not a zero we go ahead and replace that with zero and that will solve for that instance if there's one zero in the input okay so now what do we do if there's no zeros in the input so let me just go ahead and clean this up here okay and we have an input of 1 two three and four so we made it past we realized there's no zeros in it and so now we need to get a product of everything without the current value well we can do this using division so we want to get the total product which is going to be 24 we're just going to multiply 4 times 3 times 2 times 1. so we'll just call this product and this is going to equal 24. now all we have to do is just divide this product by the ith value and replace the number so here 24 divided by 1 is going to be 24 i increments over here 24 divided by 2 is going to be 12. okay i increments here 24 divided by 3 is going to be 8. and i increments here 24 divided by 4 is going to be 6. okay the only problem with this is that we have to use division and that's one of the follow-ups that said we can't use follow-ups that said we can't use follow-ups that said we can't use division so if we cannot use division then how do we solve this okay well before we get to that what is our time and space complexity if we did it this way well we have to make a few scans to the array just to check if there's zeros and then we have to do another scan and replace all the values so our time complexity is linear it's going to be o of n on time okay what about our space complexity well we have to create worst case we have to collect all these zeros and put it in an array an auxiliary array to count the zeros okay so because of that our space complexity is also going to be o of n which isn't bad it's much better than the brute force way where we take one and then get the product of everything else excluding that and do that on each element on each iteration so here we can get linear time and we can get linear space but we're using division so now let's take a look at how do we do this without using division okay so what we want to do we want to create two auxiliary arrays okay and we want to call one left and what this array is going to hold is everything all the product sums to the left of that index so starting with 1 there's nothing to the left of this one here so this it's always going to start with one we're going to initialize it with one at the zeroth index and now what we want to do is we want to fill in the rest of these values almost like using a greedy approach okay it's just going to it's a dynamic way of doing this so we're going to do 1 times 1 which is going to equal 1 then we're going to do 2 times 1 which is going to equal 2. we're going to do 3 times 2 which is going to equal 6. okay so now we have all the products to the left of that index okay and now what we're going to do is we're going to do the same thing for the right and it's just the opposite instead of initializing with the one here we're going to initialize the one at the end okay and now what we're going to do is i'll just change the color here so it's a little bit clearer this is our one here we're going to take this four and we're going to multiply it by one and just follow that same pattern so four times one is going to be four okay we're going to multiply this 3 by this 4 so that's going to be 12 okay and then we're going to multiply this 12 by this 2 and that's going to be 24. okay and so lastly what do we want to do now we just want to combine our left and right so we're going to multiply 1 by 24 i'll change it to green here and we'll replace it into our input array and we'll change this to 24. we're going to multiply 1 by 12 and we'll change this value here and set it to 12. we're going to multiply 2 by 4 and we'll change this value and set it to 8. and lastly we're going to multiply 6 by 1 and we'll change this value and set it to 6. and now you can see we have achieved our goal of our result it is the correct result without using division okay so this is a very elegant way of doing this it's you know using a little bit of a dynamic programming approach but it solves the problem in a very elegant way now i think it's really hard to come up with this in you know interview setting but i think if your interviewer gives you a hint or leads you in that direction and you're familiar with kind of using two arrays and using a dynamic approach then you can really impress someone by coming up with the solution in an interview so let's take a look at time and space complexity our time complexity is going to be o of n okay because we have to do some scans over the array but it's only an n number we don't have to do it relative to the size of the input okay so our time complexity is going to be linear and then our space complexity we do have to create these auxiliary uh arrays but we're not returning them we could delete them so you know you could argue this is constant space but technically i'm gonna it is linear space um we're gonna say uh o event space all right so let's go ahead and jump in the code okay and so what do we want to do here we want to create a left array of nums dot length and then we'll just fill it with 0 initially and then we want to set left at 0 to 1. we want to do a write array we want to do it at nums.length and fill that with zero and then we want the rightmost value to be one so we can do right at right dot length minus one equals one okay and so now we have to do a few scans over this array so let's start with the left so we're going to say 4 let i equals 1. we're going to start at the first index of our nums and we're going to say i is less than nums dot length and i plus and so for left at index i what do we want to take nums at i minus 1 multiplied by left at i minus 1. okay so what we're doing here is we have this one initialized we are at this ith index in left and then we're going to get the nums minus 1 times the left minus 1 and then go ahead and fill in that new value there okay and now we're going to do the same thing for the right we're going to say 4 let i equals right dot length minus 2 where i is greater than or equal to zero and i decrements okay and now we're going to say right at index i is going to equal right at i can just keep this consistent nums of i plus 1 multiplied by right of i plus 1. so again all we're doing here is we're coming to the right and we're starting here we're actually we're starting here okay so it's gonna be the length minus two and we're taking the length plus one which is going to be the six here and we're multiplying it by whatever was in the right which is one and then we're filling in this um this current i index okay and so lastly all we need to do is combine it so we just say four let i equals zero i is less than nums dot length i plus and here we're going to say nums of i is going to equal left of i times right of i and then we just return nums all right so let's go ahead and run this and we're good i believe my internet is a little slow so it's taking uh some time but we can see we got great performance here beat out 94 on space and 65 on uh time this is really inconsistent though you know every time you click this it's something different now we have 96 98 so but i think we make really good time and space and we get a very optimal solution using this dynamic approach so that is lead code number 238 product of an array except self i hope you all enjoyed it and i will see everyone on the next one
|
Product of Array Except Self
|
product-of-array-except-self
|
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
You must write an algorithm that runs in `O(n)` time and without using the division operation.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[24,12,8,6\]
**Example 2:**
**Input:** nums = \[-1,1,0,-3,3\]
**Output:** \[0,0,9,0,0\]
**Constraints:**
* `2 <= nums.length <= 105`
* `-30 <= nums[i] <= 30`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
**Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
| null |
Array,Prefix Sum
|
Medium
|
42,152,265,2267
|
1,833 |
all right trying out a random medium problem and we get a premium one so we go back and we try again okay tasks count in the weekend that's the problem I can see from my taskbar and we're gonna get another Premium One and we go back again um do they have a filter for that can I filter status attacks let's actually do status to do so we'll only do the ones that I have never done and uh okay pick one and we get this maximum ice cream bar problem let's avoid it is a sweltering summer day and a boy wants to buy some ice cream bars well it's winter but okay at this two there are an ice cream bars you are given an array costs of length and your Cosi is the price of white ice cream bar and coins the boy initially has coins coin these many coins to spend and he wants to buy as many ice cream bars as possible return the maximum number of ice cream bars that the boy can buy with coins I mean come on could you just not kill okay get a different video but look at the buy can buy the ice cream bars in any order let's see what it says so I have seven coins and uh these are the costs one three two four one what does the costs are indicate price of the ice cream bar there is one ice cream of this cost another scheme cost these many coins and so on the boy can buy ice cream bars certain dices zero and I says one indices 2 indices 4 a rotor of one plus three plus two plus one equals to seven okay I mean okay so the basically given the cost of the ice cream so you're gonna total coins I'm not really seeing what the for the problem here is like I want to maximize the number of ice creams that I can buy that means I'll buy the cheapest ice creams right so one of the solution obviously I sort the array and I keep adding I mean so I saw theories and then I keep adding so till I uh till I have points for entire equals to 0 I is less than coins I plus okay sorry my mobile coins left divine coins is not equal to zero or other yeah while coins is not equal to zero thank you I do um uh if remaining coins is greater than or equal to I can even do a while true here I feel like so just run a loop and if your remaining coins are greater than or equal to the uh cost of this ice cream then you just do I press Plus right and if that's not the case then you just return it and if you come out of the while loop and you have to come out of the while loop because at some point um so your index I has to be resident cos dot length but maybe you can buy our ice creams so when you come out of here again you did online so I guess if n log n is allowed then this might work or I have not understood the problem correctly let's see can you go to the wrong one sorry it will start the task is written what hotel price or what wait are the maximum of ice cream bars yes it was four no so I run five one two three four five story and obviously uh two plus one four plus two six plus four ten is not possible so um that's I guess I can fix so let's run code and see what the problem is I start with zero I have not bought any ice cream now look at the first ice and I have sorted the array and uh if oh I have not done coins equals two points Minus cost of I that is what I missed okay run good and again uh this has to be done before okay and some more and it's just accepting I okay I guess it was
|
Maximum Ice Cream Bars
|
find-the-highest-altitude
|
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108`
|
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
|
Array,Prefix Sum
|
Easy
| null |
130 |
welcome back everyone we're gonna be solving Lee code 130 surrounded regions so we're given an M by n a matrix called board which contains X's and O's we need to capture all regions which are four directionally surrounded by an X and we can call a region captured by flipping all O's into x's in that surrounded region so this problem is going to be very similar to Island count and I think the problem is count the number of farms in a grid we sold both on the channel before if you haven't solved them go solve those ones first um essentially what we're going to do is take that underlying concept that we use to solve both of those problems and we're going to do it here so we are going to find the number of islands in this grid and as long as this island is not touching the boundary of the grid right either the First Column the last column or the first row in the last row then we're going to take that Island the cells in the island and we are just going to flip them into x's and that will give us our output result so we are going to use a breadth first approach to solve this so let's Implement our Q we'll say from collections import our DQ we will set that up and there is not going to be anything on here initially so we are also going to have a visited set so we'll say visited is going to be equal to a set and we will also have an array called Islands what we're going to do is right we're going to find all these islands in the grid if it is not touching the boundary of the grid we're going to place that array onto our Islands array and once we're done running breadth first search we will Loop through this Island's array and get grab every cell in every island in this array and then just flip it to an X so let's run um breadth first we'll say four row in range length of our board for column and range length of board zero we are going to say okay if Board of our row column if that is equal to an o we know we found the start of an island but we also want to check and make sure that we have not visited the cell before so we'll say and row column pair not in visited if this line executes then we are going to add that row column pair onto our Q so we'll say Q dot append the row column pair so like I said we're gonna find every island and then we're gonna place that Island onto our Island's array so we're gonna have to have an array in here so we can grab all the cells with breath first search if they're an O and place it here and so then after uh the breath first finishes running we're gonna take this island array place it here now in order to determine if we are at a boundary position we are going to have a variable we'll call it Edge or boundary whatever you want but we are going to set it initially to false so if we ever run into a boundary position in our breath first approach that we're going to run we will set this to true and if this is true we're not going to take this island and place it here because that means the island that we're currently at has a cell which is touching the boundary of our grid which means it is not four directionally surrounded so with that said let's implement this breath first we'll say while the length of our cue is not equal to zero we're going to grab the row column pair with Q dot pop left we are also going to say visited dot add this row compare now we are going to check are we at a boundary position so we'll say if R is in um 0 or the length of board then we're going to set Edge equal to true we'll check the same but for columns and this should be board minus one so we'll say if C in 0 or the length of board zero minus one then we will set our Edge equal to true otherwise we are going to say Island Dot append the row column pair now we need to check so if we're at on the very first cell in our grid right 0 we need to check the row below in the same column the row before in the same column and then we need to check the column before in the same Row in the column after in the same row so we'll say if our row plus one right so we're here now we're going to check this element there this cell right here so if row plus one is greater than or equal to zero and less than the length of our board and our column is a greater than or equal to zero and less than the length of board zero and our plus one column not in visited and our Board of row plus one column is equal to an O if this line executes we're going to add that cell onto our Q so we can continue searching so we'll say Q dot append the row column pair we'll also add it onto our visited set so visited that add the row column pair now we need to do this three more times right we just checked the row below let's check the row above where we are currently at to do that we'll just take all of these R plus ones and change them to R minus one like so now we will check the next column so we'll take all these R plus ones get rid of them and swap them out for column plus one column and column we'll change that to plus one and this one should be plus one as well so we'll copy this change all of the column plus ones to column minus one okay perfect now once we exit this while loop we've finished running uh the search on the island so we need to now check okay is do we have cells in our Island meaning have we found an island and is The Edge equal to true or not so we'll say if the length of our Island is greater than zero and our Edge is not equal to true meaning we have found a valid Island that is four directionally surrounded if this line executes we want to take this island and place it onto our Island's array so we will say Islands dot append the current Island and then once we exit all of this we want to now Loop through our Islands right we're done running the search on our grid we have found all of the islands that are four directionally surrounded now we just need to flip all those cells so we'll say four Island in Islands we're going to grab the South so for sell in the current Island we will now say Board of cell zero and cell one is now going to be equal to an X so let's get rid of some spaces and run this because we don't have to return anything up here they tell us don't return anything just modify the board in place so this is all looking pretty good um it should run so let's run this and I misspelled board somewhere line 12. right here so we'll rerun hopefully I don't have any more spelling mistakes perfect we passed both test cases so we'll submit awesome and it does run so um the time and space complexity for this problem is going to be o of the rows times The Columns for both all right that'll do for Lee code 130
|
Surrounded Regions
|
surrounded-regions
|
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
200,286
|
326 |
hey everybody this is larry this is day 24 of the leeco day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom just trying to find to see if there's extra points uh power of 3 326 okay given in jn return true are you serious um okay the tricky part is that no way is that true i keep on i think i said the same thing yesterday which is that i was thinking of the third power which is the power of three um yeah i mean uh this we're just gonna write the same thing as yesterday i'm not gonna write any cool bit wise thing i'm not gonna i'm not feeling it today so sorry friends of you uh if you think i'm gonna do something like crazy um bit operations i mean you could probably figure it out i don't know the fourth one is actually a little bit easier but um i think it's just maybe i don't know maybe it's just a pattern matching right so i don't really know um because maybe you could figure it out it's like one and then times dad what is that i don't know um i'm gonna do a quick submit but and this is just a silly problem anyway uh unless i mis through that one uh 876 day streak i actually missed it so we'll see but now i'm curious like you know for i in range of say 10 what is the binary format of um this right i'm just curious let's take a look i don't know i'm not uh it's just very silly i don't know um do i see a pattern uh not really to be honest i mean obviously it's an odd number but that's three that's nine and then 27 i mean yeah i mean i guess i could see a because the 11 is interesting right it's just well i mean it's three but it's 11 in binary so it's just like add and shift itself or something like that but i don't know anyway that's all i have uh i need to pack for my trip so that's why i'm also just being a little bit lazy today i hope to see you tomorrow again and maybe i'll do a quick bonus question why not so yeah i'll see you soon stay good stay healthy to good mental health uh take care bye
|
Power of Three
|
power-of-three
|
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_.
An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`.
**Example 1:**
**Input:** n = 27
**Output:** true
**Explanation:** 27 = 33
**Example 2:**
**Input:** n = 0
**Output:** false
**Explanation:** There is no x where 3x = 0.
**Example 3:**
**Input:** n = -1
**Output:** false
**Explanation:** There is no x where 3x = (-1).
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Recursion
|
Easy
|
231,342,1889
|
154 |
EPF Diwan and welcome to quote card to in and expert solve this problem for a minimum mein chhote-chhote are solve this minimum mein chhote-chhote are solve this minimum mein chhote-chhote are solve this problem with the help of ministers algorithm aware and complexity weight and of log in hindi central to the problem final mein chhote-chhote rahe Part 2 110 Problems mein chhote-chhote rahe Part 2 110 Problems mein chhote-chhote rahe Part 2 110 Problems Quite Similar to the Previous One Battery Exams Friend What is the Year Main Contents Duplicate Button Previous Pregnancy is That You May Not Know Dear Zindagi Are Not Here All Elements Are You Need a History Voice Video Replacement for This Problem And suggested to watch this video and solve this problem should be destroyed it for you to understand so let me explain hai batting for example hai so sappoch yunik hai are eradicated 40,000 present shravan duplicate khar present ok sorry free condition me loot ki remix notification suggested Mere jitne logon a lot so very first edition nahi hai ki sapoch all the element a present in this section hai aur duplicate hai aur ki duplicate e want to meet oo have to apply and logic in this section the correct hai means Uttar Pradesh section milo Will be scene lo highway change to be i will be a that tomorrow it arrived frustrated ki sexy suhai will change to media 17 second scenario inch addressed me hai re tu a reminder lo rich enemy a high i improve distractions duplicate loot following soviet to Apply for all logic for this section only for this section women will be meet plus one hai mi highway celebration on na is meanwhile to condition par easy samane menshand that one to loot low medium high sudhir va hai ka swaad to Ajmer here example Suppose they represent take this festival in between two subscribe 504 506 element between what will oo two apk file first element elements in two I am in Saudi are morning simply in one element and apply all logic hindi section or one ok na ho mein pain par condition very fast 2109 limited example delhi machi suppose you are having a 1021 jhal in one month ago hai navya rotating from this position on tomorrow morning new edition try mein hai pune new year will look like 0096600966 timing here Chief Chitra Plus Seat Na Share Vid U Ki Actress Visit To And Highways Also To Sequential Reducer Minutes Each Part This Point Complex Built In Hindi Part-2 Point Complex Built In Hindi Part-2 Point Complex Built In Hindi Part-2 Loot Can See Ardhamagadhi Logic For Are Unique And Elements Saudi Arabia And Employment Unique Elements In The Given More logic porn more information for duplicate next9news hai fidgit that this condition is live voice mail messages loop hai wait a while inside novel checking that this was calculating were very first measured equal to low gas high IQ option a 209 were checking happened this to koi i this mileage After meet that UFO me and he is equal to one week only sequence year media-2 one week only sequence year media-2 one week only sequence year media-2 20 miles 243 equal New Delhi will check air chief of me to go on that any donation enemy checking to two I will move Forward medium to apply and logic hindi section means remove and lo class 1o hai to ke na vacancy hai main lo equal to how much sunao ki log came one in hide 6999 main one plus six back to witch will again be a ka name vacancy Is that Team India song oh my needs be related to it that news at index fund is that this month lo whiteness put do Om Namo latest me forward na that apply logic with this action ko one main naagin the election is this absolutely that intestinal record Needed to 4th is not wear is mediaset index for me ninth checking one by one media control your page to this video sharing value 0 hi pooja invalid two digit only nine day computer is not that light same logic and also unique element the benefits's music For Unique Elements Dushman Hai That This Dish Condition Pahal Jhal Dispel Deni Hai This Voice Mail Read This That They Are Going To Check Loot This Velvet Amir Itself Made That Greater Than That This High Hello Viewers Greater Is Half Hour This Media 0 Unnao Will Go In And listen to the voice mail this Navratri same condition in sports meet was great this meet was great approach that low medium high style present for his post and where present to cross approach English language is greater I want you to have to this back to Supplier logic hindi section only on uttar pradesh power low will be how much you will be plus one voice mail directshwar notification lagi cancer directions scenario share my media nodes electronic media will not get and it will present at the index only means and problem in the And they won't be lying decided that Lakshman was my hua but can see idaiveli bad great hai lagnesh vicious tanning restaurant 5 inches behind another condition in this section only under 500 that if in such condition invite you to tomorrow morning change of A2 And high value in does not present in this section to change were you will not I will be in admit enroll beth initial value only where to take care lagi previous one previous closing of 101 president hai aur naaye kaisi hai lo is hum 251 60400 Mission Fail Is Good Condition LG Air Frame 80 Greater Vent To Know A Little Boys Have Written Rebel To And Sunao Jhaal Miding Check Relax Nickel To File Is MS Word 210 This Meet Will We City 39 Meads Is Show Me The Volume To 9 And Chatting Well- Show Me The Volume To 9 And Chatting Well- Show Me The Volume To 9 And Chatting Well- Presented Equal to Your Present at Present Medium to Where Present One Wish All a Fatal Co in That Elle Foundation Ne Lip Care Setting Value Present Means Great and Well-Presented Highest Bliss at This Well-Presented Highest Bliss at This Well-Presented Highest Bliss at This Point is Means Too Great 10 Conditions Satisfied And after var oo will be plus one to that people will meet plus one from which country and value than three plus 154 that aapke na ho hai baking walo wash it medium to high frequency ear for listening to 4 9 is condition field due to return To Watch Good Return The Hey You People Social Environment and Criminal Name Set Hello Bittu and Hai Na A for Medium and Example in Which They Have Failed This Condition Means Condition It's True and This Condition Sports Were Left with Distinction but Right for More Example introduce kar do ko support disawar yaare ni soon protesting at this point with what is the distance 201 120 miles 260 ko 10 2014 se 0514 straight middle wa ki agar in wild lucerne hai yes submit vishwas 0.2 wich will be 2nd odi submit vishwas 0.2 wich will be 2nd odi submit vishwas 0.2 wich will be 2nd odi debut na Vehicle checking also condition live on this valley present that mean equal to high not satisfied with his voice mail this condition notice checking of midnight children f5 press subscribe will change a lot on a slow will meet plus one medium height currently to send to me a Place witch is free to get fired add previous one beam will find and have meaning in hindi section only limited to another example in this case feel very first class people and subscribe and second's cfl and 20 minutes till medium to high solitaire missionaries's In witch a position and equal to hello hi that we suppose a 201 suzy dark sprite more 9021 10 2014 features 028 pass a message how satisfied election is religion will be to hair itself getting pregnant the media two weeks in that which just this Meet Grade Equal To A Girl Is Very Interesting Facts Did You Know Which Gali Present And Made Into A Bur Develop Presented Below 200 How Field This Is Gold Kar Deni Hai To Go In This Condition Menu Subscribe To Ka Vikas How Satisfied And Second Cases Field That missal divine duplicate morning to right logic for destruction handed over section twist in witch acid 102 that serial simply right fence itself equal to need is my life in a 500 I will meet jhal 34 meed this country two boats 80 to two this picture Vid mid-day meal cooked on 80 to two this picture Vid mid-day meal cooked on 80 to two this picture Vid mid-day meal cooked on that in hide here in low is episode 10 na we are checking that this meat eggs media on 01-01-2013 that this meat eggs media on 01-01-2013 that this meat eggs media on 01-01-2013 present high 1.12 Diwali present his to present high 1.12 Diwali present his to present high 1.12 Diwali present his to 9 from which files fear checking of mid-day Hain To Hai Will Win The Media For One Day And Listen A Special Chant A Height Smith Minor Mobile Se [ __ ] Hai A Height Smith Minor Mobile Se [ __ ] Hai A Height Smith Minor Mobile Se [ __ ] Hai Yes Your Loved One Me Plus One Dos Torch Light Bill Me Tomorrow Morning Media Senior Meet 1204 No Waking Affidavit Of Hi How Much U Ki This Media Gallery 0 Political Defy Aaj They Present At Index One Is How Much In The Independent India Company Swan Member All Sweet Will Go In New Delhi After Elephant Jacking Diwali Present At The This Meet Me 400 A Greater Than Hi-Fi This Meet Me 400 A Greater Than Hi-Fi This Meet Me 400 A Greater Than Hi-Fi W One Will Present And 119 191 Followers In Equal To Meet 200 High Equal To Medium Kar 98100 Checking Election 2012 Hi This Is Subscribe Button Values 80 Solitaire Record Ras Copy School Ko Khoj Episode One More Ek Condition Sudhir Wa Ki Jis Seat Belt Bandhan Ke Swar Unique Element No How To Write A Case For Duplicate Values Main Sirf Ka Naam Saaf MP3 Us Of Name Yo 1212 Naam Fall Hi Hai Ek Din Yeh Entry Check Ignorance Ek Naam Lo Hu Is Equal To Divya President Names Of Meet Is Rumor Recording To Naam Lo Na Dixit was seen in condition that she was in cigarette adding disease condition of this much arrested Arvind taken care in and previous code insensiticide 20 condition loot so that if velvet medium to the velvet high and also withdrawal request to the low value so that you will simply change Kar lo means wishing a very fast forward kar lo two plus one shree nandishwar ji k o menu hindi list ki up show me the results five elements of it and valleys of oil in the assembly checking hindi section me removing and lo two plus to you Kyun na ho jhal is meet behavior highway live and equal in this condition was for this new Delhi will going and condition and discuss issues like this I am Hindustani ho ki lo medium hi decide subscribe cancer jaisi 721 very subscribe our video during this time Laidi Came Will B Deshwal has met this so I have met on the highway Alleged in such a condition Loot happened in JCB condition of New Delhi Which has already been taken care for also unique elements The slimmest Rajneesh Kumar Loot Senior Getting Indian dresses Prohibited is Shravan To a sequence year did not accepted solid summit mein isko a second year and accepted and this uniform logic is this peace logic pro yes brother you like this a scenario bhej ki putri gas aap haldi practical wa low medium high world apply another logic in a the media And High Very Well And When Was Not Equal In One Case Was A I Ignore Is Equal To Need And Highways Not A File First Second Third Step In This All Train Ka Nishan Li Hai Who Is This Is Question And Applied Zoology Traditional Dresses And Best Quality hai 180 invite this video please give subscribe our channel coding card and stay tuned for next video thanks for watching hai ek se ek
|
Find Minimum in Rotated Sorted Array II
|
find-minimum-in-rotated-sorted-array-ii
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become:
* `[4,5,6,7,0,1,4]` if it was rotated `4` times.
* `[0,1,4,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` that may contain **duplicates**, return _the minimum element of this array_.
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[1,3,5\]
**Output:** 1
**Example 2:**
**Input:** nums = \[2,2,2,0,1\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* `nums` is sorted and rotated between `1` and `n` times.
**Follow up:** This problem is similar to [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
| null |
Array,Binary Search
|
Hard
|
153
|
12 |
Hello everyone welcome and welcome back tu de channel in today's lecture will be interior tu roman number so we have wait and date c are going tu converted tu de no roman number so this is one of the really important and ask question in interviews so Let's see ho see can okay so here is a good thing to understand there are many things which we have to understand so first and form of singh will keep on understanding hearing first we have to understand for writing van ho see are writing it If you want you right, I am writing okay, I want you right, four, I am not going, right, I am four times, right, if I am going, right, like this, it is no, then instead we write five, okay, so this. A special number is done Mins We are following a pattern The you are adding up de numbers and are getting off for five Already having this five right for five We already have so nine for six Going you right five plus van se pattern this van tu right de se pattern date it 5 tu times three times again for 9 we have pattern one changed date it this van right so this is also a special case a gone so see can see date we have whatever In between another number we need like for this one number before this digital so date is 4 okay nine 10 9 that blue hundred and already van tu 10 covering tu take 40 okay now from here it is un 50 tu 100 so si Are you going to take C Are you not going to take 99 Are you going to take 90 Okay and give 100 Are you going to take 500 Are you going to take 400 and 50000 So basically apart from one You three four five six seven the seven days 89 10 11 12 13 Dej 13 Combination Also See You Have Written It Okay So This Is Our First Of All Us Input Puzzle Game See Can Keep It And Are Also See We Can Keep It In Map Also Her See Are Going To Keep It In It Yourself So This Is Our First Term For Most thing right more five number so all the combinations which we have discussed till now we have noted down here mains 1/4 so in between one noted down here mains 1/4 so in between one noted down here mains 1/4 so in between one and four c are having 5th between five and 10 c are having 9 in between 10 and 50 where in 40 in 1500 where 1900 means what are we doing C are just trying to cover further much further unique combination is possible so this is what we have and the final comes out ok so for these actually these combinations R already given and this van this and this five and four which is already given this is already given so what you see in black is date is already given days R D van which is C have framed just nine okay so right it 1000 You can write it cm is 100 and 1000 now we have to find one out let's say if we are taking it two three seven okay this number we have to find out is a Roman number so first of all we will check Is this number smaller than 1000 or not? First of all, let's write an M. Okay, 9C is going to be subtracted from 1000, so our value will come out, so basically it is 837, which number is less than 500, right, so 500 is less than 37, so we are 500. We will subtract from select also subtracting 500 and d answer every is 337 and c are going to write 500 which is the ok only right so instant of this c are going to write three times of 100 hundred will do so directly we will get a 37 And 37 is remaining and here we write 100 CCC three times okay nine aa 37 this is than 10 right so for 10 we will write X 5 and 2 So this is what our actually 280 2837 convert into roman number Okay let's do that thing in program and less find out So now what we will do is write the code first of all we will have a string latest okay we will show Wait and Roman number and filled it now just functions so we will take it that using for loop so far is equal to zero and I is less than values and dot length verizontal number world function will write plus Roman letter fevicol super so this Our final output is A and this is what we have to find so we can see this is all our test cases getting past so it was very easy to convert from these teachers to Roman numbers just keep in mind that Let's find out all the numbers like this and then this is how we are going to find out ok then till then thank you so much
|
Integer to Roman
|
integer-to-roman
|
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
**Symbol** **Value**
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used:
* `I` can be placed before `V` (5) and `X` (10) to make 4 and 9.
* `X` can be placed before `L` (50) and `C` (100) to make 40 and 90.
* `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral.
**Example 1:**
**Input:** num = 3
**Output:** "III "
**Explanation:** 3 is represented as 3 ones.
**Example 2:**
**Input:** num = 58
**Output:** "LVIII "
**Explanation:** L = 50, V = 5, III = 3.
**Example 3:**
**Input:** num = 1994
**Output:** "MCMXCIV "
**Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4.
**Constraints:**
* `1 <= num <= 3999`
| null |
Hash Table,Math,String
|
Medium
|
13,273
|
344 |
hey guys welcome to the core Matt if you are new to the Channel please do subscribe we solve a lot of competitive problems today's problem is reverse string so problem says write a function that reverses string the input string is given as an error of characters array so we have given as a character array we would like to reverse that character array do not allocate extra memory for another array you must do this by modifying the input array in place with them or one extra memory so it's expected that we do not use or we should not use extra memory or extra array to do a reverse of that character array we should do it in memory space so let's take example so here the given input is hello and this is what the reversed version so it's if we would like to do it in the in memory space the best approach for this one is we can take a two pointer one from the left side other pointer from the right side and what we can do he be here is just two pointers will swap the values or swept the characters okay and once they will swap it the pointer from the Lipsett will move on a right hand side and this point on will move on the left hand side so this both the pointers will keep iterating till and they will cross each other so we'll have a condition when they will they are equal or your left is less than your right pointer till that point we would like to swap those values so now let's write a code for the whole thing so here let's first define your pointers let's say this is your left pointer and let's J will be your right pointer length minus 1 okay and let's we are defining one our Tampa character because we want to hold a value for one of the left or right character while doing the step now let's try to look for that when I is less than so your left is less than or equal to J till that point we would like to do the iteration now first take s of J in the time and assign s of J with the s of why it's a normal swapping algorithm or not algorithm I would say logic s of I is equal to M okay so once we do that move your left to left pointer to the right side and you write pointer to the left side okay so the chip in the core we do not need to return anything because it's again we have signature as a void so it is going to be have to swap the same character area now let us run the code okay it could submit it or it got compiled now let's submit the code okay it got accepted so that's it in this video hope you liked it please add comments if you have a different approach or you are looking for a solution for a different problem thank you guys
|
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
|
967 |
uh hey everybody this is larry this is the 18th day of the leco daily challenge for august uh hit the like button hit the subscribe button join me on discord hang out and let me know how you feel about you know everything um okay jay's farm is numbers with same consecutive difference return all non-negative integers of return all non-negative integers of return all non-negative integers of length n such that absolute difference between every two consecutive digit is k um note that every number in the answer must not have leading zero except for the number zero itself okay for example okay yeah uh you may return the answer in any order okay so and okay so there most nine digits so i think you can boot force this um in the worst case huh what is the worst case right so i guess the worst case is something like two to the nine is my guess because if uh k is one uh then you just go up like every at every point you can choose to go up or down uh so that's kind of my guess so i think from that i could prove first uh there's some you know care that we have to do so that you know we remain the first digit isn't zero but otherwise i think we're okay so yeah let's get started and let's just have and i'm going to be a little bit lazy and just have a global results non-local results um yeah let's just go non-local results um yeah let's just go non-local results um yeah let's just go recurse let's go to current number uh last digit and digits left and of course these two things are directly dependent on each other so it doesn't really matter but it just makes my math a little bit easier i think um but yeah and then we want to okay so if digits left is equal to zero then we can just uh result start append current and because so the thing i'm thinking now is whether there will be dupes i don't think this should be dupes because there's only one way to arrive at any unique answer so uh so i think that should be okay um we'll double check that in a second uh yeah and then now we just do a four so now we know that again right last digit we know we only need to go up or down so we can just do that uh by going okay if last digit plus k is less than or equal to nine then we recurse current times ten plus uh that's digit plus k uh the new state is that the last digit is that digit plus k uh let's actually rename this so that it's a little bit easier to understand the new digit is this thing uh and now this is just you know shift and then add a new digit this is the new digit that'll be the next digit and then digits left minus one right and then we try again before subtracting right so that's digit minus k if new digit uh is greater than or equal to zero recurs current times 10 plus new digit again new digit digits um minus one right so actually i mean you can tell there's some duplicate here so we can actually you know refactor this really quick uh because i don't know i'm a little bit annoyed about it but uh yeah for let's just say d for direction is how i import um in uh one negative one uh and then it's just this right d times this uh okay so i think that should be roughly good uh kind of we have to handle the leading zero and stuff like that but that's kind of let's take a look at what this gives us and this actually the kicking off is not correct either but um is it n that's the digits no yeah but i just want to see whether that you know the recursion is okay um now see if we get the right thing so we kind of get things okay uh this makes sense uh again like i said we didn't really kick off the recursion correctly so now we just have to uh brute force the first digit right so now for first digit and range of and we can have it as zero so we can just go from one to 9 inclusive which is 10 exclusive and then we just recurse on that um our first digit is just the first digit our last stitch is also the first digit and then it's just n minus one uh because we use one of the digits as the first digit right so also we have to put in uh two one and let's do 99 for fun though actually i think nine one maybe the more interesting one uh and also maybe just nine zero okay let's run it again uh okay which one is this nine one do i not do zero huh i think i'm missing something no this is here but i'm wondering why i'm not getting one zero um this should be okay is it just not sorted do we have to sort it you may return the answer in any order okay let's just sort the results real quick so that i can see whether you know and i don't think like the order doesn't matter but i want to make sure that my answer is correct right that's the obviously more interesting part uh okay so it does generate it but just not in the oh because i did the ad first so i think if we had just done if we just do the negative first then i think we should get the um get the same order but okay so now it feels good it looks good and i'm feeling good so let's submit it um and we probably test most of the cases so ooh oh i did forget okay that's annoying but um i did forget about that case where it literally tells you except for the number zero itself right uh and there's only one case where that could happen which is when um when there's only one digit right and i am a little bit careless on that one uh so yeah let's see i just want to see what this answer is that's right okay still the same thing so i think this only comes up when n is equal to uh one so let's just put it manually submit yolo submit uh oh i did get duplicates because of z oh okay i thought i had a case for this for oh no i did i do nine zero that was just arrogant on my part i definitely should have checked that um i guess so hmm i guess i didn't really look at it too carefully i missed that's so you know one thing is to uh i guess i should have just clicked on this button but you know it's one thing to test the other is to look at your test results uh which i kind of you know made a mistake on um but uh yeah so we just have to the only time you have duplicates is if uh k is zero because then this happens twice right so hmm do i want to hack something to it okay fine uh okay fine i'm just gonna hack something into it but definitely i hope as long as you understand the how and the why then it's okay um my computer's a little slow yeah as long as you understand what's going on then i you know you could hack it however you like uh just as long as you can justify it and this looks better uh show def seems to be okay i just had to press that button apparently uh so now let's submit it and it's good uh yeah so what is the running time uh again if n is the number of uh digits um you can see that we for each one we can add most branch two ways uh so that means that it's gonna be about roughly two to the end give or take uh times like nine or something like that right uh so but still basically of two to the n um and again of course that's uh assumes that n is the number that you're given and not the um and not the data or sorry the storage size of the input size which is in this case the number n is represented by log n bits so technically speaking this is a linear algorithm because for every bit you're doing one recursion or two recursion i guess actually but um but yeah uh yeah that's all i have for this problem uh k didn't really matter space is obviously same thing because you need one for every output uh but yeah that's all i have with this farm let me know what you think hit the like button hit the subscribe button now see you out tomorrow bye
|
Numbers With Same Consecutive Differences
|
minimum-falling-path-sum
|
Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n = 3, k = 7
**Output:** \[181,292,707,818,929\]
**Explanation:** Note that 070 is not a valid number, because it has leading zeroes.
**Example 2:**
**Input:** n = 2, k = 1
**Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\]
**Constraints:**
* `2 <= n <= 9`
* `0 <= k <= 9`
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
1224
|
160 |
Jhal Hello Hi Guys Welcome To Questions Today's Questions In Section Or Black List In This Question Behavior To Write A Program To Find The Point Note Amity International Tourist Begins For Example c3312 Link List And Where To Find No Date With Flute To Liquid Suryavanshi President Kshatriya Egg Not being can find another example Video not Which will have to subscribe to that Atul English Vinglish's sweater return channel is a and with that they do it a no see what to do the first form will calculate the first of all they calculate the length Of bodhi link list should this point is point to the head of muslims and this point is point don't hear it black list increase length of buddhishma list listen straight length office printed this white handi length office setting list s 600 middle east is great think He Should Avoid You Should Believe It Is Great Dental Implant In This I Will Now Will Make The Point Make A Pointer And This Saliva Water Request Move Forward For A Day Before But By Wise Notes Pimple Different Buddhi List Idet Si Dil Length Li Related To Short Fiction and Differences in the Land of the Difference Between the President Is the Point to the How to Tear to That Not Because of Which Is the Difference of One Not from the Head of the Black List Suno After Difficult to Give One Step at Every Step And After To And Video Subscribe Cycle Intersection Of Length Point To That Point To For This Here Don't Know Difference Between Delhi To List Soe Dandruff Dhandhe 851 Convertible Point To That Point Intersection With No But In This Case Was With 300 Bones But What Will Happen When Will Not Be Interested Not Find The Intersection Of Defiance Luta The Awesome To-Do List In The Mid-Day Hai Otherwise To-Do List In The Mid-Day Hai Otherwise To-Do List In The Mid-Day Hai Otherwise 220 Not Believe Any Intention Was Not Present Dissimilar Dare Will Be Ki Goddess Anal Jewelry Anal Point Till It Means Curd Is Two Points Dr Two Points Will Convert Which Will Find A Chandra Additional Revenues Have A General Value Silai In This Case Is At Minutes Exam For BSL English Is Greater Than 20 Ver Deposit Of Everything From Wishes For Interview After Chanting For B Ek bano dal very move forward in bits and pieces with one not and with someone not both internal pointer directly this hair oil communal and he will also come in al subah fog points will intercity channel delhi novel in this benefit will entertain not and with the intersection Present in all it's friday co.in's intersection Present in all it's friday co.in's new record of this question too fast for will take that dip temple which will be settings least bit difficult buddhi hai day which did not least notes4 yes note star temp 252 head bhi normal itni lens album The People 208 Alto 120 Now Be Aware A Temple Run Is Not Equal To Null That Album Plus Seat Rapid Action Force Link Is Android Device Temple Is Equal To A Temple Next9 Similar For Similar To The Second Rank List What Will Happen Will Rise Similar Loot Birthday Devi Temple 2 And He Too Was Being Able To Together Updated And A Tattoo Physical Temple Next Water Hearts Were Torn The Length After Least Not Give Any System Temple With Her Debut As A Day And Time 2012 The Head Bent North Sea Welcome To Retail V Jheel Si Album Is Greater Than To Say The Least 122 For 10 Days Album - Alto Album - Alto Album - Alto Ki I Plus Will Update Attempt Variable Temple Run Temple 1222 Temple Next K Last Lali Effects The Winner And Will Be Better Than Album Subah Dal Kharif Crops Per Ko Handle Dual To - 11th Handle Dual To - 11th Handle Dual To - 11th I Faltu - Album Dance Plus Hai I Faltu - Album Dance Plus Hai I Faltu - Album Dance Plus Hai Little Baby Time To Who Is Equal To Tempo Next9 What Will Happen Not Every Situation Will Be Appointed Starting Method Same Relative Se Related Position C But Biscuit Settings Of Heaven And Bases Position After 10 Chapter 1 Hour or Half Hour of Delivery Pollution Oil Are A Temple Not Equal To Take Two To Ki Dominant Temple Run Tattoo Etc. Breaking Management Temple Will Be 10 Point Interaction Between Two Will Do Temple Is Equal To Temple Next Ki Hand Tattoo sorry time to is equal to time to next9 members were that half after the might look peace initiatives temple will welcome equal viral absolutely infection impound tiffin training respond dengue hai vikram give equal find android smartphone and temple run vikram tap morning Simply Written Test One From Air Pollution Revolver Content On Also This World And A Good Night System Decode That Medical Code Setting Understanding 800 Alto Quality Time Complexity Of This Question Is Bell OnePlus And Shadow Of Album Plus Two That Is The Length Of Lemon Juice One and Reduced to 100g Cheese Relative Video Thank You
|
Intersection of Two Linked Lists
|
intersection-of-two-linked-lists
|
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
For example, the following two linked lists begin to intersect at node `c1`:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
**Note** that the linked lists must **retain their original structure** after the function returns.
**Custom Judge:**
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
* `listA` - The first linked list.
* `listB` - The second linked list.
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
**Example 1:**
**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
**Example 2:**
**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
**Example 3:**
**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
**Constraints:**
* The number of nodes of `listA` is in the `m`.
* The number of nodes of `listB` is in the `n`.
* `1 <= m, n <= 3 * 104`
* `1 <= Node.val <= 105`
* `0 <= skipA < m`
* `0 <= skipB < n`
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
599
|
279 |
hello friends now let's solve the purple squirrels problem Nancy a statement given positive integer and find the least number of contexts where numbers for example 1 4 9 16 which some two and lastly example any caught your health and the result should be 3 well how do you think about this problem we are given 12 then we will the very intuitive ways we try every perfect square number that is less than 12 so we will try one and try for and the not so basically we will if we use one then we will try to find the minimum squirrels 11 right you should have minus 1 and if we use for we are use minimum squares try for a minute cause I know 12 minus 4 and then we will keep her finder so for this 8 we will still needed to find the minimum square numberless equals 1/8 and then we will also try to equals 1/8 and then we will also try to equals 1/8 and then we will also try to find the minimum squares that I will P so 8 minus 1 right and what if we try 4 plus minimum squares there will be 8 minus 4 it's four right so you will see they have many of lapping subproblems so the obvious solution is to cache the results and also this problem have an optimal feature which is to felissa number so you will um you have to come up with their dynamic programming solution because TP is very suitable for the optimal substructure and overlapping subproblems so how do you find the relation basically it's the same like the recursion the difference that you catch the result of the previous problem so as we want to find the least number of political numbers open we will eat neither integer array and asides through the pizza and plus one why because we only can find use the pub integer and first we need to initialize DDP with other reason is that we want to find the least number so we should I initialize the array to the larger stir very well first of all and also for any even integer like supporting we can always make up this process square I just use 15 one so there the maximum number should have be the size oval and deep hit zero shoulda beena shy to zero and deep he 1 should be 1 right because of this number to make happen 0 and wash the beat 0 1 now we just try to make up her let I start from one i'll a circle then and I plus the minute there's a we try to find the least number to make up I and I will start from 1 to the N the reason data we can sing like this way is that the following element will not be affected oh I'm sorry the previous element will not be affected by the following element was there me if you will we can find the minimum number to make up this for even if a we will calculate five outwards the mini manometer makeup before will not be affected by the five and by the six so on so forth so the which means the previous elements are independent so and then we will for each given element I we will try to use the purple squirrels to make habit so we should use it J times J is weaker than I what the reader will use the Europe because they all may be the one so we can use them yo J plus and we want to make up of this i right so the minimum number to make half of this I will echo to the EPI minus J times J plus 1 what does that mean because the instead we'll use a perfect square number which is J times J right so we should use the number minus this value plus 1 because we can only use one element to make up this J times J so it allows so gesture return this TP okay thank you for watching see you next time
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
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. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
137 |
hey everyone welcome back today we are going to solve problem number 137 single number two first we will see the explanation of the problem statement then the logic on the code now let's dive into the solution so in this problem we are given a nums array where we need to find an element which appears once so all the other elements will appear Thrice right we need to find an element that appears only once so we need to write an algorithm which is order of n time and it should have a constant space right so we are going to solve this problem using bit manipulation technique so now we will see how we are going to do this so initially I will be having two variables once and twos where it will be initialized as 0 at the start so here the once variable will give me the element that appears once in my input array so initially I will pick the first element from the nums array that is 2. so now I am going to update the 1 once variable right so to update that I'm going to do xor operation between the ones variable and the currently picked value 2 right so the binary representation of 0 is 0s that is going to be four zeros then binary representation of 2 is 0 1 0. so in the xor operation when the values are different it will be 1 if the values are same it will be 0 right so here it will be 0 and since the values are different here it will be 1 and here it will be 0 right now we need to find the complement of the variable 2. so the variable 2 has 0 so we take the binary representation of 0 now we need to take complement of these values so we need to flip these digits so we are going to have 1 and 1 right so we are going to use this value to perform and operation on the previous answer that we got so here it will be 1 and 1. so here 0 1 it's going to be 0 1 it will be 1 and 0 1 it will be 0 and 0 1 would be 0. so here we have 2 this will be updated in my once variable so here we are going to have 2. so similarly we need to update the variable 2 so we need to perform xor operation between 2 and the current value that is 2 right so we have 0 and the binary representation of 2 and if I perform X or operation on this we are going to get 0 1 and 0s right so now to update the variable 2 we need to take complement of 1 so the binary representation of 2 is 0 1 0 and we need to flip these digits right so we are going to get 1 0 1 so we need to use this to perform the and operation right so here we are going to get zeros so 0 will be updated as my variable twos so now we pick the next value which is 2 again so we need to perform xor operation between once and the current value so here both are 2 right since all the digits are same we are going to get zeros right now we need to take the complement of twos so here we have 0 and the complement of 0 is going to be 1 and 1. so we are going to use this to perform and operation here we are going to get 0 again so we need to update this as my once so we are going to have 0 now we need to perform xor operation between two's variable and the current value so here two's variable is 0. and the current value is 2. so here it will be 0 since the values are different here it will be 1 rest will be zeros so now we need to take the complement of one's variable so here since we have 0 it will be all once right so here it would be 0 1 and 1 it will be 1 rest will be 0. so now this will be updated as my 2's which is nothing but 2. this is a representation of 2 right so it will be 2. so now we pick the next value that is 3 so we need to perform xor between ones and the current value so here it will be zeros and the current value is 3 if I perform xor between these two it will be 1 and 0s so now I need to take complement of twos so the binary representation of 2 is 0 1 0 and the complement of 2 is 1 0 1 we just need to flip these digits right so here I'm going to get 1 0 1. if I perform and operation on top of this we are going to get one zero so I will update 1 in my once variable so here it's going to be 1. so now we need to update the tools variable so here we have two and the current value is 3 so we need to perform X over here so we are going to get 1 and rest will be 0. now we need to take the complement of one's variable so here the representation of one is zero one so now we need to take the complement of this so here it will be 1 0. right and if I perform and operation we are going to get zeros so I will update this as my tools so 2's will be 0. now we pick the next value which is 2 so again we need to perform X or operation between once variable and the current value so here the once variable has one so the binary representation of 1 then we need to take the binary representation of two so here the xor between these two will be 0 1 and we need to take complement of two's variable which is nothing but 1 and 1. so here we are going to get one and zeros so now we need to update this in my once variable which is nothing but 3 here so now we need to update our tools variable so we need to take xor between twos and the current value so we have two's variable as 0 then we need to take binary representation of 2. so here we are going to have 0 1 0 so now we need to take the complement of once variable so in the once variable we have 3. so if I take complement of 3 it is going to be 1 0. so we need to take that and if I perform and operation we are going to get zeros here so I will update zeros in my so then we have done with all the values in the input array we need to return once variable as my answer so here we have the element 3 which appears wallets so this is what we are basically performing in the once variable so the xor operation between the once variable and the current value if the bits have appeared twice it is going to keep the bits unchanged also this going to toggle the bits that have appeared odd number of times right and the reason why we are taking complement of 2's here is that it is going to effectively remove the bits that have appeared twice and the and operation between these two values going to ensure that the bits have appeared once and not twice right similarly for the tools variable the xor operation toggles the bits that have appeared even number of times so here it is odd number of times here it is even number of times and it will remove the bits that have appeared twice and the complement of 1 will ensure that bits that have appeared once will be remote right and if we perform the and operation between these two will ensure that we retain the bits that have appeared twice and we remove the bits that have appeared once so it is just an opposite of what we are doing in the once variable right so that's all the logic is now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I will be having once and twos variable as 0 at the start so here we will be writing a for Loop to pick each and every value from the nums array then we will be updating the ones and twos variable using the xor and the and operation right then finally we need to return the once variable as my answer which will be having the element that appeared once in the input array that's all the code is now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
329 |
hello friends nama thought the longest increasing parts in a matrix problem let's first see the statement given integer metrics find the length of the longest increasing parts for each cell you can either move to full directions left right up and down you may not move it diagonally on move outside of the boundary weather around is not allowed let's leave this example 1 the numbers is like this along his Paris is from this one and coalesce in the coop so it's a 4 and this example we go from history and we go right into done so useful so how do you think about this problem you see if we are at c2 we know their longest path in this part so it is 3 and then we go to this one we do not have to search sure this again we just know this its neighbor to has the longest path to 3 so we just add the 3 to this one we get 4 so the co idea is to use extra 2d array if he to save the result to catch the readout every time we just need to check that a DP value equal to 0 we do the search thing if not 0 we just skip it another thing we need to pay attention to is that so when we do the search like we are at this for we can go down this is lens tube and we call to left so this is a lens to which means we can just choose one out of these four directions to plus one we cannot add all these four directions which means aratake only choose one directions this is nice into your potential tree so let's start first educate check is the metrics what you're not or matches on that zero or desitin zero and is there Rose you put your mattress darlings and colors you go to the metrics their dollars this is the deep here right so excited if you are a is rose Collins iterator this impurity for Inc j0j less than colors j+ so if the current if he than colors j+ so if the current if he than colors j+ so if the current if he IJ achieve jewish means we haven't um handled we are we such but we also need a result at first it just go to 0 if they equal to drove to the FSC and we compare the current deep he very end as a result now try to get to the larger in the final return this result now that's employment this deficit function so why do we need that you return there because and i say before we can only choose one directions to class one so we needed this to return value and we compare this for directions value that's the results and the first apparent is the matrix and the row and the column index this deep here right also we need to compare current value in the previous value so we use the previous value so there as usual the first we need to check if this index are valid so if the rope less than there or Rho greater than matrix so less minus 1 or color less than zero or color their metrics their domains - one or the their metrics their domains - one or the their metrics their domains - one or the current value is less occurred and truest values a certain zero the party is zero another thing is if their current DP they are not equal to Z which means we have already calculated before so adjuster returns this value and say I will try to care the four directions max pars matrix Rho plus 1 : pars matrix Rho plus 1 : pars matrix Rho plus 1 : left if we go to the left since then a rope stay the same column minus one and the previous value will change through the matrix row color value now I missed at this deep heat okay so the right well the right longest part will be matrix row plus 1 TP matrix row color and this Apple will be DFS matrix row minus 1 : Apple will be DFS matrix row minus 1 : Apple will be DFS matrix row minus 1 : DPN matrix row color there's a ton of ETFs matrix row matrix P matrix row and we compare this four things so we let the tip heat I think I can write another function J to get max and we will pass a basically the same okay so I just simpler right like sleep next the left and the mess is right and catch of the max of done up so we get to the max of this forehead and we plus one finally because even if oh it's the four directions are less than it the longest part should be one so it's correct wrong : correct wrong : correct wrong : so let's fill this place matrix IJ e P privet sick because and isolated l-lisa privet sick because and isolated l-lisa privet sick because and isolated l-lisa help what so the first I initialize little probably code to the minimum okay thank you for watching see you next time
|
Longest Increasing Path in a Matrix
|
longest-increasing-path-in-a-matrix
|
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1`
| null |
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
|
Hard
| null |
395 |
okay so this question is longer section with at least K repeating characters so you are giving a student s and an integer K so you have to return the length of the longer substring of s such that as the frequency of each character in Assumption is greater than or equal to K so this question is a little bit difficult for sure and without looking at other people inside I probably cannot solve it so um so here's my explanation and maybe you can just follow along so um I'm going to just go through one example and I'm going to explain how I go through okay so for the first example the string is AAA BB and k equal to 3 right so which means I need a substring from s for every single character uh has to be what at least K frequency time so the only thing is going to be this right lens access three the substrate has to be continued continuously right so you cannot say a this doesn't work because the Assumption inside this but for the B is one and others is three but it doesn't matter because you cut off at least uh at this position so the entire first uh the rest of the substring for the uh soon as that doesn't work because this is not what uh this is not about the answer right all right so uh how do I explain my example two so this solution I mean this example is way too easy to actually explain I'm going to just change it right I'm going to change it so K is still equal to 2 okay so I'm going to say a c b a and then I'm going to just say uh Z sometimes right so um in this one I'm going to uh in this example I'm going to use a DFS and with the two pointer so I'm going to just Traverse from left to right and I'm going to see if there's a if there's an index which is not um which does not uh greater equal to k then I need to split the current index uh for the left and right so I'm going to split the current index uh stream for from what from zero to okay imagine this design so from 0 to I minus one and then this is some this is going to be a left substring and then for a right substrate it's going to be I plus one two little and something like this right so um this is the example so I'm going to say I need a counter because I need to know the frequency right so I'm near I need a counter to store the valve uh to store the frequency for every single one character right so a b z right I only have uh sorry and also I have C so the frequency for a is what one two three Four B is equal to c equal to 1 is equal to one all right so this is the counter for the frequency uh I mean counter for the you know frequency of characters so and I need to Traverse from left to right so I'm giving the position the left is actually starting from zero and then right is actually started from the end which is n at the end of the string so I need to Traverse from zero to n and then I need to see if my current frequency in the content array in a Content array if the current frequency is actually less than k I need to split so contain a what at The X Sunshine is I need to split and how do I split I need to know like my Index right and the index is going to be what um it's going to be recording for sure and then I need to split my left and I need to split my right and then again on the split array I need to call it DFS so it's going to be a recursion right and then in the DFS if there is a position for the content array is not what greater than or equal to K I need to split the left and split the right and I'm not going to in I'm not going to including this uh including this chart which means I'm going to minimize the string into a substring into a sub substring and then keep going down until what the index until the index is what imagine this is uh L this is our until the air is like really equal to R and I will break and then this is the idea right so uh let's just start coding and then let's look at the constraint so it's going to be one to ten to four okay it doesn't matter or only lower case right so when you store the frequency you can just say uh C minus a right and then you only need a 26 space right for the container right and then case what from 1 to 10 to power five right so the base case for this one is going to be if s is x equal to no or extra length is actually equal to zero right I'm going to return zero all right so if the K is actually equal to what if K is actually equal to zero or one it doesn't matter I'm going to just return insta length and now it's going to be a defense right so I'm going to say DFS stream my left position is going to be zero my right position is going to be extra length my what my k is going to be what um the frequency of fluid uh the frequency of charge right so I need to declare my ends DFS string as in L in r in k so you don't know like I pass in a start length so when I want to return I don't need to say okay uh R minus L plus one right because I already including the current you know uh I mean the index is a it's already take care of it right so once I return the land of the substring I don't have to say plus one right and uh for the base case the DFS is what if L is actually equal to R right I need to return to zero because this is not valid right and I need to counter for what frequency right so from what from I equal to l i listen all I plus right so count for what a star chart at a what a i minus a plus so you can actually show you what actually rewrite chart c equal to what it's a chart at a i count for C minus a plus right these are these two lines are the same for this one because I only declare 26 space so I need to say minus a right back to here so now I need to know um uh all of my positions are all of my character I mean the frequency of a character are what greater equal to a greater equal to K if all of my characters are greater or equal to K I don't have to split um so I need a flat for split right so I'm going to the initiative true so I need to Traverse from 0 to 26. for the content array so if the content array AI if this is greater than zero right it has to be greater than zero but also if I uh if only a i if this is less than k The Flash has to be false so once I know if the flag is false I don't have to uh if a flag is false I need to split if the flag is true then I need to return R minus L because this is the length of the substrand so let's just keep going so I know from now on the flag is false which means player is a split but uh there is a split right and then how do I split I need to have a one position right I need to know which index so I'm going to say put something like this equal to one definitely starting from error right and I also need to know what is the current Max so uh this is all right so for in I equal to l i listen r i plus so if the um how do I know if I need to split I need to look at my corner array if my content array okay a star chart at a i minus a if this is less than k why do I have the red line well it doesn't matter so if this is less than K so which means I need to split because I don't need this current position this current chart right so when I need to split I need to know my result so I'm going to split the left so it's going to be split from uh DFS s and then the position is going to be starting from what pivot right pivot and all the way to I comma with the frequency of K so you can say a star doesn't matter but I like to stick to it because I know this position is a position I don't want so this is going to be a left and I need to know since I know my left is going to be starting from L to I right the current substring so imagine this is a string and then this is the split right and my eye is currently right here right and my Pivot is right here right and I already call the DFS for the left right I need to update my Pivot to what I plus one and I'm going to say I need to split my right so I need to update I need an update so pivot you go to I plus one so I don't have to go through my right string inside the if statement or inside the for Loop because I can when I when you use a recursion right you can definitely say result Master Max result and then DFS as um for the right it's going to be like pivot it's just gonna be all this is gonna be K and you'll return result and this is pretty much it right so uh this focus on this because pivot we update the pivot so you probably will say okay this uh this is the left and you might be asking like why do we have pivot at least a list in this uh again right because we update the pivot and then we're using a recursion and then the pivot will definitely change it but once you run to a line 37 the pivot is going to be on the right substring for the beginning index so this is the entire idea all right and then let me run it and submit all right so uh this question is pretty you know difficult for sure so let's look at the time and space so this is not uh these two are nothing this is definitely the hardest one we need to talk about and this is a space 26 this is what all of n right this is all of 26. and these two are pretty straightforward and this is not going to be uh this is definitely not going to be easy to explain so I'm going to say this is all of them in this one this is going to be all of that because the pivot can be what can be go through from left to right again so imagine from here to here and then from here to here so it cut every single string shoulder so this is that one uh all of them and this is almost like all of them so it's gonna be like all of n square right for the time space is constant so this is a solution so peace out bye
|
Longest Substring with At Least K Repeating Characters
|
longest-substring-with-at-least-k-repeating-characters
|
Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.
**Example 1:**
**Input:** s = "aaabb ", k = 3
**Output:** 3
**Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times.
**Example 2:**
**Input:** s = "ababbc ", k = 2
**Output:** 5
**Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only lowercase English letters.
* `1 <= k <= 105`
| null |
Hash Table,String,Divide and Conquer,Sliding Window
|
Medium
|
2140,2209
|
16 |
so good afternoon friends uh in today's video I'm gonna talk about the problem called threesome processed so uh friends in this video uh I'm gonna explain the solution from this page and it's actually I'm gonna talk about the thought process or the intuition behind how the solving this particular problem so actually this is the uh extension of the problem called threesome so if you solve that a particular problem that's fine and if you haven't sold still you can uh go with this particular solution because I will not talk about the solution or uh directly from this page so if after watching this particular solution actually you'll able to understand uh you'll be able to solve this threesome problem as well and the mean intuition of the there is a parent problem called tuition so or for all of these problems called threesome process as well as threesome the parent problem is two sum so if you know the two sum that's fine actually in this problem and in the threesome problem also you'll have to use the concept which is used in uh to some problem so two sum problem is based on sorting as well as our two pointer technique so let me first explain what the two sum problem is actually and uh I'll talk about that what is the thought process behind the tuition problem and how we do how do we optimize that particular n Square solution to the uh and Logan Solution by making use of sorting in case of two pointer so let's say I have some elements so let's say I have the element of one and five and let's see this is 7 9 and 4. and uh what the two some problem statement is you are given a Target so you would be uh given a Target so let's say let us take some different Target over here so let's say uh the target is what the target is uh the target is 11. so the problem statement of two sum is you have to figure out such a pair uh in this particular array whose sum is uh whose sum is add up to this 11. right so you have to find a player whose sum is equal equals to 11. so what could be the Brute Force solution so the simple Brute Force solution is uh is to check all possible pairs so there are obviously total nc2 or pairs so what you could have done you can just uh figure out or you can just explore all the possible Pairs and you're gonna get any such uh payers whose sum would be equal to the given Target then that would be our answer and that would be obviously the order of n Square approach so what you would have done you will make use of one outer for Loop so in I is equals to let's say 0 and this will go till I is lesser than n and I plus so you will have one inner for Loop so inner for Loop will run let's say in r j is equals to I plus 1 just next to it and J would be less than n and J plus so now here what you have to check you just have to check if uh your uh let's say ARR of I plus a r i plus a r j is equals to if it is equals to your given Target uh then what you need to do you can just return that yes uh this pair exists so you can just return true right and uh finally if it doesn't exist we will finally return will be returning false over here so this is this simplest solution which you can solve this uh in order of n Square so now you can optimize this particular solution to the uh order of analogon solution so in that particular solution what you do you just first sort all the elements and after sorting you just apply the two pointer top technique so what you do we uh you just sort of these uh all the elements so after sorting what you're gonna get one and then four and then five then seven then nine and oh you're obviously the target is still 11. now you have to find such a pair whose sum is equals to 11. so now how do you apply the two pointer technique over here so what you do you just take two pointers let's say this is I and this is G right so you'll be starting one of the pointer will be the front of the array and the another would be the last of the last element of the array so you just add up these elements what you are getting 10 so 10 is obviously lesser than 11 fine so if 10 is uh lesser than 11 so it means you want to get the greater value or you want a pair whose sum is greater than 10 so that's why what you do like what you do if you will just decrease this G then you know the value to the left side of this pointer J left side of this particular value 9 would be lesser than this so that's why you will uh you will not able to get a pair uh whose sum is uh greater than the 10 so there is no use of just decreasing this particular right now at this point of stage there is no need of uh decreasing this point of J because you want to get a payer which uh whose sum is greater than this 10. so what you do you just increase this g i so obviously what you can eliminate because this I this one will never able to contribute in a pair whose sum is equal to 11 because you have added that particular uh um one to the greatest value which is 9 and still you are getting the values is lesser than 11 that's why this one will never contribute in your answer that's why you just increase this I by 1 and now your I will be pointing over here so now what can happen you can just see that now we are getting uh the sum which is equals to 30 and obviously you can understand 13 is greater than 11. now what you can understand the value uh since uh this summation is 13. so you can just see if for this particular 9 if you see all the elements which is uh right hand side of this four those are greater than 4 so obviously this 9 if this will uh add up with these values so you will gonna get the sum which is greater than 13 so that's why you'll never able to get the sum 11 because all these are greater than or thirteen greater than 13 I are greater than 11 so that's why in this case you can eliminate this nine you can eliminate this line because your this 9 will now over your nine will not gonna contribute in any of the answer so that's why you will decrease J by 1 and here uh you will be here so now when you will add up you are getting what you are getting 7 and 4 which is equals to of 11 right yeah so 7 and 4 is equals to 11. so what you are getting so obviously 7 and 4 is equals to 11 and you your target is 11. so in this way you got your answer and finally from here only you will get a return true because you've got a pair who some uh summation is equals to 11. so in this way you have to make use of this two pointer technique to solve the two sum problem so the same approach uh I mean the same uh two pointer techniques we're gonna use in this three sum problem as well three sum project so now actually here we have to select uh two element only right but in this problem what we have to select three elements what do you select we have to select three elements so now how we can decompose this problem to the two pointer problem so let's say that's fine like let's say if I have chosen one element I have already choose right if one element I have already chosen what else I have to do obviously I have to figure out two elements now right now because after choosing one element I can just say key I have to figure out now two elements so on those two elements like initially there was your target like uh let me say still your target is equals to our let's say in this case your target is uh 10 right so if your target is 10 and if you have chosen 7 right now so what would be the your new Target your newer Target because you have chosen one element so your new Target would be uh your actual Target minus uh the current element chosen so your actual Target was 10 so 10 minus 7 is what 3 so now you have to apply two pointer technique on this particular new Target called three so now you'll look here whether you will able to get three or not and if you are able to get 3 that's fine and or so in this way uh since you can see that there's no pair whose sum is equals to 3 so that's fine so in this case you will now uh this element you have chosen now you will try for the second element now you will choose this element and now you will see that whether such kind of pair exists or not right like in this case you are choosing one so before this obviously you will have to sort all these elements uh I have to sort for this obviously because uh you cannot apply the two pointer technique or without sorting you cannot apply so first you'll sort these elements and then obviously you're gonna play so in this case what you could have done if you have selected this uh finally at the end you will be getting this 5 and 4 9 and this would be equal to 10. so in this case also we're gonna get a triple triplet from sum is equal to 10. now actually this problem is all about fisa now this is a very small uh variation of this problem very small which is called uh closest right so in this uh threesome process you have what you have to do there is no need to find the exact uh Target uh the sum which you need to find that is not the necessary to be equal to the given Target you just have to find that is as much as closes so it could be equal to the Target as well and it could be uh anywhere it could be greater than that it could be lesser than that but you have to figure out such a triplet whose sum is as much as closest so uh what do you mean by as Mrs closest so if you have some value let's say if you have right now only you have the target 10 and let's say if you are getting some value some answers you are getting uh let's say one of the target you are getting eight and one of getting 11. so which value is closer to this than how you can figure it out let's say one another value called 10 is also there so if you how you can figure out so if you will tag on number line if you represent so you'll be able to figure out so if you will take the absolute difference between all the values so let's say absolute difference between this is true so here uh what other things I'll need the difference so initially I am taking my difference as int Max let's say this that is of a very far away from my Target and finally I'll be taking one answer so I'll uh the answer the final answer some I'll get i'll store into this answer variable so here in I is equals to 0 and I is less than n and I is I plus so here this for Loop will be choosing the outer elements one element and then rest of the element apply the two point attack so my new Target would be as I said uh that would be nums of Target minus Norms of I yeah and J is equals to I plus 1 and K is equals to n minus 1. now I have to apply the uh two pointer technique on this rest uh less number of elements so here I'll check that if uh nums of I uh nums of J plus nums of K is let's say exactly equal to your new Target if this is exactly equal to your new Target the it means you get such a replay whose sum is actually or to your given Target so here in this case you can directly data there is no need because this is as much as mean as possible since absolute difference will gonna be equal to zero so now there would be no other pair which would be as much as near because this is exactly equal to the given Target only so here you will be gonna do this and now what you will check if your difference is get greater than the absolute of uh absolute of numbers of I plus nums of G Plus numbers of K minus your actual Target if it is if your this difference is greater than uh the selected triplet then what you will do you will just update your uh you're gonna update your difference to you're gonna update to the new difference over here and in this case uh since this is a beta answer which we're getting so that's why what you will do here uh you will store your new answer over here in your answer variable yeah and finally what you will check if your nums of G plus sums of K is are greater than your new Target then what you will do since this is greater than your our new Target so you want lesser value so you'll just decrease your K by 1 and if it is not the case then you will just increase your J by Y and finally what you will do you will be returning the answer so hope this is clear uh the approach which I explained I just uh coded over here so if I'll run this solution let me run this oh yeah so let me submit this so yeah it's accepted so hope this is clear and actually I just want to mention that I have created one of the post over here as well so I'll be mentioning the link of this in the description of this video so if you want to read out this particular article this is the same here I have explained actually I have given the code as well you can see the python code you can see the C plus code everything I have given here so if you want to see that post also you can check out the description so thank you so much finally thank you so much for watching this video and if you like this video do subscribe to my channel if you are new to my channel and uh stay with your friends and like the video and we'll meet in the next video thank you so much thank you
|
3Sum Closest
|
3sum-closest
|
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
**Example 2:**
**Input:** nums = \[0,0,0\], target = 1
**Output:** 0
**Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
**Constraints:**
* `3 <= nums.length <= 500`
* `-1000 <= nums[i] <= 1000`
* `-104 <= target <= 104`
| null |
Array,Two Pointers,Sorting
|
Medium
|
15,259
|
34 |
Doing latest problem cold find first and last question of element in water a day Jai Hind is question you can just read that they can return minus one is element did not exist and which can simply do this question in vivo and complexity of light which Uses for loop in this question but will lead to solve work that has formed a city of login suhaag tweet celebs on certain already they can apply for binary search and checking element exists or not but its elements are one thing they can apply for brain research on both loop Android Side of Fund Index vs Modification in our Binary Search If you want full solution and explanation Please subscribe and comment
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
120 |
hey everyone welcome to lead code programming solutions my name is funny and let's get started in this video I'll be talking about the problem triangle minimum path Sun so what's the description given a triangle find the minimum path sum from top to bottom at each step you may move to the adjacent numbers on the row below so what does that mean let's take a look at this example here so we have four rows this is a triangle at row 0 we have element 2 and we don't have any other number so we'll have to pick this number to find the minimum path some at fro 0 we'll pick two at Row 1 we have a choice we have we can either pick 3 or 4 since we need to find the minimum path some so we will have to choose 3 at Row 2 we have a choice between 6 and 5 7 is not an option because it's not adjacent to the number that we chose in the previous row so 7 is not adjacent to 3 now between 5 and 6 since we need the minimum it's 5 and similarly we'll pick one from the next room and here the minimum path sum would be equal to the sum of these numbers and it's equal to 11 so now how do we solve this problem so we'll use dynamic programming to solve this problem now let's take a look at the example again the idea here is pretty simple we'll start from the row just above the last row so in this case it's Row 2 we trade through each of these numbers in this row so for every number add the number with the minimum of the two numbers just below it in this case it will add 6 with the numbers minimum of 4 + 1 which is 1 so we let 6 with one of 4 + 1 which is 1 so we let 6 with one of 4 + 1 which is 1 so we let 6 with one and get seven similarly if you take five we'll add five with the minimum of 100 so it's 5 plus 1 is equal to 6 now we repeat this process by going back to all the rows up until 0 and we would have found the minimum path at row zero so whatever value that we get after doing this iterations so that will be the minimum path now how do we solve it using dynamic programming so first we'll make a deep copy of the last row so we'll call it DP now like I said we'll start from the row just above the last row in this case it's row 2 now let's look at the algorithm so here we want to calculate the sum of the number with the minimum of the two numbers just below it so triangle of row column gives that number and minimum of DP of column and column plus 1 gives the numbers just below it and we'll update this index here after doing this computation so let's look at a star will run here now DP of 0 will be equal to triangle of the second row and this column so it will be 6 plus minimum of 4 + 1 which is 7 and 6 plus minimum of 4 + 1 which is 7 and 6 plus minimum of 4 + 1 which is 7 and we'll update this TP with that value now let's move to the next column so we want 5 so we're moving to the next column here triangle 2 one will 0.25 and me and here triangle 2 one will 0.25 and me and here triangle 2 one will 0.25 and me and the numbers just below it is 1 and 8 so minimum of 1 and 8 so in this case 5 plus 1 it's equal to 6 and we'll update this value here similarly we'll go to the next column and this is triangle of 2 & 2 which is 7 and this is triangle of 2 & 2 which is 7 and this is triangle of 2 & 2 which is 7 plus minimum of 8 & 3 in this case it's plus minimum of 8 & 3 in this case it's plus minimum of 8 & 3 in this case it's 3 so the sum is equal to 10 now this got updated after this we cannot move to column 3 because if you see in row 2 we have only columns from 0 to 2 so it's rewrote 1 & columns from 0 to 2 so it's rewrote 1 & columns from 0 to 2 so it's rewrote 1 & 2 now we will go to Row 1 and move to column 0 so we see the computation again TP 0 will be triangular 1 0 which is 3 in this case plus minimum of 7 & 6 which in this case plus minimum of 7 & 6 which in this case plus minimum of 7 & 6 which is 6 and we get 9 now DP of 1 will be equal to triangle of 1 which is 4 plus minimum of 6 and 10 so it's 6 so we get 10 now after this here row 1 has two columns 0 & 1 so we are row 1 has two columns 0 & 1 so we are row 1 has two columns 0 & 1 so we are already at column 1 now we will move to 0 & 0 so here D P of 0 will be equal to 0 & 0 so here D P of 0 will be equal to 0 & 0 so here D P of 0 will be equal to triangle of 0 which is 2 plus a minimum of 9 and 10 it's 9 so the value is updated and this is the minimum path same that's required now with this understanding let us write the code so for this problem I am using Python 3 because it's much more 6 int the same algorithm works in Java as well okay so what we want is a variable called EP and we want to store the last row of the triangle list so we'll make a deep copy the deep copy of the last row of the triangle - one that gives me the last row now we - one that gives me the last row now we - one that gives me the last row now we want to iterate from the last but one row until row zero so we will say true in range the length of triangle and then minus two gives me the last but one drew I wanna loop until index zero so I have to give minus one for that because it's exclusive and since I'm decrementing every times I have to commend the minus one and I have to iterate through for every row now I have to iterate through every column so four column in range of from zero through until every column in that room so I have to give row plus one because its exclusive again fighting this range function now what we want is TP of column is not how or we'll do this we will say triangle this is the number that we want to add with the minimum of DP of column and DP of column plus one so this is the previous row and now let's return this DP of 0 so this is working okay so this is working perfectly now before leaving I want to show something so if we don't make a deep copy and then if we just do a shallow copy right so if we just do this what actually happens is before I return it I'll just do a print of my triangle so this is my original list right so I'll do a print of the triangle and run this code and what happens is my original triangle list got modified because I didn't do a deep copy and that's the reason we have to do deep copy we don't want to change the source so thank you very much for watching this video I hope you liked it please do subscribe for more videos thank you
|
Triangle
|
triangle
|
Given a `triangle` array, return _the minimum path sum from top to bottom_.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row.
**Example 1:**
**Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\]
**Output:** 11
**Explanation:** The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
**Example 2:**
**Input:** triangle = \[\[-10\]\]
**Output:** -10
**Constraints:**
* `1 <= triangle.length <= 200`
* `triangle[0].length == 1`
* `triangle[i].length == triangle[i - 1].length + 1`
* `-104 <= triangle[i][j] <= 104`
**Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
| null |
Array,Dynamic Programming
|
Medium
| null |
516 |
hey everybody this is Larry this is day 14 of the leeco daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Palm which oh wow we haven't done it before yay 516 longest parodramic subsequence hit the like button hit the Subscribe and join me on Discord uh what is this about give me the string s find the longest paradramic subsequences length in s uh seems like we're back to dynamic programming usually these kind of I mean I don't know about why did I say even usually uh it's a little bit I mean medium is probably right but it's still a pretty hard medium if you ask me um I mean it was it's one of those poems that I kind of talked about in the past in the realm of okay a lot of people have seen this Farm before or similar problems to this before so it's not a hard medium per se but if you were dissolving this from scratch or you know with not that much practice this is pretty a hard medium uh they're pretty difficult but in any case okay uh so the excuse me foreign I try to I'm trying to remember literature here and try to think if you can do better than n square and square is a pretty um pretty straightforward uh well maybe I can say this before I get it right but uh put it but um yeah pretty okay kind of uh dynamic programming so let's just get to it then right uh and we'll see if this is fast enough um one thing that I wanted to do and get practice on is debugging C plus um so I'm gonna do the code in Python now and then we'll try to do C plus by asking out my one of my good new friends Chad GPT uh and then we'll kind of see because for me it's about building up the confidence that I have on chat GPT C plus as well which you know maybe that's the whole thing if you're following my Saga about q4s and python you'll probably get why okay so yeah so now uh let's do a uh get longest right um you're gonna have left and a right and the idea here is that you're going to try to find the paradramic subsequence from the outside in right and then now you have a left and a right um and for us they are going to be inclusive bounds um yeah you have inclusive bounce you go you know you have the left bound outbound you just chop chopped characters from 11 chopped cow just from the right and then work your way in so if left is equal to right then you have one character left and that's going to be one because that's always going to be a palindromic subsequence uh otherwise if s of left is equal to S of Y then well you could do some calculation it might not be the best thing but the one of the best things you can do is and we might have to make some optimization but that's fine uh Max of get longest of left plus one uh oh right minus one plus two right I also need to do uh if left is great and right returns zero just to be lazy on the other conditions but yeah okay otherwise then we can either just skip the left or skip the right so the best is going to Max best get longest left plus one right or get longest Left Right minus one right and then return best maybe that should be good so now we return get longest from zero to n minus one um let me kind of run it real quick it looks okay I'm about to hit submit but not really right because we always set this to this dynamic programming the good thing is that we only do um we only do uh like five operations or something like this right for each one so yeah what a number of inputs right n left can be zero to n uh y could also be zero to n kind of I mean here we have an invariant that left is uh less than right or equal to I suppose so it's gonna be n choose two or n Square over two ish which is still o of n Square obviously but in running time sometimes it matters right so that means that total number of inputs is O of n Square foreign takes all of one time so total time is O of N squared time yeah and all of n Squarespace as well if we remember to memorize which we will do right now right so DP um our usual way right um yeah something like this right uh and then now here we go if has cash of left right then we return cache of left right I write this the same way so hopefully this makes sense uh usually this is actually a very good uh test for my chat GPT thing okay so this looks good um I want to try a big case so let's do that's 10. right that's 50. that's a hundred should be a thousand let's see just running for the benchmarking uh one second looks kind of what I roughly expected so let's give a submit and hopefully uh we don't get you know screwed by the code python uh okay that's I mean I expect this to be slow so yeah I mean it is what it is but I mean uh there are a couple of reasons here um but this is gonna be so yeah just to go over it is O N squared time and square space just to be clear um there are some optimizations that you can make um first is that here we always allocate exactly n Squarespace like we said there's some optimization you can make about recognizing that left is always less than right so then you can you know half the space right there almost technically of course the diagonal but more or less half right um and that would make um because a lot of this running time is also just allocating n Squarespace you know uh and for each problem that may add up I don't know right um the other thing you can do is writing your bottoms up just has a lower performance profile because you don't have to do uh push stuff on this push stuff on the stack you don't have to allocate extra stack space you don't have to make extra function cards which are slightly expensive in Python uh and the other thing you uh is that after you do that you may be able to recognize that you only um uh you only need the last if you do it correctly you can do a space optimization trick that should reduce it to just linear space and you can check that out I have a video on dynamic programming progression if you search for that hopefully that should come up for like Library dynamic programming progression or something like this on YouTube and yeah um not actually doing that but that's basically the idea uh okay what else um okay I am going to try to see uh paste this into chat gbt convert to C plus please and I just want to see how good um how good it is I'm doing it off screen I don't know why just in case I have some really you know Chachi PT and I go way back we've been having really deep heart-to-heart conversations uh that I heart-to-heart conversations uh that I heart-to-heart conversations uh that I want to put on screen all right okay yeah and this is very long okay fine all right let's see if C plus is Gucci here that looks okay they have gotten better though I feel like let me try to hit a submit and see if I got anything wrong okay so that's good too uh also I guess the same performance profile so if it's still way faster than and a python version as you can see which is why I'm practicing and just kind of get a few of C plus timings on the code in general but uh I feel like in the past they didn't well they also converted the comments thanks but I feel like in the past they didn't always know how to do Anonymous functions um but having that them or maybe I've been converting to Java so C plus obviously has it but I don't remember if chat gbt converted them uh but now that they converted them then maybe it'll be a lot you know like the coach should translate more one-to-one so a few mistakes one-to-one so a few mistakes one-to-one so a few mistakes um the thing that I did do here is that I was using um I was doing explicit cash versus like using memorization so let's see if I can use uh let's say if I did this we went up not being uh we didn't know to translate let me also try again thank God which window do I have oh there it is to see first piece thank you my chatbot master has to do that thing where it types it out so otherwise it should be just instantaneous if you ask me I don't know how uh if that's there's a setting let me know I don't know if that's just like me being silly um all right apparently just like a decorated let's see if that works foreign oh it's slower hmm why is it slower hmm I guess it's slower because it's using an ordered map instead of whatever but that's unfortunate though right hmm uh this is even slower I mean um I could see why it's slower because it's using Maps instead of vectors like the previous one but that's going to be annoying to do let's see what happens if I change it to use lru cache does it do anything different hmm this is why I'm learning friends hopefully this is entertaining for you uh I'm just trying to figure things out a little bit now it's still uh no hmm you think oh you cash it you sister because it doesn't used to decorate a function now that uses uh oops huh because then now it doesn't use The Decorator you just use the maps directly which is half as fast uh let's see is it faster with a regular map I guess not so that's man that is slow let's see if that's fast enough still too slow what was my original timing on the one that did pass on this one um interesting oh wow this is way faster so I guess the key thing is you know use vectors instead of maps hmm I mean that's how I would do it if I was writing C plus from scratch I was just wondering where I can like what did the extent in which I can do these you know okay I guess we have some idea but yeah uh I think that's what I have for today and this problem um I don't know that I explained it I think I've missed explaining this poem in detail to be honest uh but basically the idea is that if they're the same you know then they add uh you might have already missed this part but I'm gonna explain it here then but yeah if they're the same then you can add two characters right and one characters in the middle because there's always you know there's only one character left that's the character in the middle so then now you get this plus two thing and uh and yeah and then this is just a skipped left and then skip right but yeah um yeah I think that's what I have for today though so let me know what you think if you have questions please ask in the comments uh I do read them I might not you know I and I try to factor into the next explanation obviously I'm if you're watching this the video is already out and there's no edit for video and this is in the Stream So yeah but anyway um uh stay good stay healthy to good mental health um yeah have a great rest of the week and Friday's coming up so I'll see you soon uh goodbye and take care bye-bye
|
Longest Palindromic Subsequence
|
longest-palindromic-subsequence
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
String,Dynamic Programming
|
Medium
|
5,647,730,1250,1822,1897,2130
|
59 |
Hello gas, I am Lalit Agarwal, welcome to the country, today's late problem, what are you saying? Okay, before the problem, 1 minute, friends at the station, they have understood this problem very well and those who want to try it themselves are the six. Look, this question has come literally, if you had asked yesterday's question then it is exactly a singular question, there is no much difference, just what were you doing there, if you were doing your travels, then driving is the same. After that, I was nourishing the value stored on my hand in my own words, what I have to do here is to reduce it from my own, but here on the vector I asked, after turning on, I have to turn on something in the matrix and what will be the value now here. What value will you put on the pay? To do the value you will have to maintain a counter which is 123 meaning Kal Vijay is running it, that's it, you have to do something in it too, you have to bag something in it too, it takes it anyway. What needs to be kept in mind in this is that after extracting the value from your matrix, what to do in it in your answer? Where will you have to push back the value in the matrix ? You will do some bags in the ? You will do some bags in the ? You will do some bags in the matrix. You will have to maintain a counter which will run serially. There are 123456 sands on serial wise and off discussion is all that is needed, think a little about it and if you have not practiced yesterday's question then please go and practice yesterday's question. If you have practiced once then this question is literally. It will become very easy and if there is any doubt in yesterday's question then you can do yesterday's video, it was not a very typical question, it will be very easy to write on YouTube, the last video you will get is from yesterday. It is just a question, okay yes, okay, now let's discuss our question here. Now, for those who have not understood the problem, there is no need to take tension, first of all we are going to understand it very comfortably. What was the question? After that we will approach it and give the final bill versus implementation. The question was very simple. I have given some character named N to myself. Practically what does it mean? What is the meaning of this. Tell me what is the final bill versus implementation. There is a matrix, there are 3 roses in it and by three pen I mean the matrix of three crossed three. This N is telling himself only this much, apart from this he is not telling anything else. He said, ok, it is a simple thing, now I understand three. If Cross Three has its own matrix, if we go to fill it in our Puri, then how can it be a flower, only one said, one, you mean, how many elements can come in it, atmospheric, new elements will come in one row, three elements will come in each row, then 3:00 How many elements did you have till 10 o'clock? 9 3:00 How many elements did you have till 10 o'clock? 9 3:00 How many elements did you have till 10 o'clock? 9 elements, it's a simple thing, yes brother, it's a simple thing, it's over, something is fine, yes, it's very good, now what will happen here, now do that, nothing, you just have to make a matrix. And in this matrix from one to nine, because today I can enter this item, I have to get all the elements from one to nine solved back, but now how will you store yourself in this form, like one you Three will come here first and then after that it will come in this order. Give 45 in this order, 67 density means four plus, after that come back and repeat the formula again and again. What has to be done is that a counter will have to be maintained which keeps on incrementing and Apna kept getting it stored, he said, it's a simple thing, now how will we do it, let's take a quick recap of tomorrow, he said, look, Apna was not doing anything, Apna was doing the look of a four, first of all, what is the look of four? First the look of four will open, first it will move from left to right, said ok, first this phone look will move from left to right, ok, after that another look of four will move, from where to where it will move from top to bottom. Clear, there should not be any problem. It will work from the top to the button. After that, where will your photo go? Brother, right to left is the right thing. So, if you are clear, how is your work going on? You have to store your photo in your G form. We are going to move according to it, okay, so we had to move from right to left, then from where will it move, it is a simple thing, then our top will move from bottom to top, okay, there should be no doubt, it will go to our top, there is no doubt, now all this How long will all this continue, until you make this Puri of yours drink the date with the help of the matrix, then what will we say here that these four will be completely in one line, meaning below this There will be a loop, there will be this folder below it, both of them will be here, they are fine and what will you put on here unless you file up your 9 volumes, what can you say here that unless you file your 9 Bill Waluj as your own. What is nine? 10 *1 *1 *1 I have also understood that you read it at every point of time, as if you join this group, how many times can you read it? First of all, you have read it here, then here. Filed out, then here Pay Three is out, then you will be going here, then you will check whether your three is still free, yours has reached 9, do you like another value that you do not have access to, back to this We will check in the photo whether you nourish the six, did you say no, if you are ok, then this photo of yours will work, in this you will say, has this run become equal, no, has this become equal to nine, said yes, it is important if. If you are having doubt in the concept of how you are doing then please go through yesterday's question once because it has been repeated since then, if you go to bring back the previous one then it will be exactly the same and it will be repeated, there is no meaning in it. So now you have come to this function of your life size. What did you do in vector and vectoring? Okay, you have also seen that you are also a vector, meaning from matrix, what is the size of your matrix? Apni Bola No, it is okay in this. Three cross three, if you take this example, then you make yourself in this way, today what is the number of rows, there is N in it and how many are the number of columns, that is also what was done initially, everything is zero, its ending or what can I say? You can take the bottom line, that is, what is the last row, what is yours, hand minus one, this is your text, white is -1, it is text, white is -1, it is text, white is -1, it is absolutely correct, just like this, what is your starting pen, that is, what is this pen on the left, what is this one? It is zero and the pen on the right or it can become your last pen, you can say, it is N - 1, it is can say, it is N - 1, it is can say, it is N - 1, it is clear, yes brother, this much is fine, then what did you say, your total number of value, how many times will you come, said brother, and No cross and meaning, okay, now that you have maintained a pigeon, answer to this, you will add plus and value, its Adam density means value, you will go on file it, okay, not open, welcome, okay, it is a simple thing, now first of all your Inside it, he used a low and said from here to here, okay, should I say what he is saying is okay and till where, he checked the ending pen and the starting pen, along with this there should not be a condition of its own and it does. Okay, so what did you do on your own and said here, first of all rub the zero pen of his, then first of all he will come to the account, one means okay, plus is done, mine is okay, then here you will come here. It should not be a matter of ending people, then what did you do, it has started, it will not open, this thing should be clear, then what did you do, you started the phone again, where will you go from where to where, brother, from here, from top to bottom, top to top button or Then what will you say even from the beginning, it is absolutely correct, so if you are ending from your beginning, then this is the starting account, it is okay to increase it from the line, brother, what was the pen, okay, you have flowered it, then what did you say, have you ever said your last? The one will not even come in the ending column because this has also become your first row, so what did you do to this one, Mines one, it is okay, when you stopped starting, what were you doing, you had done plus so that it does not come on your first row, meaning. These should never come to zero. Our atoms can come here. Okay, now you have mined the mines here, which means even the open ones will not come here. Now you can come here only from here. If you have done so much of the film, then it will run from here till here. So what is the meaning of moving from here, is it from the hanging pen to the first pen or is the count correct, it should never be greater than 9, it is a bullet, then what did you file up here and what did you set? It has been said that whatever it is, it should become constant, meaning it is doing its flower in this room and Apna Jo Aayi means that this pen will keep coming its own, will that open pen keep doing its flower, will it later finally give its ending row also? What have you done to me, you have done me to me, it means that you will never come even on the rope, it is a simple thing, then you will call back, you will start asking where are you going, then you will ask if there is an ending, even if it is your setting, then do not check, but this is the value. Said the hero above what has been made of the opening and should not go till here above the starting, said when it is a clear thing, checked the pan here again that Apna did the first Olympics and here Apna what did you do? Whatever number you have changed, you have filed it in your account, that is, your account has been hit, on PAN hit, you have billed it out in Pay Matrix. Okay, then what is your final number here? The starting pen has also been changed to plus, which means that this bullet will never come in this pen again. Yes, when it is clear, okay, now go back to yours, it will start again, what is your account till now, is it nine or so? Nivea has grown older than 9. Nivea has not grown older than 9. Okay, till now my account is exactly 9. I had to file only those nine last. This is my child. Okay, is it here? Have you started? And what is your ending pen? Tell me, your starting one is also the same child because the starting one is mine. It is a simple thing, we have adopted this pen, after that what did we say in it that you have filed up in the starting line. Do it now, stop at the beginning, what was done in the beginning, it was done plus, okay, there should not be a concept of this, what else is there, these are five sets, they do not have any value, okay, our contestant will take one, but here. What are you making? You are making a matrix. What is the size of the Puri? Sen, how much space have we taken in the process? How much will be the time quantity? Brother, what are you talking about? You have also prepaid for filing the Puri matrix. If you are doing it for the first time, how many times have passed and there should be no doubt, it is a simple thing, submit button
|
Spiral Matrix II
|
spiral-matrix-ii
|
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 20`
| null |
Array,Matrix,Simulation
|
Medium
|
54,921
|
435 |
welcome to august leco challenge today's problem is non-overlapping intervals problem is non-overlapping intervals problem is non-overlapping intervals given a collection of intervals find the minimum number that you would need to remove to make the rest of the intervals non-overlapping non-overlapping non-overlapping when we say overlapping basically we just mean the start or the end point are not within another intervals range you can see with this example one two three four one and three can be removed which would make the rest of the intervals non-overlapping intervals non-overlapping intervals non-overlapping a couple things to note is are the borders are touching that doesn't count as an overlap and we can always assume the interval's endpoint is always bigger than its start point so there won't be any tricky you know mixed up start and end points so usually with these kind of questions you could first approach it recursively you could think maybe we'll confine every possible combination we can have all four we can pop off one we can pop off two three or four we can pop out these two and just every possible combination and just check to see which one is the minimum light or i should rather say maximum length where it's going to be non-overlapping where it's going to be non-overlapping where it's going to be non-overlapping but that is going to be very expensive and frankly if you just have like a length of 10 intervals you can imagine there's so many combinations that just becomes unrealistic to do that so usually with interval problems there's either a dynamic programming solution or a greedy method and here there's going to be a greedy method now initially you might think what we might want to do is sort this list of intervals and then we can just go through and to see how many overlap and as soon as we find one that overlaps we could increase our counter to say one and that would give us the number of intervals that we would need to pop off so for instance we had this example here we can sort it this would be put into here and we can just check from the beginning hey this uh is three or i should say rather the start point uh less than the max endpoint from the previous and if it is we know that we need to pop this one off and just continue on and just count up the numbers that we need to do that for so that would be kind of the first thought i would have so we can think for well first we'll say if not intervals we're given an empty list just return 0. next we can sort the intervals and we'll set up two variables max and as well as the output max n is going to be a float of negative the lowest possible number in python so that's just going to be negative inf as well as output 0 which is going to be counting up the number of intervals that we need to pop off so for start and end in intervals which have been sorted now we could say if the start is less than and well maybe we can flip it we can say start is greater or equal to the max end then we will just update our max end to this one second otherwise we'll increase our counter plus equal one and finally return the output so i want to go into this more deep dive because it's very interesting but i just don't have the time today so let's imagine that we have this example oops let's just see what happens here so you can see this works and i would submit this but i already know it's not going to work because there is a problem here what if we had something like 110 and 4 5. like with our algorithm what it would do is first use this 10 as our maximum end and then it would say okay we need to pop this one off to get it all non-overlapping but we can to get it all non-overlapping but we can to get it all non-overlapping but we can see clearly here that it'd be better to just pop off the first one right so this would fail if we've ran this algorithm it would return 3 but the expected answer should be 1. so this really threw me for a loop for a while but eventually when i started researching what i realized was instead of sorting by the starting points what would happen if we started sorted it by the end points because if we did that what that kind of allows us to do is maximize the number of intervals that we could have in our list so basically you can imagine that if we sorted by the ending point uh whatever's left in terms of the range is going to be maximized right so whenever we pop off we want to pop off the minimum number that possible so if we put everything with the end at the end if we sorted it this way then our algorithm actually does the same thing but it guarantees that we'll pop off the minimum number of intervals so to do that we just need to sort it using a lambda function we'll just say t equals lambda x one like this and this let me just make sure this example works so there we go it seems to have worked and go and submit that and there you go accept it so this was really interesting to me the fact that if you sorted it by the ending point this would actually kind of magically maximize the number of intervals that we want to keep and thereby minimizing the number of intervals that we want to pop off so i think one day i'll go deeper into this i just don't really have the time today so i'm not going to be able to but hopefully that gives you an idea of why this algorithm works and yeah so thank you very much for watching my channel and remember do not trust me i know nothing
|
Non-overlapping Intervals
|
non-overlapping-intervals
|
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104`
| null |
Array,Dynamic Programming,Greedy,Sorting
|
Medium
|
452
|
1,996 |
hey everybody this is larry this is day nine of the leco day challenge hit the like button hit the subscribe button no three points uh let me know what you think about today's problem and so forth uh no video today or no uh no intro today with uh funky stuff um i'm in london right now uh for the next i guess just one day until tomorrow uh and yeah there's some i mean it's just a really uh really crazy time to be you know in london i suppose because of you know the queen rip right so uh so yeah um i don't know what's going on so anyway today's problem is yeah let's get started on today's vlog today's one is the number of weak characters in the game 1996. you're playing a game that contains multiple characters each of the characters has two main properties attack and defense you could win given a 2d array attack defense said to be weak if both okay a character said to be weak if any other character has both attack and defense strictly okay um okay so i think the way to do this is just by starting on one that i think in this particular case um and this particular problem uh is symmetric right what i mean by that is that there's really no difference between like there's nothing the attack and defense is essentially the same it's just a value that you used to compare to other greek or other characters that may or may not be weak and so in this case i think you can just sort and sweep line um meaning that um yeah meaning that as well as because in this case all you need to do is find one case in which uh an uh a character gets dominated and then there will be character right so okay so let's just say we get to go to zero um we might have to phrase it a little bit better and just for laziness i'm going to start by the first dimension so then that what does that mean right uh we might have to reverse this uh this is kind of greedy so i'm trying to think about it as well as i'm talking about it so if i'm a little bit sloppy let me know in the comments um but okay let's say we sort by so okay i think i want to start the other way though i want to reverse this um because uh in this case what we want is to kind of maintain an invariant right and it and then variant is that as we go from and this is just thinking about the attack dimension of the first dimension right so it's because we sort by the first dimension that means that as we go from left to right from index 0 to n or n minus 1 as we do that then as long as there's a way weak oh it has to be strictly greater than so may there is some like you know we might have to um yeah we have to do some like minor uh you know thing to make sure that handles the strictly greater than part versus the you know um the other thing like a uh greater than or equal to um but still going from left to right then variant is that if you're strictly smaller on the other element then because the assumption is that on the first dimension you're already gonna you're going decreasingly right or not increasing i suppose but let's say you're going decreasing uh do you okay i just want to check whether they're unique because of the uniqueness easier as well obviously but yes you're going to from 0 to n minus 1 dimension 1 is decreasing so as long as a number is smaller than uh dimension two or a number if you're processing it if a number is smaller than another number that you've seen before then you know that means that this number or this character is weak okay hopefully that was a an okay explanation uh maybe i need more visualization but i feel like that's okay so let's get started i think like i said though the thing is about strictly greater so we have to be a little bit careful uh and in this case like there are maybe similar some scenarios in which you have to do some binary research on every uh every character but here we can be greedy right and what do i mean by that what i mean by greed is that because you want to find only one character that's uh bigger or larger number in one in the second dimension in defense we can just always choose the largest defense right so it kind of becomes like a delayed uh some delayed something right so yeah so basically what we have maybe we you know i think i have all the pieces in my head so we'll see we'll take a look into it but now we have let's say the max is equal to say negative this could be negative number now it has to be a positive number but i'm going to write negative infinity anyway and then uh and then now maybe uh current max is to go to negative infinity as well but the idea here is just to differentiate the strictly greater than stuff so then now we have for attack and defense in properties right uh and maybe we do uh let's say last attack right is equal to i don't know uh infinity just because we're going decreasing so then we go if attack is equal to last attack okay let's say if it's not equal to last attack right then what happens right then we do last attack is to go to attack but then that also means that we get to update max right so max is equal to the previous max maybe let's just say pending max maybe that's a little bit of a better name depending max and and that's the resolution but we also have to do um so pending max is equal to max of pending max and then defense that's these are the updates so we have to check first whether um if defense is less than max strictly then we do a weak increment by one so that's the big money thing right okay and then so that's if this is the k so if this is the uh if we have a new attack that means that what am i doing here is that like for example we have uh okay the examples don't actually have it so i was trying to look through but let's say you have like five four uh and then uh i don't know 410 right so in this case we don't want to update the max to five until we pass all the fives right uh actually i think we can i mean i'm thinking now that i think about it i think i'm complicated to springs i think what we can do actually is just sort this backwards as well on the defense i mean what i'm doing will work and you know you just have to be careful but if we sort it the other way then we can assume that you know the four will be if there's a bigger number it'll be from a previous greater thing so actually i think we can do it that way and now that makes our code even easier so then we just have max and we don't have to worry about last attack and then we just go with defenses and then we can do something like max's equal to max of defense or max and then here we sort more specifically uh so we want to sort by decreasing first element and then increasing uh second element and i think now this is good actually so maybe you see my progression as i go over it but i think the tricky part is stuff like this where um where the tie breaking rules are because the input that they give you is kind of pretty straightforward so wait whoops okay i need to get rid of that space i have the extra space but okay so that looks okay though that's still not confident because it's still like 0-1-1 but let's give it a quick like 0-1-1 but let's give it a quick like 0-1-1 but let's give it a quick submit because i'm lazy and then we'll see that took way too long to be honest with for maybe not all right um cool that's all i have i suppose i have 892 days yay um this is you know because of sorting is going to be n log n and of course the rest is just linear so you know um yeah that's what i have with this one let me know what you think uh stay good stay healthy to good mental health stay safe everybody i'll see you later and yeah take care bye
|
The Number of Weak Characters in the Game
|
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
|
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105`
|
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
1,762 |
everyone so today we are looking at lead code 1762. it's a question called buildings with an ocean view and what we have to figure out in this question is if we have an array which represents the heights of buildings and we are looking at the buildings from uh east to west which buildings at the index are going to have an ocean view so let's take a look at the prompt here there are n buildings in a line you're given an integer array heights of size n that represents the heights of the buildings in the line the ocean is to the right of the buildings and a building has an ocean view if the building can see the ocean without obstructions formally a building has an ocean view if all the buildings to the right have a smaller height and we want to return a list of the indices zero indexed of buildings that have an ocean view sorted in increasing order okay so here example one we have four two three and one so one is going to have an ocean view three is gonna have an ocean view two is not gonna have an ocean view because it's smaller than 3 and 4 is going to have an ocean view and what we are returning is the indices in reverse order essentially of 0 2 and three the buildings that have an ocean view similarly here every single one of these buildings will have an ocean view one you can see the ocean if it's to the right two you can see the ocean three and four and here uh let's see we can see four so that's index three zero one two three the value is four so we're gonna have the index there three two you cannot see the ocean three we cannot see the ocean because this four is obstructing it and one we cannot see the ocean because the three is obstructing it and so here building at index three is the only one that has an ocean view okay example four we have two and we can see that this is the only building at index three that can see the ocean everything else is um not able to see it you can see two is not above this two right over here okay so let's think about this so let's say we have this array four two three and one okay and we want to get what indices we'll just go ahead and put in the indices here 0 1 2 and 3 okay as the indices and we want to figure out which one of these buildings has an ocean view and return those indices so we know that the building to the right is always going to have an ocean view okay so we can create a result array and we can go ahead and push that three index into uh our result array we'll just go to label this result array okay now when we go to three we can check is three larger than the last element here in our result array so here at index three it's one three is larger so we're gonna go ahead and put in two okay we're going to iterate backwards here to this 2 and we're going to check is the value at index 1 uh larger than the value the last value in our result it is not it's the it's uh it's actually smaller because the value is three at index two and here the value is two so we are going to go ahead and skip that and then here we'll get to four and we'll check is the value at index 0 which is 4 is it larger than the last value in our result it is larger so we're going to go ahead and push in that 0. okay and that's going to give our result and we can see here we actually want it in reverse order so all we can do is just dot reverse this okay let's go over this one more time just so it's clear okay um let me back up here and we'll just kind of step through this each time maybe label the variables a little bit more clear okay so here we have four two three one okay we're going to have a result array that's going to contain the indices and from the start we can go ahead and put in that first index so we can go ahead and get the length of our input array and just get the last uh the last index so the length minus one so heights dot length minus one and go ahead and put that into our result array as the start okay and now what do we want to check we want to iterate backwards through this list we want to go from the last to the first and so what we want to do is we want to check what is the current height okay current height is going to equal the index i that is going backwards okay so we can say current height is going to be heights at index i okay and now we just want to check if the current height is greater than uh the last element in result okay so we can say um result at result.len minus one result.len minus one result.len minus one okay and if it is then all we're going to do is push the index i into our results we just do result.push index i okay so that's pretty much it's not too bad it's just a matter of making sure you keep track of these indices and there's just a lot of ways you can get bugs in here but the logic is actually not too bad with this question okay so let's go ahead and code this up so what we're going to do here is we're going to go ahead and create our starting value okay so we can just call this start and we can just set this to the very last index in our height input so we can just do heights dot length minus one okay that's going to give us our very last index now we want to go ahead and create a result array and then just go ahead and put in that start okay so that sets up our initial uh our initial result now we want to iterate backwards from our input array so we want to say let i equal heights dot length minus 2 okay because we already have the first one in there so we just want to get the one that's next over and while i is greater than or equal to 0 we're going to just do i minus okay now what do we want to check if the last element in the result is less than the current element the current height that we're at okay so we can just create a variable say let cur building we can just say curve building okay and we can go ahead and set this to heights at i okay and now we want to get our last building and we can set this to result.length minus one result.length minus one result.length minus one okay so as we are iterating through the heights that's our current building we're comparing it to our last building which is our last element in that result and now all we have to do is check if the current building is greater than the last building and the last building remember is the index this last building is going to be the idx okay so we do what we could do actually is just put this into our heights okay this is why this question can be a little bit confusing because in the results we're storing the index but we're doing a comparison with the values so we can just check if current building is greater than last building we just want to go ahead in our result push in that high pushing that index okay and now lastly we want to reverse the whole thing so we just want to return result.reverse okay go and run that and we are good okay so let's take a look at time and space complexity for this okay so relative to the input how many times are we traversing over our input array relative to the size of the input we're only doing one pass through this uh this input array we're going from the end to the beginning okay so because of that our time complexity here is going to be o of n time all right now what about space complexity how many times are we how much space are we creating relative to the input well the worst case is every building would be part of our result array okay so our space complexity worst case would also be linear space okay which isn't bad all right so that is lead code number 1762 buildings with an ocean view this is not really that difficult of a problem it is asked at facebook a lot and i've noticed that facebook tends to ask these types of questions that are fairly simple but there's bugs like this that you can easily step into which is when you're doing these comparisons you're storing the indices but you're comparing the values so you just want to make sure that this is like kind of like walking through a minefield you want to make sure that you know you meticulously check every single line of code that you're putting down as to avoid bugs okay so lead code 1762 hope you enjoyed it and i will see you on the next one
|
Buildings With an Ocean View
|
furthest-building-you-can-reach
|
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line.
The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height.
Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order.
**Example 1:**
**Input:** heights = \[4,2,3,1\]
**Output:** \[0,2,3\]
**Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
**Example 2:**
**Input:** heights = \[4,3,2,1\]
**Output:** \[0,1,2,3\]
**Explanation:** All the buildings have an ocean view.
**Example 3:**
**Input:** heights = \[1,3,2,4\]
**Output:** \[3\]
**Explanation:** Only building 3 has an ocean view.
**Constraints:**
* `1 <= heights.length <= 105`
* `1 <= heights[i] <= 109`
|
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
|
Array,Greedy,Heap (Priority Queue)
|
Medium
| null |
611 |
hello everyone and welcome back to another video so today we're going to be solving the lead code question valid triangle number so in this question we're going to be given integer area called nums and we need to return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle so just a quick example over here we have nums 2 3 4. so one valid combination is two three and four and what that's telling us is that uh we have a triangle where one of the lengths is two the other length is three and the final length is four so just given the length how do we know whether or not it is a valid triangle so for that there's actually a simple kind of rule about triangles which is the sum of two of any two sides must be greater than the third side okay so any two sides when added up has to be greater than the third side so let me just write it down so it should be easier so let's say we have three sides a comma b comma c although we'll just draw four triangles so a b and c so in this case what the rule tells us is that a plus b has to be greater than c the same way a plus c has to be greater than b and finally b plus c has to be greater than a so if all these three conditions are true we do have a valid triangle so i mean you could just look at the most extreme case which is when we have an equilateral triangle so let's just say all the sides are five so in this case five plus five is going to be 10 which is always greater than 5 right so this rule always applies true for any types of triangles and this is what we're going to use to find out whether we have a valid triangle set of values right so to actually just do that let's first look at the most naive solution which is going to be using three different for loops and the way this would work is we would have one for loop which goes through all these numbers so we'll go to two then two again then three and four now we would have a second for loop which would go through these numbers two three and four and then a third for loop which goes to three and four right because we can't have repetition of numbers and we would just keep doing this on and on so then uh on the second time we would have a for loop going through two three four then we would have a four loop for three and four and finally one for four so that way we just go through all the combinations and at each combination we're checking to see whether or not it forms a triangle so this is a very naive solution and let me just show you what i have so this is it right so we have a one for loop for x one for y which starts at x plus one and then one for z which starts at y plus one and then this is the condition that we're checking for here so num x plus nums y greater than num c nouns x and num z greater than times y and num z plus minus y greater than number x if that's true we do have a possible triangle combination and then we add that to our result where we finally return rise and rest starts off at zero so that's pretty simple that's the brute force approach of this and that's going to be big o of n cubed now we want to see whether we can come up with a better solution and to do that let's actually um see how we can actually do that so let's say we take this okay let's take four two three four as an example so let's just say we have four comma two comma three comma four so one kind of way to look at this is we have three values right we're going to have a comma b comma c and what we can kind of do is beforehand we can set one of these values so let's say we always decide what a is now once we decide what a is our goal is to be to is going to be to find b and c such that it fits the criteria that we have and the criteria is that when two sides are added it's greater than third side so this is what how we're going to approach this question we're always going to fix a okay so how can we actually make this easier for ourselves so let's say we fix a as four now our goal is to find b and c so in this case or uh as it is our array is not sorted so finding b and c is not going to be so easy so we could just have a two for loops do the same thing but the time complexity is going to be exactly the same there's no point so let's see if we can actually optimize this and kind of come up with a better solution so what we're going to do is we're going to sort this area and the reason we're storing the area and why it makes sense is because what we could do is we could have b as the smallest value and c kind of has the largest value and what we can do is we can kind of find what is the limit so what is the smallest possible and largest possible value that we can have and doing that we can kind of find all the possible combinations so as i go through this it should make more sense okay so for oh sorry um so we have four comma two comma three comma four so now let's sort it so let's say we have two comma three comma four okay so now this is sorted i'm just gonna get rid of this over here and this is what we're working with so the way we're going to do this is we're first going to set a value of a so one thing that we that actually does matter in this case is what direction are we going to iterate through it so we could go from left to right or from right to left but in this case it's only going to work if we go from right to left and i'll explain why that is so what we're going to do is we're going to start off from right to left and a is going to start off with this value over here okay so now we're searching for b and c and the way we're actually going to search for b and c is we're always going to set b equal to zero so b is going to start off at zero over here at the zero index and c is going to be one less than a and the reason c can't be over here is because again we cannot have repetitions so c is going to be the index of a minus one so in this case c would be right over here so this kind of over here is our search space so what exactly we're doing here is checking if this is a possible combination so to check if it actually gives us a possible answer we're checking the sums of all three combinations but in this case we don't need to do so we can just check the sums of the two smallest values and see if it's greater than the biggest one so the reason uh and this is also one of the reasons why going from right to left makes sense because we know for a fact that uh the largest value is going to be a because c is always going to be a minus 1 and b is just going to be 0. so keeping this in mind over here a is always the greatest so once we know that b plus c is greater than a the other conditions obviously become true and just to kind of write it down so b plus a is always going to be greater than c since a is the greatest and the same way a plus c is also going to be greater than b okay so we're just going to check for b plus c is greater than a so in this case what we're going to do is we're going to do 2 plus 4 is greater than 6. sorry it's greater than 8 right so let me start down 2 plus 4 has to be greater than 4 and that's correct 6 is greater than 4. perfect so now how exactly do we account for this and our answer so what this is telling us is that one possible combination over here is the values 2 4 and 4 but we can actually extract more out of this so we know that 2 4 is a possible combination but what this also tells us is that everything in between can also be part of the combination instead of b so what that actually means is that since so b is going to be at the zeroth index in this case right so if it is valid for when b is at the smallest value that also means that when b is anywhere in between which obviously means it's going to be greater than or equal to its current value it is also valid so in this case b could be 3 as well so let's just write that down as well so 3 4 is also a valid combination and if you want to check that it's just going to be 3 plus 4 greater than 4 that is correct 7 is greater than 4. so just to kind of add on to this just to show you so let's say we have 2 comma 3 right so in this case uh the same thing applies right so 2 4 is a possible combination and this is the first two and then the other 2 4 is also a possible combination so using this 2 over here and the same way 3 4 is a possible combination and so is the other 3 4 so this three and this three sorry it's supposed to be a comma here okay so now that you understand so once we find this combination everything in between can also make up a possible combination so we're going to have a result over here which starts up at zero and each time before we incremented it by one but now instead of just incrementing it by one what we can do is we can actually increment it with all these possible combinations so instead of just looking at two four 4 we can also look at this 2 4 this 3 4 and this 3 4. and the way we get that is by taking the value of the index c and subtracting it by b and the reason we're doing c minus b is because c is greater than b so let me just write down the indices so this is index 0 1 2 3 4 and 5. so in this case it will be 4 minus 0 and 4 minus 0 is equal to 4 and so we're going to add 4 to our result so now our result is zero plus four which is four perfect so here we found a valid result and now we have four possible combinations and exactly as you can see we have four so now we found one possible value over here right so we found these values over here but what exactly is the next step so as it is b plus c is greater than a right this is the current condition that we have so for the next iteration and we already accounted for whenever we move b to the right since we accounted for all these three values in between so now what we're going to do is we're going to move c one to the left okay and the reason for that is we still want to see if this condition is true so we're going to keep moving c to the left as long as our condition of b plus c greater than a is true so now let's move c to the left by one okay so c comes over here let me just clean this all up perfect so now we have c at the third and let's and we do the exact same thing which is uh over here we do the check so we do two plus three is it greater than the value of eight so two plus three is greater than four so perfect and now in this case uh five greater than four that's correct and now we do the same steps so what are our possible combinations so the first possibility is two three and four okay so that's correct and again we're also accounting for all the possibilities in between and now this is again one of the reasons we're iterating from right to left and not left to right because we know it's an ascending order so once we have a b and c set right it also accounts for everything in between of that so in this case the other possibilities are two uh three and four so the second two and then the second three so three and four so all of these are possible solutions and to check it three plus two six greater than four three plus three six greater than sorry three plus two five and three plus three six okay perfect so now this over here is three more solutions and the way we know we have three is by doing c minus v which is the index three minus zero so three minus zero equals three and we add that so now our result is seven so this is how we keep going on so in this case the condition is still true so now we move c over here right and now we check if a plus a b plus c is greater than a and it is three plus two five greater than a so now we do the condition again so in this case let's just directly get into it so we have two minus zero two and now we have two extra solutions so now our account for result becomes nine okay now we move c again and when we move c over here we have two plus two which is four and four is not greater than four so this over here is that means it's not valid so this is where we kind of stop and we look at the next possible possibility which is where we move b to the right and the reason for that is b plus c currently is too small and we want to look at larger numbers and the way we do that is by moving b to the right so in this case we move b to the right and what happens is that b and c end up at the same index so at any point when the index of b is not less than the index of c we're going to stop out of this kind of this while loop that we're in so currently we're done okay so this is the first iteration and remember we locked a into a single value and a was always at the fifth index so currently we're done right so a being at the fifth index is done and we found nine possibilities out of it so now we move a to one left so now a is going to go to the fourth index and we do the same exact steps so let me just go through this real quickly and then you can kind of understand that this process just continues on until a reaches the first index over here sorry uh until uh a reaches the second index right so that's basically the process right and why the second index because well we need three numbers so when a is at the second index uh b would be here and c would be here right and those are and we have to have three numbers for a possible set of triangle values okay so let me just show you what this looks like so a would be over here then we uh b is always at zero and c is at a minus one perfect so now that we have this all we need to do is look at the same conditions so three plus two is greater than four over here so now our number of possibilities is three minus zero so we add plus three over here and now we move c to the left so the same condition is true so now we have two possibilities here so plus two now we move c to the left again but over here it's not true two plus two is not greater than four so now we move b to the right and in this case the b is not less than c by index so we're done perfect okay so now eight gets moved to the left by one and the same steps follow b is over here c is over here so we have b plus c which gives us five and five is greater than a so the same steps follow so over here we have two possibilities so plus two so we move c and now we have two plus two four which is greater than a's value of three so that's uh one minus zero so that's one possibility and now we move c again and now they're the same index so we can't do anything okay now finally a gets moved again so this is the last time we move a and over here b is at the zeroth index and c is at the index a minus one so currently uh let's look at this so this is two plus two four and 4 is greater than a's value so that is one possibilities because index one minus zero so plus one perfect and now let's move c to the left and obviously we can't do anything and this is the end so this over here is our final solution so let's just add it up so nine plus three plus two so that's five seven eight nine eighteen okay so our result here is 18 for the area two three four so let's just actually check if that's correct so let's just do custom test case so two three and then four so run code okay and our expected answer was 18 and we also got the answer 18. so this over here is the solution that we're going to use and i think it is pretty intuitive and now let's just see what this looks like in code because i think that's a lot easier to understand all right so we're going to start off the first thing we need to do is we're going to sort now so none stop sort and the advantage of this i think it takes log and time and it happens in constant space so yeah there's that and we need to have a result and let's just equate that to zero in the beginning and now we're going to have a for loop for the a value remember a is being fixed so a is going to be for a in range and we're going to start off from the ending so the last index is going to be the length of numbers minus 1 and we're going to go all the way up to one so uh what that means is we're going to go uh the last index is going to be the second index which is exactly what we want right this is the last index okay and each time we're going to decrement it by one okay so this is for a and now we will arrange b and c so b and c and b starts off at zero all the time and c is always a minus one like we defined okay so now we're going to have a while condition and remember the condition was we keep going as long as b is greater than sorry is less than c so as long as b is less than c we stay in this loop so now we first need to check if this is a possible combination and the combination that we need to check was for b plus c has to be greater than a so let's do that so nums b plus num c has to be greater than nums a so if this is true we have a dilated triangle okay at this point we have a valid triangle and so since we have that we need to account for that in our result and the way we do that is we get all of the indices in between as well remember we did that so to get that we're going to do uh c minus b right so c minus b and that gives us all the number of possibilities and the other thing that we have to do once we have a valid triangle is we have to decrement the value of c right so we decrement c by one to look for other possibilities so c minus equal to one perfect now else if this is not the case we don't have a valid triangle and we want to look for larger values so we want larger values so we move a plus equal once okay so sorry a small mistake over here so this is supposed to be b plus one so we increment b to the right by one right so uh okay so that's exactly what we do b plus equals to one and finally outside of the while loop and outside of the for loop when we're done we're going to have a value for result which we end up returning so let's submit this and as you can see our submission was accepted so hopefully this video did help you out do let me know if you have any questions and thanks a lot for watching thank you
|
Valid Triangle Number
|
valid-triangle-number
|
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_.
**Example 1:**
**Input:** nums = \[2,2,3,4\]
**Output:** 3
**Explanation:** Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
**Example 2:**
**Input:** nums = \[4,2,3,4\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
| null |
Array,Two Pointers,Binary Search,Greedy,Sorting
|
Medium
|
259
|
279 |
Hua Tha Hello Hi Everyone Welcome To My Channel Today 2074 Recording Challenge Every Problem In Perfect Square So Give Any Positive Interior And Finally This Number Of Perfect Square Numbers For Example 496001 112 Subscribe Minimum From 403 Also From One Plus One Atithi Minimum Nine Two Numbers Minimum Nine Two Things Like This Problem Relative Minimum Change Problem Is Amount And Have To Go Hindi Minimum Coins From The Giver Set Of Points Software So What Is This Problem Is The Beach Side Of A Mountain Means Are The Number Beach Start From 21 To Central Is Festival Lansdowne Number Subscribe Like and Subscribe Related To Which Can Change Minimum Nine Two Square Plus 4 To Minimum Nine To The Phone That Simmer Let's Example Life But One Can Visit From Flight Subscribe Plus One Two Three Four Three For Free Live Web After Two C Plus Way Can Directly Subscribe To 400g Online Members Minimum Points For This Like One So Acidity Key Problem Subscribe Button Otherwise Need To Start From A [ Otherwise Need To Start From A [ Otherwise Need To Start From A A & B Retreat From Inside Because 218 A & B Retreat From Inside Because 218 A & B Retreat From Inside Because 218 York Equal To One Plus Bank Account It Is Equal To What Is The Meaning Of The Square Of The Meaning Of York subscribe And subscribe The Amazing And subscribe 560 Yes No 1112 Thirteen Service Seal Testis Pass 123 Cutting Pass Yes So Let's Samay Tower Solution Record Tip Code The City Was Taking To Much Time Facility Explanation Time Complexity It Is Time We Effigy Let Me The Example And Tried To Create An Entry For Example Se Withdraw From A Pun Number One To Three Subscribe 1451 Dhund Hi Dhund subscribe and subscribe the Channel Mein Nivesh Pranali 400 11.7 Channel Dhyan For Mein Nivesh Pranali 400 11.7 Channel Dhyan For Mein Nivesh Pranali 400 11.7 Channel Dhyan For Taking this will get you will terminate subscribe now from hair oil suvvi subscribe my channel subscribe top 10 gram fennel youtu.be a slap record to new of house map that and one of witch act in the map is tense Key for women in the letters tense Key for women in the letters tense Key for women in the letters written mam debit the android not independent of force updater map and account it is the meaning of the word and will return subscribe and subscribe the Channel Please subscribe and subscribe the site is accepted for this is the top down method For solving its problems receive the time complexity of this solution like it is the square root of time complexity of solution of ninth and you are also to the power of 1.5 and space complexities of 10th is shopping so let's solve this problem in water approach beginners for this using Dynamic Programming for the Business Solutions for Water Flow subscribe The Amazing Size Plus Way Elimination of Which Celebs Headed by Chief Chaff Kee and GPS of How to Stuart and GPS of Three List 3 Members of The Nation and I Will Stop Dams Are Don't Frill a B P web Max Value The panel of studies is a great from point of view option 214 I that garlic and equal to a nic plus here enjoy deposits 220 will start from one and they will star like zor equal to z Plus plus this is made hair develop dp word 300 dpi of eye easy method cotton of gps off kar allu safed the value of measurement of the indian avengers in the cockroach solution that savitesh compiled and were getting correct for all the power custom test of this letter Submit Water Pollution The City Has Accepted And Time Complexity Of This Also Like This Is Running For Friendship Is Running Oil Square Of Internal Set Can Go To The Standard Model School Ground Floor Subscribe Seervi Subscribe Shravan Numbers From Between You Minimum Number From Which Tower Number Bill Form Sorry For This Purpose 200 Is That Film Sholay's Three We Can Represent Festival Plus Shy Problem To The Number Subscribe Share Minimum Free Mode On The Total Subscribe The Volume Minimum For Example All The Number One That 496 Replaced With Jeevan Number Similar This To Thursday Like This Is Star Subscribe To 209 This Will Be Representation Of From Delhi To Numbers So How Can We Check Digit Number Which We Can Do Simple Chalu Karo Kal Sham High Cost 212 I Want To Square Root Of In The Square Root Of Man Ki And Check Ifin - I On Square Leg Ki And Check Ifin - I On Square Leg Ki And Check Ifin - I On Square Leg Side Is The Meaning Of This Subscribe Now To Receive New Updates Will Be Replaced With A Great Historical Development From The Proving Subscribe Node For The Power Plus Subscribe Third Appointed Return For Pyun Subscription Form Number Subscribe Quite Beneficial like and number between this representation from born in the skin from second and third from subscribe The Channel press the world will be third year pin code for the power of 108 name plus0 what we can do for solving will repeatedly divide number one And All Cases Will Repeatedly Divide Disawar Number 90 subscribe The Video then subscribe to Hands Free Mode Ko Beth 100MB Model Reduce Question Is This Point Is Model 181 Reminder Shy 30 Feet Which Is The Number With U 128 Pralay Grants To Lage Is 151 Is The Answer Pimple Intent Of Maths Dot Square Root Of N Star Symbol You Who Is Equal To And Just Simply Written Work And Next Two Years And More Product That Person Done To In That Case Will Run More Is I Lash I Love You To The Square Root That Ravi Pandey C automatically type student take by plus day on Thursday to - festival and similar e visit a - festival and similar e visit a - festival and similar e visit a this country We can divide mode volvo v40 to remove the part of which will divide the subscribe mode key reminder set the written in this will wipe a case for ne bhi twitter result se turn on this is from the implementation of your Video not remember And subscribe The Amazing Programming Interview Subscribe Thursday Maximum Subscribe To A Square Root Of And Thank You Like This App Please Like Button Thanks For Watching
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
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. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
134 |
welcome to this video now we're going to solve a coordinate question gas station this is the problem statement there are in gas stations along a circular route where the amount of gas at station i is gas i you have a car with an unlimited gas tank and it caused cost i of gas to travel from station i to its next station i plus 1 you begin the journey with an empty tank at one of the gas stations return the starting gas stations index if we can travel around the circuit once in the clockwise direction otherwise we have to return -2 otherwise we have to return -2 otherwise we have to return -2 if we're given gas equals to this array and cost equals to this array represents the amount of gas we have at station 0 at station 1 at station 2 at station 3 and at station 4. at station 0 we have one leader at station 1 we have two later adaptation 2 we have 3 liter at station 3 we have 4 later at station 4 we have 5 liter and this is the cost to travel to the next station if we want to go to the station 1 from this station 0 we need 3 liters of gas from station 1 to this station 2 we need 4 liter of gas okay hope you have understood the problem statement this is our circular path we can travel to this path in clockwise okay here we have index 0 at index 0 we have gas 1 liter and we have cost 3 letter to visit the next station here we have index one and we have at the station two liters of gas we need four liter of gas to go to the next station now our goal is to find a station such that we can travel this circular path once if we start at this station 0 we have to travel this circular route such that we can reach this station zero okay at station zero we have one liter of gas but in order to go to the next station we need three layers of gas so we can't start here at station one we have two letters of gash but in order to go to the next station we need four liters of gas so we can't start at this station one at the station two we have three liters of gas but in order to go to the next station we need 5 liters of gas so we can't start here at this station 3 we have 4 liters of gas in order to travel to the next station we need one liter of gas so we can start at this index let's see if we can travel to this circular path such that we can reach this station again if we can reach this station again then we have to return the index of the station let's see if we can reach this station if we start from this station if we start at the station's 3 this is the index we will have in our tank zero plus four equals to four so we'll have four liters of gas initially we have zero liters and at this station three we have four liters so total gas we have four liters at this station if we visit the next station then at the next station we will have our gash total of 8 liters so 4 minus 1 is 3 plus 5 at this station we have 5 liters so five plus three is eight then from this station if we visit the next station we will have seven letter of gash eight minus two plus one that is seven from the station to go to the next station we need three liters of gas at the next station we will have our gas of six liter from this station if we visit the station two then we will have gash in our tank at this station to 5 liter and from this station if we go to this starting station 3 we need 5 liters of gas and we have 5 liters of cash so we can reach the starting stations if we start at this stations so in this case we have to return the index of the station so the index of the station is 3 so we have to return 3. now how we can solve this problem first what we're going to do is that we're going to add the different for all stations 1 minus 3 is minus 2 two minus four is minus two three minus five is minus two four minus one is three five minus two is three if we add all the different then we get zero now our rule is that if we have the sum of difference is greater than or equals to zero then we have at least one station where we can start our journey such that we can reach that station again okay now let's see how we can solve this problem with the health of pseudocode we have here circular path okay first i'm going to declare a function can travel it takes two array cash and cost then we're going to declare a variable position equals to -1 position equals to -1 position equals to -1 this position will store the index of our starting gas station if we will not found a starting guest sessions then we'll return -1 we'll return -1 we'll return -1 then we're going to declare a variable current equals to 0 after that we're going to declare another variable total equals to 0 then we're going to run a loop for i from zero to length of the gas minus one then we're going to calculate the difference between the amount of gas we have at a particular stations and the amount of gas we need to visit the next station then we're going to add to this current variable then we're going to add the different to the total variable then we're going to check if the current is less than 0 then we're going to set current equals to 0 and position equals to our current iterations or our current station at the end of this for loop if we have total is greater than 0 then we will return position plus one if we have poodle is equal to or greater than zero then we will return minus one initially we have position equals to minus one current equals to zero and total equals to zero okay for the first iteration of this loop we have different equals to minus two current equals to minus two total equals to minus two then we're going to set the current to zero and positions to our current station then for next iteration we have i equals to one difference equals to minus two current equals to minus two total equals to minus four current equals to zero and position equals to one then for next iteration difference equals to minus 2 current equals to minus 2 total equals to minus 6 current equals to 0 and position equals to 2. for this iteration we have this value and for the next iteration we have this value at the end we see that we have total is equals to zero so we found a stations where we can start traveling okay and the station index we can get by adding one to this position okay for this input it will return three in order to understand this problem you have to go through with your own examples then you will see how easy it is here we have everything to make you understand this problem but i encourage you to go through with your own example you can take a look at the value of this variable for each iteration we have here okay so you will have a easy time understanding this problem i promise that if you can go through with your two or three examples this solution will be pretty easy to you all right if i'm going to explain every single details here then you'll get bored i didn't want that right this is my solution to this problem this solution will takes big of end time complexity or n is the number of stations we have or length of the given array and this solution will takes constant space complexity if you have any question if you have any suggestion let us know thanks for watching this video
|
Gas Station
|
gas-station
|
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**
**Example 1:**
**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
**Example 2:**
**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
**Constraints:**
* `n == gas.length == cost.length`
* `1 <= n <= 105`
* `0 <= gas[i], cost[i] <= 104`
| null |
Array,Greedy
|
Medium
|
1346
|
1,559 |
Hello Friends Welcome to CP Study List C Another Problem SC Code Contest Per Jhal Ki Police Call Details Cycle * Degree Been Given Police Call Details Cycle * Degree Been Given Police Call Details Cycle * Degree Been Given A Great And They Will Celebrate Contents Any Similar Egg Subscribe And Like Subscribe And Subscribe Loot Pimples Motorcycle Cycle Liquid Form A Co No Tax Literally Loot Thursday That He West Indies And How E Should E That Veena Document And A Color A Data Systems Road Suppose E Have Agreed To File A Man To Man So I Don't Color And He Is The Color Of The White Color Subscribe to that not the color it is the same character edit colors 032 pass that and adds and vegetables and setting the color equal to Sudhir volume minimum set subscribe this video subscribe color Thursday that wearable tourist property porn video also in present- day crop liquid video also in present- day crop liquid video also in present- day crop liquid police and appointed subscribe and subscribe to alarm set roll code this is all the logic behind it is really heart problem ke laddu electronic this logic for this example1 note colors with oo that Vishnu care about his date never be Are doing it first reversal n we are going from different not experienced subscribe vishuddha chakra vishuddha again will be coming from haridwar sidkul are not the current president on kar do hai ya yoga maintenance free global variables in this cycle from zeemeen se zeemeen upkari neeti girl in The great toe subscribe to the page if you liked the video then subscribe to send that in the baikuntha medical shop set me color equal to one is directed to find jobs for peon in verification left right down that asaf khan and coriander powder class ninth Vidron Its Urgent Seervi Hai Bluetooth Settings Commercial Electronic Loot Subscribe Skin Problem Please Subscribe Our Youtube Skin Problem Hai
|
Detect Cycles in 2D Grid
|
cherry-pickup-ii
|
Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the **same value** of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell.
Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`.
**Example 1:**
**Input:** grid = \[\[ "a ", "a ", "a ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "a ", "a ", "a "\]\]
**Output:** true
**Explanation:** There are two valid cycles shown in different colors in the image below:
**Example 2:**
**Input:** grid = \[\[ "c ", "c ", "c ", "a "\],\[ "c ", "d ", "c ", "c "\],\[ "c ", "c ", "e ", "c "\],\[ "f ", "c ", "c ", "c "\]\]
**Output:** true
**Explanation:** There is only one valid cycle highlighted in the image below:
**Example 3:**
**Input:** grid = \[\[ "a ", "b ", "b "\],\[ "b ", "z ", "b "\],\[ "b ", "b ", "a "\]\]
**Output:** false
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid` consists only of lowercase English letters.
|
Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively.
|
Array,Dynamic Programming,Matrix
|
Hard
| null |
80 |
all right so let's talk about the remove duplicate from solder array 2 so this question is pretty straightforward and you are giving the solder array but for every single unit element inside the array you can only have two maximum frequency right two maximum focusing is a ratio uh here we go so let me just draw it so uh you have three uh three for one right two four two and then one four three right this is a frequency this is a unique value right so you can only have maximum two elements for every single unit uh unique element right so one comma one and then you don't need one anymore right two right and twenty two and then three right so then of the length of the array is actually five so you return five so this is gonna be exactly the same thing zero one and then you get rid of this right two and then three and then the length of this should be seven all right so this is the idea right so the solution should be simple so uh i'm going to say 1 2 3. so the first two elements shouldn't be matter right this is because we always use we always need it and this are not the one we need to take care of right so we're starting from here and changing another likeness so this is i right and also not i also need another index for j so j is actually the array like you need to uh that you need to travel for the return value and then for the i well i basically just have to traverse the original sort of array so i started for i equal to 2 and j equal to 2 right and then i compare when what when nonsense j minus 2 less than num say i right if this is valid then i know they are not duplicated even though this is one right if this is one and this one are satisfied right so you move your eye on the next iteration but j still keep this index so once you satisfy this function num j minus 2 which is what j is x equal to 2 minus 2 0 so which is 1 and less than two one less than two this is the value then i update my current index value to two right to two and then i increment my j index and then i will just keep doing on the next iteration so this is supposed to be the idea and then you'll just return j right all right so uh in j equal to 2 for in i equal to 2 i listen and if not j minus two listen say i then use a number g plus equals and you're returning so this is the solution so let me run it okay so let's talk about timing space this is a space constant this is the time all open and this is the easy solution so i will see you next time bye
|
Remove Duplicates from Sorted Array II
|
remove-duplicates-from-sorted-array-ii
|
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements.
Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`.
Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\]
**Output:** 5, nums = \[1,1,2,2,3,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,1,2,3,3\]
**Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\]
**Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
| null |
Array,Two Pointers
|
Medium
|
26
|
424 |
okay welcome back to uncle Jess today's question is leak code 424 longest repeating character replacement so in this question we have to return the length of the longest substring that contains the same letters and you're only allowed to perform K operations or k updates so we have two updates that we can perform in example one and we have this string of a b so we can update one of these strings for one of these operations so if we update A to B K will decrement to one and then if we move along and update A to B again then K will be equal to zero we've used up all our operations and the longer substring we can generate from that is four okay so we know what we need to do in this question we have a string right here and we can see from this if we choose this substring we'll have to update this character right here to an a in order to get a value of 4. so how would we go about doing that well we can Loop through this array using a left and right pointer so left and right we can map out the indices we want to get the length of this string so it'll be right minus left plus one to get it right because three minus zero plus one is equal to four the length of the substring is four so right minus left plus one now in order to get the amount of B's within this substring because we want to update the beat right in order to get this B we need to subtract the A's so we need to grab the frequency of the eight right so if we say minus a frequency which is essentially going to be three this will give us the value of B right so this is going to give us B now if B is less than or equal to k then we can update the longest to the length of this substring right so if this is less than or equal to K we can update the longest to equal this substring so this is the equation we're going to be using for this solution but how are we going to map this out well we're going to need a matte data structure we're going to use a two pointer technique along with this and this map is going to store how many times we see each character so up to this level we have a is pointed 3 and b is pointing to one we're also going to need a top frequency right and this variable is just going to be the character that we have seen the most throughout this so at this point in time it's going to be 3 right because a is mapped into three B is mapping to one the greatest is three now we can slightly adjust this equation so rather than a frequency we can add top frequency and this is going to equal smallest frequency so let's run through the solution we start off here we have a left and right pointer let's map out the indices so the first thing we do is we look at the right point we see that we're at an a is a within the map no it's not so we update the map to contain a and add a value of one we update the top frequency to 1 and we can use this equation down here in order to work out whether we can update the longest and we already know we can update the longest in this case so the longest it's going to go to one we move across we update the map to two top frequency is going to be two again we can update the longest we move the right pointer to B now we add B into the map top frequency is going to be the maximum between top frequency and the value we just added in and now we make a check so it's 2 minus 0 plus 1 minus top frequency of 2 this is equal to one right so the smallest frequency as we can see in the map is equal to one is this less than or equal to K yes it is so we can update the longest two right minus left plus one right because well the longest is going to do the maximum between the current longest and this value here which we've worked out is valid so we'll update longest to three and we'll move our right pointer along the right pointer is at an a we can update the map at Key of a to 3 and also we can update the top frequency to three now we can look into this equation right minus left so three minus zero plus one which is equal to four minus the top frequency of three is going to equal one this is equal to K so this is a valid substring so we can update the longest two right minus left plus one which is going to be four and then we move the right pointer along so the right pointer is at a B so we update B within the map to two top frequency is still three and now we make the check so right minus left so four minus zero plus one minus the top frequency is three is equal to two this is greater than K so here we need to decrement the value of a from that so A goes to 2 decrement the map before moving the left pointer then we update the left pointer by shifting it across by one so now that we've updated the map we've decremented the value and moved the left pointer across we also need to update the top frequency which is going to be 2 the highest frequency within the map that is and now we can update this equation so it's going to be four minus one plus one minus top frequency of two well what is that equal to that is still equal to two so again we need to update the map we decrement the value of a we move the left pointer along top frequency is still two so we're at b a b so it's going to be four minus two plus one minus top frequency of 2. now that is going to be one so this is valid right because the smallest value is a in this case so now we can compare this substring with the longest value is still full so we keep that and then we iterate across so we move the right pointer across we repeat the process we update the value of B and map to three top frequency goes to three and then we look into this equation so right is equal to five left is equal to two plus one this minus the top frequency of three is going to give us value of one this is valid because it's equal to the number of operations that we can carry out within this substring and as we can see the only value we need to remove is a so this substring is equal to length four we check it against the longest value they're equal so we keep four and then we repeat the process so we move the right pointer along check the map check the top frequency update this equation and as you can see for the rest of the string we're not going to get anything longer than four so that is the solution to this question and time complexity for this solution is going to be of n where n is the length of the string and space is going to be of n where n is the amount of keys within the map so let's code this out we're going to initialize a map our top frequency the longest string and the left and right pointer so while right is less than string.length string.length string.length we need to carry this out so let's first extract the right character which is going to be Sr right then we need to update the map so look into the map to see if we have the right character if we do then we just add 1 to the value that is within the right character otherwise we set it to 1. then we update the top frequency which is going to be map.max between top which is going to be map.max between top which is going to be map.max between top frequency and map at right character and this is where we implement the equation so it's going to be a while loop and it's going to be while right minus left plus one so the length of the substring minus the top frequency so the character that has been seen the most if this is greater than k then we need to update the left pointer so let's get the left character which is s at left let's decrement it from the map and then let's update the left pointer so this will iterate through the string until we have a valid substring and then we can update the longest which is going to be the maximum between the current longest and the current length of the substring which is right minus left plus one and finally we need to update the right pointer then all we need to do is return the longest and give this a run submit it there you go
|
Longest Repeating Character Replacement
|
longest-repeating-character-replacement
|
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times.
Return _the length of the longest substring containing the same letter you can get after performing the above operations_.
**Example 1:**
**Input:** s = "ABAB ", k = 2
**Output:** 4
**Explanation:** Replace the two 'A's with two 'B's or vice versa.
**Example 2:**
**Input:** s = "AABABBA ", k = 1
**Output:** 4
**Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ".
The substring "BBBB " has the longest repeating letters, which is 4.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only uppercase English letters.
* `0 <= k <= s.length`
| null |
Hash Table,String,Sliding Window
|
Medium
|
340,1046,2119,2134,2319
|
244 |
Hello hi friends welcome back today we are going to solid code problem 24 and 240 500 g test for distance to enter for scissors equal shortest distance problem only it is good to solve the problem statement from the is that you have been given here of words as you can c servi have been given to different words and will have to find the minimum distance between two words before they discuss the rate approach and implementation is just want to mention the type of account create key lead videos s well s java j2ee interview related videos and have Created The Giver Playlist And Like And Difficult Solutions Binary Search Tree Solutions And Lot Of Different Problems On It Code Sonu Sir Please Do Subscribe To This Channel Your Subscription Will Help The Channel So Let's Not Look Distance From This Problem Solve This You Can See You Will Sit in English Word Series Pencil Coding Practice Makes Perfect Coding and Mixed 1600 Indicators of Your Interest and Which You Have Been Given Two Words Coding and Means to Have to Find the Minimum Distance Between Its True Words But Some Distance Between Specifically for Example Which According to Its Coordinates of Indices for and Mix in Taxes for a Short Distance Between This 225 - Previous This Dynasty Distance Between This 225 - Previous This Dynasty Distance Between This 225 - Previous This Dynasty This Episode Distance President to Directions Distance Calculator Solve Viewer Point to Solve This Problem Which Will Have to Approach S Hui and Two Types of Solution for This Problem Solved and Fennel First Approach Argument Use Map to Solve the Problem of What We Are Going to Is Will It Increase Awards and Wherever You Will Find the World Like Coding and Mix Swallow Koi Find Any Abusive Words Will It Be This Map Of string soft list frontiers captured the list of in tiers for coding rights for coding middling appears that position zero and according appears that position for solving and convenience for these earliest and similarly for max player two and mix exact position five point at least two And five using he is proud for these two words and after you are done with the universe creation for her time is gifted on time day what will you give in to this post at least 100 lift world and for each of the India should compare this with Second list index and will find out per distance for example if you will find 2012 to distance to 2015 distances five at the same time I will keep track of the minimum distance have seen so for software hui house in the distance to right 2012 is 2015 This 500 minimum distance to now will go to next index for now you will again calculate distance between two and 400g distance between two so will not do anything because our minimum distance dongri to na welcome practice for and 500 loot from distance s12 will update and minimum Distance to 150 grams development and lower head back to states have you will find the minimum distance between two words so let's look at the implementation of this that you problem using his mother son s you can see is to the same word series it awards and hui is the function where passing awards and to give one to words rate shiv world player who has been given his mates and another is doing this so let's look at the implementation for the short distance for this you have defined and create a map clear is the time string and List Open Teacher and Boy Irritating Hair Rupees Tied a Great Words and They Never for Each Word Which Gives the Map Does Not Contain World Busy Creative Brain During Illness and Added One to the List Hair and Valued at Least in Two The Map of the World So Will data peer which is the world and yadav allied war list is already existing and placid for maths and waste index in the map in to-do list waste index in the map in to-do list waste index in the map in to-do list and now you will add new earliest into the map hair oil sofa this point to you already have app Created right and after doing a great service to and e stud and villagers define one variable contact distances appear to have elected through destroyed and stud and will keep track of the world compare least to distance with least one life least two minus b to you will get Clear And Calculate The Systems Were Sickly And Keep Track Of The Meaning Of This We Have To Yaar Solve Will Always Check The Distance 09 2008 Distance Between Minimum Distance And Even Threat Of Two Words So Hair Oil Will Keep Updating Disturb This Rumor Using Maths Dominar 400 Fit will give the minimum distance development of method of meat and give food to point and distances 130 years back also improve the implementation solid message me weekly anshu sauce you can see forces paytm app for coding 2014 and for mac 2002 and favorite software item start exam Start 100 Am 500 Shares As You Can See Code English Hero End 4 End Maxists To End Favorite Show The Spot Where To Find You Get Here In Our Where Running The Program Belt 2014 End To End ₹500 Will Run On For Look 2014 End To End ₹500 Will Run On For Look 2014 End To End ₹500 Will Run On For Look After 10 Created To Welcome 350 500 will keep track of the minimum distance 102 2025 minimum is the two only right and will take fourth next react reaction foreign tour minimum distance two and four and five men in fab - police one so let's you find in fab - police one so let's you find in fab - police one so let's you find the minimum distance one saw this Is one of the proposed a few have a source of the earliest forward approach viewers Middle East and you compare list distress and distances 34 index with index in Delhi schools that Chief Controller comparing dal plate dual updated distance of minimum distance 533 way approach for the Boss You Have Seen Same Hall Defamed Mix Encoding S1 Distance Because Coding Is Hair Porn 0123 4 100 Index 40 Index Is 5.5 Width 5.5 Width 5.5 Width Minimum Distance From That Is Already Scheduled Dates Minimum Distance Raw One And Whose Printed The Map Just To Show You How Amazing Integrated Selection Lipstick Look at the same problem which can solve using preset Subha This another approach you have to solve the same problem solver Look again kiddie Are of words and will power trees and you will create set one for coding and two for maths wherever they find The world according year boy just a date sex in dogs tight sw0 and four years and for matters will have two and five year so I have to see its new ones with 0.125 solid liquid start less laddu with 0.125 solid liquid start less laddu with 0.125 solid liquid start less laddu or running so both in president example directly create A Little But Another Example For girl can compute the example of in a sunil ramdas sowry set one will get one and industry to you get to front well also have to 5th same whatsapp message send coding software engineer passing muster force world and codings our second world according and second world Are To Be A 210 You Can See The Two And Five Formed For Mixed With Cosmic Appear Into The Opposition 0.2 And Five And For Coding Where 0.2 And Five And For Coding Where 0.2 And Five And For Coding Where Finding 10 And 4.0 Latest Spend A Best Wishes For 4.0 Latest Spend A Best Wishes For 4.0 Latest Spend A Best Wishes For Swift Code 130 Hui First Created To Research And In What We Will Do Is Will Reduce Set 151 Scheduled Tribe Comparing The Person Reset Have To Function Called As Floor And Higher Floor Will Give You A That Dulled Thing Looser Value And Its To But Which Is The Maximum Shopping Discuss Refined War Drink Low Sir Value Will Get 300 seats from the 2nd part to the high value purchase order minimum wages for here right needle for hair soft tissue you will get these values and key for hair soft tissue you will get these values and key for hair soft tissue you will get these values and key base values comparing with this base values comparing with this base values comparing with this original value and keep calculating distance for example wore hui 10 2012 - distance for example wore hui 10 2012 - distance for example wore hui 10 2012 - 0is to that Is The Distance And To For - 0is to that Is The Distance And To For - 0is to that Is The Distance And To For - 22222 Is Our Distance For The Minimum The Next Time Between Phases Compare The Place Value From Klusener Dho Maximum Valid Point For Indian Values Bigger Than Values Bigger Than Values Bigger Than Five Missing 5mm And Velvet Suggest That Bigg Boss Minus One And Its Uses Calculate 514 Basically there are five lines and the suite candidates leftist f-18 so let's you candidates leftist f-18 so let's you candidates leftist f-18 so let's you using the reset clear neuralgia till hui Arun Vyas interesting through the year awards and honor for watching the set top edit * starts from 2512 editing 272 top edit * starts from 2512 editing 272 top edit * starts from 2512 editing 272 that Sonia the receiver is already Looking Great Scientist Finding Correct Index This Day Will Just Different One Variable Contact Distance And Hui A True Between Value Pin Set Per And Will Reduce Floor Method To Find The Value Is Layer Pendant Value What Maximum Well Wishes Is The Floor And Higher Give You Like The values at least value which more can be values at least value which more can be values at least value which more can be united for example here is the whole fine value of example like late to full 155 and list 12345 to maximum lower and higher means the value of higher than five but least 50 years - 119 basically you can 50 years - 119 basically you can 50 years - 119 basically you can Find the world with flower and equal distance calculation after life they will not be possible only when you are down to icon player only say yes to remove network alerts how to select 102 friend ko rakt disawar set one member set one let Set one is this and state to this different plate Shesha vansh three and 500 unit se effective where trying to find out the blitz hui and that this tour of tourism place so this is right down the year student should they two floor of two day it Will give what the value inches less than to but maximum value what is that * say in this and to it value what is that * say in this and to it value what is that * say in this and to it is increased s and when will do higher function festival function on to day guys the value of which is more than to but at least amount of Class 12th Sutra In Protest Of Lower And Higher Work Tubelight To Aaye Hai Us A Shown With This Example Of Lower And Higher Will Work With Ki To Write Similarly In Flat From Your Finding Both For Ki Right Yr Ki From This Point That Is For So You Are doing and of lower order for rice floor of birth date is the co minimum value so student for right and when you here after higher of two-four days you will get five in situ development that is two-four days you will get five in situ development that is two-four days you will get five in situ development that is the value which is ireland four in the city Tour of which might have no other way but it's a seven days but will give five decades that is the least amount of value between sex for father is no valid will give you not right I returned home want to mention with examples for it's clear in the Floor and hard work should be removed from hair soft important meeting done setting on the floor itself value and give a little distance by practice but with original position from three and will keep updating minimum similarly they will keep updating minimum balance subscribe to that suppositions to here And the back 100 with floor and forward will be char with lower right with your function so like that you put a five day in backward v4 rebellion function and forward additional forward values mihir additional forward values mihir additional forward values mihir velayudhan512 in the test will be minus one right 100 gu computers distance And you will get only Ramesh to minimum distance 135 - Ko has Ramesh to minimum distance 135 - Ko has Ramesh to minimum distance 135 - Ko has one should support this has given for the process of working correctly you 200 Amazon discussed in detail about after this process so it will check in this code * process so it will check in this code * process so it will check in this code * Maggi tha program new ticket from rate You not change your values and ignore tried to understand how not change your values and ignore tried to understand how not change your values and ignore tried to understand how the floor and hard work order to create and how to find pollution and research center nearby open delete code javat solution videos as well as you know java j2ee related interview questions have created play list For Binary Search Tree Edifice Solution Celebs Return Fully Some Problems Solutions After All Deaths In To My Channel Please like Share and subscribe the Channel Please subscribe Really Help Please subscribe thanks for watching the video
|
Shortest Word Distance II
|
shortest-word-distance-ii
|
Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.
Implement the `WordDistance` class:
* `WordDistance(String[] wordsDict)` initializes the object with the strings array `wordsDict`.
* `int shortest(String word1, String word2)` returns the shortest distance between `word1` and `word2` in the array `wordsDict`.
**Example 1:**
**Input**
\[ "WordDistance ", "shortest ", "shortest "\]
\[\[\[ "practice ", "makes ", "perfect ", "coding ", "makes "\]\], \[ "coding ", "practice "\], \[ "makes ", "coding "\]\]
**Output**
\[null, 3, 1\]
**Explanation**
WordDistance wordDistance = new WordDistance(\[ "practice ", "makes ", "perfect ", "coding ", "makes "\]);
wordDistance.shortest( "coding ", "practice "); // return 3
wordDistance.shortest( "makes ", "coding "); // return 1
**Constraints:**
* `1 <= wordsDict.length <= 3 * 104`
* `1 <= wordsDict[i].length <= 10`
* `wordsDict[i]` consists of lowercase English letters.
* `word1` and `word2` are in `wordsDict`.
* `word1 != word2`
* At most `5000` calls will be made to `shortest`.
| null |
Array,Hash Table,Two Pointers,String,Design
|
Medium
|
21,243,245
|
240 |
lead code practice time so in this video there are two goals the first goal is to see uh how to solve this problem uh and then we are going to put some code here and the second goal is to see how we should behave in a real interview so let's get started so remember the first step in real interview is always try to fully understand the problem if there is anything unclear please bring up the clarification question and at the same time think about some match cases so let's read through this problem it's called search a 2d matrix too so write an efficient algorithm that search for a target value in a and by an integer matrix the matrix has a following property so integers in row each row are sorted in ascending other from left to right and the integer in each column are sorted in uh ascending other from top to bottom so it's like from left to right is sorted from up to the bottom is sorted um so let's see this matrix and uh yeah so search for the target so let's say for this matrix we are trying to search five and similarly for this one when we try to search for 20 if it doesn't exist then we are going to return false okay so let's see some constraints it says that m and n so it's for sure that uh it is not going to be a empty matrix and uh it says that each element is within minus one billion to one billion and all the integers in each row are sorted against any other all the columns or sardines and the other and the target is between minus one billion to one billion so uh having said that i think for this type of the question usually it is started from the upper right corner or bottom left corner and then move the each step you just move to the left or to the suppose we start from the upper right corner then each time we just move to the right uh sorry move to the left or move to the bottom so let's see um if so let's see for this let's start from this corner if it is smaller then we are just going to move to the left uh so we move here when we move here is we see that it is smaller then we are going to move uh to the left so because the reason is because if the number of years the target you're searching for is smaller than this number then you don't really need to see everything uh in this column because this is certainly as any other so uh and uh if you are let's see if the number you're searching for is uh smaller than this number then you don't need to see this one this part the writer part so in this way uh we can just uh filter a lot of things um so it's like we go from here to here and we see that it's uh it is it's more than four then he moved to the bottom so um i think we should be good about uh sounding this problem so the runtime is going to be uh so this runtime is going to be o m plus n uh so having said that um let's do some coding work so for coding uh we care about the correctness of the code the readability of the code and of course the speed is concerned so let's see uh let's see in row is equal to uh the matrix that is that it's the matrix dot plus minus one and in column all right so actually the in column is because we are starting from the upper right corner then the column is actually matrix 0 that lens minus 1. and this one it is actually starting from zero okay so um well uh the row is smaller than matrix. and the column is larger or equal to zero now we are going to see if the matrix row call is equal to target then we are going to return true otherwise um if the matrix um row uh is larger than the target then we are going to plus the row otherwise we are going to if it is smaller uh then we are going to minus the column yes and finally we here we are going to return floss here so let's see this example so we start from here you see the 5 is smaller than we are going to uh minus column so now it is larger than we are going to plus zero and then we are returning true so i think um the time okay so i forgot to mention that after doing coding it's time for us to do some testing usually you do some sanity check by going through our example explain how this piece of code is going to work and at the same time fixing some books within the code and i think after he goes through this task is it's good and for this one um when we try to search for 20 we first go to here and then we go to here then you go to here and here we go out of the range and we are going to return false so let's uh do some testing so it says wrong answer what is wrong answer so let's see uh row is zero column is matrix zero lens minus one okay so well row is uh smaller than that and the column is larger or equal to zero so if matrix zero column is equal to target we return true if the matrix if the target is a smaller thing if target is smaller then we are going to actually here i think we just did it wrong if the column if the target is smaller than the current element then you're actually moving minus the column if the target is larger than the current thing you're going to plus zero so let's run again yep so now it's good uh let's do a submission for it alright so uh everything works well so that's it for this coding question if you have any questions about the puzzle or about the solution itself feel free to leave some comments below if you like this video please help subscribe to this channel i'll see you next time thanks for watching
|
Search a 2D Matrix II
|
search-a-2d-matrix-ii
|
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:
* Integers in each row are sorted in ascending from left to right.
* Integers in each column are sorted in ascending from top to bottom.
**Example 1:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= n, m <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the integers in each row are **sorted** in ascending order.
* All the integers in each column are **sorted** in ascending order.
* `-109 <= target <= 109`
| null |
Array,Binary Search,Divide and Conquer,Matrix
|
Medium
|
74
|
257 |
welcome ladies and gentlemen boys and girls today we're going to solve another problem which is binary tree path so basically this is one of the good problem so but the question is it's quite simple so the question is saying like uh we are given a root over by tree and we have to return all root to leave in any order okay so the order does not matter but we have to written it's all the foam is from the roots from over here to its leaf over here so this is our root and this is the leaf node this is the left side and from the right side uh this leaf so this is left side and this is the right side so over here so okay so how we have to do it we have to do one two five and one three like this if you carefully look at over here if you carefully see we have to written something like this in the stream format so the question is it's not too hard but the only difficulty in this one we have to written in the form of string okay so let's general let's start solving the problems for how we're going to do this so first of all i will suggest you to look at this constraints so let us see anything like we do have deal with any base condition and um they are saying like the number of not present in is from 1 200 okay so it means like there might be something present over here so we don't get any we don't have to write any base condition but let's just we will write it over here anyways so what i will do over here my first job is to create an arraylist where i will get my final result find the output so okay and it has to compare then it has to be in the form of string okay so let me i mean hold as result simple and this new array list okay i'll show these things clear okay now what i will do i will get my base condition i will say if my root is no let's just say we get empty so i will simply uh return my result over here okay and now what i will do i will make up i will make a function called i will make another function called that function called helps me to get the complete order from this root to the left okay so let me just call that one as a uh helper and finally written the result over here so this is the simple thing okay now let me just create my headphone function over here so for that i will use void helper okay and this is three node root and path will be present in the form of string path and what else we have to i have to make a call to my result as well if you remember arraylist okay and this arraylist is present in the form string result and here we go ladies gentlemen so i hope so this thing is clear what i'm doing all right guys okay now here things come so what i will do i will create one condition over here but my condition will say if my root left is null and my root total right is null as well so this is let's say our another base condition for this one if the only root is over here it doesn't have any leaf node okay then what i will do i will simply say result and add to my array list what path plus root value simple guys okay now over here now what i'm say i will say add this will add my left value until it does not reach null okay so you know i have to i will add my left value until it does not reach null over here like this in this one okay so till then this thing will work so what i will do i will simply make a uh a function called helper and in this one i will say root uh off left with path so uh path plus total value plus this sign if you remember this sign you know as you see over here you'll see over here that's the sign we have to give this one so that's what i'm doing over here okay and finally make a call to our result as well okay guys i hope the code is simple that the code is not too hard the only thing is like uh you have to get literally any form of string that's all looking over here similar thing i will go for my uh right side of my binary tree okay guys plus root value plus all right and reasons so i that's all our code lineage german let me just give a quick run here let's see any compilation error do we face over here then i will talk about its type of basically so we just get a compression over here what is saying as new array list okay oh that's what mistakes happen so it's okay that's why we call engineers because we build twos for the mistakes anyways guys let me just give a quick glance and here we go ladies and gentlemen so it's accepting very well okay so let me just talk about this time complexity so in this one guys time complexity we are dealing with is because n log n two because n square okay so what so did this will be for our best case and this is what our worst case okay so i have all these things here if you still have any dot other cs2 just do let me know in the comment section i will definitely go on these two guys and thank you ladies and gentlemen for watching this video i hope this video uh helps you a lot so if you still have any i was again saying just do let me know in the comment section till then take care bye and i love you guys believe me i love you take care bye
|
Binary Tree Paths
|
binary-tree-paths
|
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,null,5\]
**Output:** \[ "1->2->5 ", "1->3 "\]
**Example 2:**
**Input:** root = \[1\]
**Output:** \[ "1 "\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `-100 <= Node.val <= 100`
| null |
String,Backtracking,Tree,Depth-First Search,Binary Tree
|
Easy
|
113,1030,2217
|
493 |
That Everyone Welcome To My Channel Today Will Be Solving Problems Reverse Pastry Sheet Sharif But You Will Give In Exams Date Of Account Number Of Paris I Ko Maje Sach It Is Always Speak And Evaluate Aaye Cigarette The Voice Of Divya J7 Straight Person Others 1323 210 President Top Vegetation And S One Which Mix Player And S One So Let's Check The Example You Can See The Notifications York And Easy Way To Meet His Death Was Not Physically Tea Or Coffee And Doesn't For Your Request Your Is note print voice of 25th year to computer all depends true that divine of infidelity awadhesh leaf now jan22 directly all the place which settles for giving total number of players for this thank you are in interview first prize for literature from where to check how many jio4gvoice Light condition key to share and where you can donate Modi is charged and you will get off account Tweet Time complexity of this approach s Basically a running approach s Basically a running approach s Basically a running universe itself and space complexities Soaked oven Sainik Tabs Interview will ask you to optimize scooter Time Complexity Do Something Better Nadi Approach That We Can Discuss Will Be Similar To Something Which Will Discuss Any Problem In Work Hand Notes In The Video Of Highly Recommend You To Pause Video Right Way And Degradation And Watch All The Best Video Editing Tobacco And Watch Modified Mode Start Which Will Be Required To Solve This Problem Not Withdraw His Physical Speed Come To Hearts Of This Again Withdraw His Physical Speed Come To Hearts Of This Again Withdraw His Physical Speed Come To Hearts Of This Again Into House And Over Again Into House To Enter Must Try Something Like This Is Not Divide Subscribe To March Me Hi Laptop And Unite Together So To -do this Laptop And Unite Together So To -do this Laptop And Unite Together So To -do this method left padhare vinod 108 itself and within life threads vinod let's get started in itself and fixed deposit ia bd starting point of laptop and fixed deposit visited the starting point of the right to vote for india vs v t20 i contact for sand android me desmond tutu true nx100 that more life condition remedies this is always garlic ok voice of egypt vacancy recent job will take displaced with support this garlic thukudu sava 100 semolina stage right one and a half hundred will remain this from initial 21.00 spike in se reduce will have contributed by answer agree remain this from initial 21.00 spike in se reduce will have contributed by answer agree And understand is removed after 10 years mung or a sword on pc this is done and which left a great support you should not be checked for the and considers no contribution of this form mode tap and you will get 2014 90 laptop and decide for the first time Subscribe 505 10's Business New Zealand You For The Element In Laptop Windows 10 From It's Something Like It Well Known Key Setting Next Step If OTP Laptop Diye Sorted By Others On Aam Aadmi Party And Right Of Waste Oil को मनाये या And Right Of Waste Oil को मनाये या And Right Of Waste Oil को मनाये या 0.5 INCH FROM POINT Shri over nor I will 0.5 INCH FROM POINT Shri over nor I will 0.5 INCH FROM POINT Shri over nor I will stand and India to the amazing issues related to atrocities comprehensive and 0151 not garlic covered health * sad why important issues Intact to garlic covered health * sad why important issues Intact to garlic covered health * sad why important issues Intact to this na aaye rest in peace 25s lashes equal to wife in the thirty-eight 120th equal to wife in the thirty-eight 120th equal to wife in the thirty-eight 120th give point modification directly Initial position and this point wo and they will be guided by one and Shayari of Baroda 25th scan their affair diner everything on the left of ninth paper because they are sorted in excel super 2018 their face value day accept movie I point and remember one Thing E Will Stand Otherwise Complex Will Not Be Something 28-12-2012 Also Want To Listen Shyam Ki 28-12-2012 Also Want To Listen Shyam Ki 28-12-2012 Also Want To Listen Shyam Ki DJ subscribe This is not less 1.8 Do not DJ subscribe This is not less 1.8 Do not DJ subscribe This is not less 1.8 Do not emphasize the number of elements select this will not go into me in this ten disa left exhausted and you Can Search Operations Observe Positive This Compound Schezwan Price Officer Will Not Move DJ Point Listening Things Will Prevent Violence 151 Sa Worthy Fit And Way Can Perform WhatsApp App Minimal Set Up This Will U Something Like Schezwan Sauce Use That Point To 6 October Disa Jail Because Sikhs Are Not Garlic 1022 Basically Element And Digits In Next Roadways There More 108 Exhausted Even Stopped And You Can See The Audience And 251 Alarms That Can Make With Obscene Dance Sannikshep Yoga In This Is To Think Tanks Gas Already Exhausted After 10 Minutes Or From laptop dell 1781 mortal remains of visible form much sleep will give us 60 hp laptop rate is quite well and this point to decide subscribe condition of listening to * * * * * you can see this has been left 1615 2009 subscribe is not garlic ok Ult Him Greatest Wealth Gold Trader Mukesh Point To 98100 Not Difficult 25.22 Next Index Straight Half Difficult 25.22 Next Index Straight Half Difficult 25.22 Next Index Straight Half Exhausted Doing When Will Stop At All Elements From 98100 Vijay Has Already Been A Real The Way To 600 Condition Will Also Be Satisfied Condition Next 9 0 A Possible Also Faculty Development Education Society With Real If You Can Meet Business And Idol iPod Over Sunday Laptop Diya Reddy Andaz Dhania Going To Stop This Only Slow Hotspot Anil Maurya 29808 S2 6050 Kali Aarti Jeevan Beach Tube Light Bill Story Edition Of This Will Give One Number Of S A Loss Of Operation For Temporary Tuition-Hussan 10:30 That Bigg Boss Ne Tuition-Hussan 10:30 That Bigg Boss Ne Tuition-Hussan 10:30 That Bigg Boss Ne Noida Maximum On This Number Subscribe Near Android Maximo December Subscribe Now He Died From Starting Every Time She Came Into To Do You Want To Here From Only Rather Than Seven time to two to the number only and not for this channel subscribe kar jaawat aavat solution subscribe which will give us a absolutely slow shot function vriddhi no 9 and start from zero and minus one are basically folk my sweet heart function school with low earnings Half switch a video single element in a single element crazy that country to my and software written during and after that is computed minute low plus highway 2 and once completed roadways I opened the laptop days to come and the removed life in it plus one earned basically Called Electric Question and Divide Trick Question Awadhi Electric Question and Electrification Has Been Equated Complete Hi Pade Cycles March Function in This Award Function Help in Writing My Complete Two Computer Number of Inventions Per Stop This Problem Solve Pass Dilon Home Made and Why Know the Length of But from dreaming your right of bihar will be from mix plus one to hi new business prohibition law 2016 jail ad starting position and brighter clear admit plus one you definitely hydrate come from you to meet her destiny left pop the are and orders is just keep Checking for this condition dedh seedhi right for age subsidy all a good condition is not been met binal ki full movie hindi hj point and once in this condition clear but i know which zooms in next true dedication smart 16 2010 any number of left elements flu Control Room And 6406 - In Plus One Of The Volume Slow And 6406 - In Plus One Of The Volume Slow And 6406 - In Plus One Of The Volume Slow In This Function Positive Computer Day Number Of Years In Account Solid Waste It Clearly Stop Interior Temple And Any Slice 250 Ayogvah Yadav Dynasty Admit Plus One And Half Inch Pocket Rating IQ Variables Must Smaller And Anti Shatter Maze Degree Left Right Left Smaller And The Temple Run List Channel Increase Right Left Parties Pain And Right Toe Health Tips Gyan In Hindi Original Hum Saare Laddu Ise Simply Divya Total Number Of S A 154 Cigarettes Total Number Of Years You Can edit to the invention and in return the invention for every request equal and ultimately you will get answers for pun shot witch you can return chief total number of this channel must subscribe very nice bro and sis and minus one witch element returns of the day Middle Class 2nd Test Day 1 Question Awadhi Light of the Question Laddan To Takal Dheema In This World Computer Number of March Buddhi Left and Right Lower Middle and Lower Starting Point of View Account 2012 Total Number of Users Like This Post and Copyright Day Plus One To The Point From Low To Make Sure You Keep It Inside This Year Also Moving A Little Any 20 Condition Said Cords Life Is Condition If Light Up Drs A Soft And The Second Condition Variety Garlic Request Condition Satisfied Patio Umbrella Cut This Loot Direct Contact number of elements of this malefic planet will contribute free number of paris of the rectangle index element as its pregnancy player ata gel minus one decade the number of elements loop fennel computer's total number of invention place for the left and right of they are Together if to medium flame function solid west side declare a temporary vector product that I please chief loop point edifice index of the left side and pleased with right point addition of the white a way that is simply meeting that antioxidant absolute question is my love Is Possible In Temple Dish Now And Increase The Left Point One Will Dare Attack You Have Completed A Big Boss Se Left Side In All The Meaning Of Left Side Don't Forget To Subscribe So Basically Turn Off The Number One Time Varicocel Call 100 2018 Se Bank Account Of Invention Over All The Receiver Schools Will Be I Tears That Is What I Can Write Directly So In This They Can Get Answers Sanseri Bandhe The Drawing Room And Intuition Shifted Please Like Share Like This Video YouTube Channel Subscribe To All Of You Want To for Instagram and Ajwain and Telegram group discussion with us after this video you will be updated on
|
Reverse Pairs
|
reverse-pairs
|
Given an integer array `nums`, return _the number of **reverse pairs** in the array_.
A **reverse pair** is a pair `(i, j)` where:
* `0 <= i < j < nums.length` and
* `nums[i] > 2 * nums[j]`.
**Example 1:**
**Input:** nums = \[1,3,2,3,1\]
**Output:** 2
**Explanation:** The reverse pairs are:
(1, 4) --> nums\[1\] = 3, nums\[4\] = 1, 3 > 2 \* 1
(3, 4) --> nums\[3\] = 3, nums\[4\] = 1, 3 > 2 \* 1
**Example 2:**
**Input:** nums = \[2,4,3,5,1\]
**Output:** 3
**Explanation:** The reverse pairs are:
(1, 4) --> nums\[1\] = 4, nums\[4\] = 1, 4 > 2 \* 1
(2, 4) --> nums\[2\] = 3, nums\[4\] = 1, 3 > 2 \* 1
(3, 4) --> nums\[3\] = 5, nums\[4\] = 1, 5 > 2 \* 1
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-231 <= nums[i] <= 231 - 1`
| null |
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
|
Hard
|
315,327
|
1,372 |
hello fellow ops and welcome to another uh video on the app hacksaw youtube channel uh today we're going to be going over another leak code problem uh 1372 longest zigzag path in a binary tree so this is a tree problem um we're going to be using a depth first search algorithm with a uh that is recursive so this problem is interesting we're going to have fun with it let's go ahead and get started so let's go over the problem statement given a binary tree root a zigzag path for a binary tree is defined as follows choose any node in the binary tree and a direction right or left if the current direction is right then move to the right child of the current node otherwise move to the left child change the direction from right to left or from left to right there's a typo there repeat the second and third steps until you can't move in the tree so the zigzag length is defined as the number of nodes visited minus one so that means a single node has a length of zero and we return the longest zigzag path that is contained in a tree so let's go over example one uh we are starting our zigzag at the second or the one on the second level of the tree right here so we're starting out by going right go right here and then uh because we went right we have to switch our direction to left and then right and that's it that is the longest one if we had started at the root we would be able to go right and then left and we would be stuck so that's why we start here right left right and our output is three because um so again number of nodes visited minus one so one two three four minus one is three or you can view it as uh just um the edges one two three let's go to the second example so for this one uh we start at the root and our first direction is left so we go left right and our longest zigzag path is four example three if you just have a root then and that's it your longest exact path is zero because there are no other nodes that can be visited alright guys so let's go over the solution we are now in our eclipse ide let me show you what's going on here so we have our tree node static class which is given to us by elite code uh we have our solution methods uh this is straight from our solutions on the op sort website we have our main method where i'm instantiating the variables so let's go ahead and start a debug session alright so now we've instantiated our tree uh this is the same tree that you guys can see it's example two from leak code so let's jump into our method longest zigzag and then here we're going to just go straight into our recursive dfs method so this is our base case if the root is null then we return zero that represents zero length now so now we have into l uh equals dfs node left and then false that's just a boolean for whether it's a left variable so let's see what's going on here this method is going to give us our length call if we were starting our zigzag search at this node right so let's go into that so that means right now we are on the one on the second level of the tree uh to the left so it's the left child of the root and now we're gonna we call this right obviously this is going to be null because the left child of the root does not have a left child itself so it's null we return length of 0 and we can see that l all right so i made a minor modification to our overlay here i put the tree from leeco into our white board so we can better uh talk about what is going on here so i'm going to call this one a b c d e f and g all right so right now we're on b and l of b returned zero because b does not have a left shot so r we're going to go into r and actually i'm going to label what just happened on the whiteboard so l b is zero and now we're on right of b so now our current node is d and when we go into l now we are on node e and if we go into that we're going to return no because e does not have a left child so that's zero and we go into the right node now we're on node g so l and r are both going to return zero here and we can see that zero all right now let's see what happens when we go past these two so remember we're on g currently so we do math.max so we do math.max so we do math.max of the current result so result here we have our uh it's a field so the whole class can see it and it is a constant value or not a constant value but every um recursive call can see the same value for results so we just math.max it with for results so we just math.max it with for results so we just math.max it with what we got here so result is zero l and r are both zero so result ends up not changing and then we return our sum uh for the parent so is left if it's a left if this is a left node then we return one plus the value that we got for l so for g um since the is left boolean is true and essentially what this boolean is it doesn't actually represent whether it's a left node what it really represents is the alternation so uh this value is always going to alternate so when we first call the dfs function we pass true and then when we go left it becomes false um and then when we go right it becomes true so it's an alternation is what it is so g returns one because l and r were both zero so one plus zero and now we're back at e um so e has an l value of zero and an r value of one so let's record that zero r one of course right so uh we math.max right so uh we math.max right so uh we math.max l that's still going to be zero we mapped out max result and that is going to be one uh so you can see result has turned into one and now here the islet variable is false so we're going to record the value from r so we do one plus r uh so we return 2 for that parent right so now we're on d so d got an l value of 2. and i'm not going to go into the uh r value dfs because we get the idea so f is going to return zero and our l is going to have zero for uh l and zero for the right node as well so that means it's going to return 1 to d so d will have an r value of 1. if i run that we can see 1. so again we mapped out max results result will turn into two because l is two uh that will not do anything and then again the is left is now true because we're alternating so return one plus the l value so l value is two we return one plus three to the parent um which is b so that was right it was the right child of b so let's record that we got three and yep three math.max l that's zero and yep three math.max l that's zero and yep three math.max l that's zero will do nothing math.max r and result so we have three math.max r and result so we have three math.max r and result so we have three as the new value result will become three and is left is false so we're going to get one plus the value for l uh which means we will be returning uh l is i'm sorry is left is false here so we return we will be returning the value for r so we will be returning one plus three to the parent which is a the root so a has an l of four and we know that this is going to be zero which means r will be one for a and indeed it is uh math.max the results so result would uh math.max the results so result would uh math.max the results so result would turn into four because l was four and we don't care about the return value here and we simply return the result that's it four and there is indeed four zigzags uh in this tree so this problem showcases the beauty of recursion it's very useful for tree problems uh we are doing a depth first search uh because you can see uh when we go past the recursion or when we first start calculating results we are at g so the node with the highest depth on the left hand side so this has the highest step out of everything that's g and then the next value we calculate is e uh and so forth and of course f and then d right so i hope you guys enjoyed doing this problem um leave a comment if you have any questions or if you would like to provide some feedback otherwise please like and subscribe and we'll see you next time thank you very much you
|
Longest ZigZag Path in a Binary Tree
|
check-if-it-is-a-good-array
|
You are given the `root` of a binary tree.
A ZigZag path for a binary tree is defined as follow:
* Choose **any** node in the binary tree and a direction (right or left).
* If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
* Change the direction from right to left or from left to right.
* Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return _the longest **ZigZag** path contained in that tree_.
**Example 1:**
**Input:** root = \[1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1\]
**Output:** 3
**Explanation:** Longest ZigZag path in blue nodes (right -> left -> right).
**Example 2:**
**Input:** root = \[1,1,1,null,1,null,null,1,1,null,1\]
**Output:** 4
**Explanation:** Longest ZigZag path in blue nodes (left -> right -> left -> right).
**Example 3:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 100`
|
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
|
Array,Math,Number Theory
|
Hard
| null |
322 |
hello everyone welcome to codescan and today we are going to cover coin change so the given input here is an integer array coins and an integer value amount we have to return the minimum number of coins needed to form this amount so let's understand this problem statement with an example so here is a given input the integer array points represent the different denomination of coins available for us and we can assume there are infinite number of coins available in the given denominations and the amount given here is 11 and we need to return the minimum number of coins needed to form amount 11. so consider the first coin one so you need 11 one rupee coins to form 11 rupees the same way if you consider two rupee coins then you need five two denomination coins to form 10 and one more one rupee coin or one denomination coin to form 11 so in total you need five plus one six coins to form 11 same way if you consider the last coin five you need two five rupee coins and one rupee coin to form amount eleven so in this case you need two plus one three coins to form 11. so out of all the solutions three is going to be the minimum coins required to form amount 11 and that is going to be our output so how are we going to approach this you can approach this way our dfs recursion dp since i have learned how dp solution works and become a big fan of linear dp solutions so now in this video we are going to see how we are going to get the help of dp to solve this problem so let's go to the solution so here is our dp array which represents the amount given in the problem and we are going to fill the array and arrive at our solution at the last cell of the array so before understanding the pattern of how the array is being filled i wanted to understand why we are filling that array in such way that is each cell here represent a sub problem it will solve or arrive at a solution for each sub problem and from that sub problem calculate the solution for the next sub problem and finally arrive at the solution for the bigger problem so let's start filling the values so now let's first fill the two columns with the values we know that is it represent the amount so we are going to calculate how many coins needed to form the amount zero we literally need zero coins so let's fill zero here and moving on to one to achieve amount one we there can be only one possible solution that is we need one rupee denominated coin so we are going to fill one here so now let's start filling from index two so index two represent the amount two so from the given coins what are the possible ways to form coin two that is you can either have two one rupee coins or two one denominated coins or one two denominated coin it can be formed using two one coins or one two coin so in this way which is the minimum we know one is the minimum that is you can form two in one coin itself so that is gonna be the answer for this sub problem that is forming amount 2 using minimum number of coin is going to be 1 so now moving on to the amount 3 so now i want you to understand that we have formed the amount two by using minimum number of coins the solution is here that is we have used one coin to form amount two so if we want to form amount three we can add only one rupee or one dollar to make it to amount three from two so in this case from two that is we have used this many coins to form among two you can add only one rupee coin to make it three so the first possibility is you can have two coins to form three that is how did we get this to from 2 that is from amount 2 we have used one coin to form amount 2 from that solution you are adding one more one rupee coin to make it to amount 3 so far the solution plus one gives us two so this is one solution and from amount one if you add a two rupee coin you will get amount three that is from amount one if you add two rupees you will reach three rupees so we have one solution at that point from that you need to add one two rupee coin so far the solution is one you are going to add one more coin so it is gonna be two so there can be two solutions that is from amount two you can add one rupee coin or from amount one you can add 2 rupee coin so we got 2 in both the cases so whichever is minimum we are going to update that with our array so now it's time to move to our amount 4 similar way we have formed amount 3 by using two coins so along with this two coins you can add only one rupee coin to make it to amount four so the solution is two plus one three same way from two rupees if you add one more two rupees you can reach amount four so far the least number of coins needed to form amount two is one along with that you are going to add one two rupee coin so one plus one two rupee coin is going to be two so now we are going to update our amount four with minimum number of coins required so minimum is two so i am going to update it with value 2. so if you observe we are just arriving at a solution for each sub problem if you individually see that is the minimum number of coins needed to form amount 4 from the given coins is 2 that is 2 plus 2 will give you 4 this is the optimal or minimum solution for this sub problem so each cell represents solution for a sub problem or solution for the minimum number of coins needed to form that particular amount now let's move on to our amount five same way from amount four if you add one rupee coin you will get about five so far to form amount four the minimum coins needed was two with that we are going to add one rupee coin so the total coins are three same way from amount three if you add one two rupee coin it is gonna be becoming five so for the coins needed to form amount three is two along with that we are going to add one two rupee coin so that is gonna be three points again also since the amount is five we have one more coin to be considered that is five so from zero if you add one five rupee coin it is gonna make it amount five so it requires only one coin that is previously to form zero we needed zero coins along with that we are going to have only one five rupee coin so it is gonna need one coin to form about five so out of these three the least is going to be one i'm gonna update here one so now moving on to our amount six we are going to consider amount five plus one rupee coin so one plus two gives us two coins also from amount four we are going to add one two rupee coin so two plus one give us three from amount one we are going to add one five rupee coin which is going to give us 1 plus 1 2 so minimum out of this is going to be 2 i'm updating among 2 with 2 coins so if you see going on to our amount 7 i'm going to consider amount 6 plus 1 rupee coin which is going to be three and a month five plus two rupee coin which is going to be two and amount two plus one five rupee coin which is going to give you two again so minimum of all this is gonna be two so i'm gonna update to here moving on to a coin eight or amount eight we can form by adding amount seven plus one rupee coin that is gonna be 3 and amount 6 plus 2 rupee coin that is going to be 3 again and amount 3 plus 5 rupee coin so it's going to be 2 plus 1 3 again so all of the same value we are going to update 3 here going on to our amount 9 adding 8 the value at 8 plus 1 is going to be 4 the value at 7 plus coin 2 that is going to be 2 plus 1 3 and the value at 4 plus 5 is going to be 9 so value at 4 is 2 plus 1 5 rupee coin is 3 so updating the minimum of all 3 is going to be 3 here moving on to our 10 so now 10 can be formed by adding 1 rupee to the place at value at position 9 so it is going to be 4 coins and while adding value at 8 plus two rupee coin that is three plus one two rupee coin is going to be four again and value at five plus one five rupee coin so value needed to calculate five was one and we are going to add one more five rupee coin so total coins are two so far the minimum value needed to form amount 10 is going to be two coins that is five plus five so finally we arrived at the last cell which is going to be giving our output to form 11 rupees or amount 11 we are going to calculate amount 10 so far the minimum points required to form amount 10 was 2 along with that i'm gonna add one rupee coin so which is gonna be making three coins to reach 11 also amount nine had three minimum coins so plus that i'm gonna add one two rupee coins so i'm gonna get four and finally coins at position six with that i'm gonna add one five rupee coin so far to make amount six it was two coins plus i'm gonna add one five rupee coin a total of three coins so out of these three is going to be the minimum values i'm updating three in this box which is going to be our solution so yes using dp logically we arrived at a solution in linear time so let's go to the code now so let's start declaring our dp array of size amount plus one so now let's fill our array with maximum value and i'm gonna start filling my first index 0 with value 0 because we know to form amount 0 there are zero points needed so now i'm going to iterate my array from index 1 because we already filled the value of index 0 and inside my loop that is for every amount i am going to consider every denominated coins given so for every coin i'm checking whether the coin is less than or equal to the amount because if the coin is 2 rupee coin and we have to form the amount one it is not possible so i'm checking for every amount is less than or equal to the coin value and ep of i minus c is already filled if we fill the value it won't be holding the maximum value if that is the case then i'm gonna fill so yes by considering the minimum value of that place already with adding the previous value with the amount it will calculate an arrival solution at the last index so we are checking if our last index is not filled then it is not possible to arrive at the solution with the given denominated coin so we are returning minus 1 if not return the value at the last index of the array so yes let's run let's submit so yes the solution is accepted and then runs in 30 13 milliseconds so thanks for watching the video if you like the video hit like and subscribe thank you
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
1,099 |
hey everybody this is Larry this is me doing week one of the Le Cod daily challenge or weekly challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this prom it's a premium prom let's play around with it $199 two sums two sum less than with it $199 two sums two sum less than with it $199 two sums two sum less than K giv away numbers of integ and inte K return the maximum sum such that there exists I less than J uh okay so two numbers that add to each other where it is less than K strictly okay so I mean obviously you can do this in N square and you know you'll be you could do it would just be very sad I mean uh I mean it'll be very easy for sure and during a contest that's what I would be doing but of course even if you're not doing contest or if you're not doing contest and you're at least if you're interviewing or anything really um you want to do a little bit better and what can you do well um one quick thing that you can do is um I mean there two things you can do one is um sort and then just scan right if you do a sort then you can kind of do a um a binary search on the uh the number that you know if you have num sub I and num sub J and you have uh stored up all the num sub J so when you get to or when you store about the nums of eyes so when you get to J's you can do a binary search uh on the biggest number that's smaller than Su minus num sub J right so that's what you can do um another thing that you can do without the Sorting is of course also using a binary search tree um you can do that as well um yeah that's Al both of those should be and L again um another thing that you can do of course is noticing that um this is less than a th and if it's less than a thousand and K is less than 2,000 then thousand and K is less than 2,000 then thousand and K is less than 2,000 then you can do effectively not a binary search but a linear scan right so uh you know you can scan down from um yeah and for each of those number because you only need to scan at most um say well it's not possible but yeah um you can scan at most a th elets it's going to be 100 times a th000 but of course that is actually slower than n Square in this particular case so I would not recommend that um and also I think I said you could search and then uh you can um I said that you could sort and then do a binary search on each query but of course you can also just do a two- pointer this thing because as a two- pointer this thing because as a two- pointer this thing because as num ofi gets bigger num sub J will get smaller and so forth uh yeah all these things are things you can do uh so definitely play around with all those techniques and all those ideas there are a bunch of them as you know um yeah uh I don't know which one I'm going to do which one do I want to do okay let's just do the binary search tree one because I think it's a little bit different from previous before so uh what am I don't know what sort of this what is that from again oh man I am bling out it's that collection it's sorted collection or something H sorted containers huh man I'm just Bing out today I sorted this right and then now basically what you want to do is for X in nums um you search basically you know that some X Plus Y is less than K right and you have X right now so you're searching for y so you minus X on both sides so then you're searching for K minus X um you're trying to find the biggest number that is less than uh K minus X so then you have now a sorted list right which contains all these uh x uh all these y's this becomes y in the future right um so then now the search would Beal to um the bisect left of k- X and this will um the bisect left of k- X and this will um the bisect left of k- X and this will be the index uh and of course you want this is the number that is k- x equal to this is the number that is k- x equal to this is the number that is k- x equal to or bigger so you want the one index that's smaller so if index one is greater than or equal to zero then um then yeah and SL index minus one is going to be your number but you actually want to know the maximum sum right so best isal to Max of best this number plus X and then that's it give a quick submit uh roughly speaking I mean if you want to be pretend and you know s l I'm not going to go over it but let's pretend that BC left is loog in then this is going to be un log in for obvious reasons uh that's all and all end space of course roughly speaking uh that's all I have for this one let me know what you think uh yeah stay good stay healthy to go mental health I'll see you later and take care bye-bye
|
Two Sum Less Than K
|
path-with-maximum-minimum-value
|
Given an array `nums` of integers and integer `k`, return the maximum `sum` such that there exists `i < j` with `nums[i] + nums[j] = sum` and `sum < k`. If no `i`, `j` exist satisfying this equation, return `-1`.
**Example 1:**
**Input:** nums = \[34,23,1,24,75,33,54,8\], k = 60
**Output:** 58
**Explanation:** We can use 34 and 24 to sum 58 which is less than 60.
**Example 2:**
**Input:** nums = \[10,20,30\], k = 15
**Output:** -1
**Explanation:** In this case it is not possible to get a pair sum less that 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 1000`
* `1 <= k <= 2000`
|
What if we sort each cell of the matrix by the value? Don't include small values in your path if you can only include large values. Let's keep adding a possible cell to use in the path incrementally with decreasing values. If the start and end cells are connected then we don't need to add more cells. Use union-find data structure to check connectivity and return as answer the value of the given cell that makes start and end cells connected.
|
Array,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
|
Medium
|
1753
|
106 |
Hello gas my name is Geetanjali and today we are going to discuss daily problem of net so let's see what is today's problem Construct binary tree from in order and post order reverse so the question is what is given to us in order and post order reversal Will be any binary tree and we have to construct the binary tree and return its root note so basically in order and post order reversal if there is life then how can we create binary tree we see that approach then see the sample test So we have been given zeros of sample test in which we have been given a post order reversal of a tree and we have to construct a binary tree from it, so basically first of all what is the post order reversal of any tree, we start traversing and First of all, we have left node i, given right node i, given root node i, so we know that if there is any post order reversal, then the last note in it will always be the root node, so in this way we have post order reversal. There is life and the last mode in it is three, so we came to know that our root node is three of the life tree, so we came to know about the root note, but now we have to construct its left sub tree and right sub tree. If we take help, then all the notes to the left of three will come in its left subtree and all the notes to the right of the root will be on its rights, so in order reversal, here we have 3520 and seven 300. Now as root notes. Which notes will come in the left sub tree, which will be on its left? In this case, if there is only 9, then nine will come on its left and which notes will come on its right, 15, 20 and 17 because in this order reversal, these will be on the right side of the three. So we have a basic tree in which three is the root node and on the left we know that there is nine and on the right we know that these are three notes, but now how in this, which node will come here that three? Which one is just to the right, then it will be one of these three and to find out which one it will be, we will check the post order, so in the post order, I know that the right most note was three, now it is on the left. I will check which is the first note A. While reversing left, out of these three, 1520 and out of seven, I have the first note 20 A. If I am going from right to left, after three, then the first Because I have 20 A, then I will have 20 just to the right of three and after that again, now I have to check that the children behind are 15 and 7, so what will come to the right of 20 and what will come to the left? Again I have placed my order in Checked the reversal. While checking the order reversal, I checked that here is a 20 note and 15 is on the left of 20 and 720 is on the right, so that means I came to know that 15 will come on the left of 20 and 7 will come on the right and because If there is a single node then there is no need for us to look again so we have our required binary tree constructed. Now this was the logical approach that how can we draw binary on 10 papers. Now how can we code it. If we do this, then in order to code, we will have to understand it a little from the point of view of the code, so what can we do for that. Now I noticed that when I was looking at the theoretical, I had to check the indexes in this order again and again. I was wondering where my life node is present in this order, so what I did was, first of all, I stored my in order in this map, at which index is the ninth note and which is the third note? The 15th note is coming on the index. Which index is the note coming on? Give it like this, after that I will now take two pointers, one for the painter, one point for the left painter and one point for the right painter because in the map I have already stored the indices in this order. So I have taken the pointers obviously for post order and I have created a global mercurial index which will always point to the right because I always have to check from the right and not which one is the first one so that I can just find the right note. So, this is how my index is just pointing to the last note and is pointing to the left point and the first note, so now tomorrow I will do the function from my record, from the record to the function first. What will happen to me in this order? What is the position of the root note which is pointing to the index? Index G is also pointing to the note. I will find its position in this order traversal. So I did three in the map. When I found the position, it came to me. One, then the position came to me. Now I know that whatever notes are on the left of this position will come in the left sub tree of three and whatever notes are on the right of this position will come in If the rights of three will come in the sabri, then basically we have that the three keys of Sir Sean are in the position one with me, so all the indexes which are smaller than one will come in the left sub tree and all the indexes which are bigger than one will come in the right sub tree. If we come to the tree, I have called function A from a record, on the left of that there will be tomorrow, on the left there will be a function for you, tomorrow again, so this way we have function A from record, now we want to see the code of this, so basically this is We have the code, so what's in the code? First of all, I created global variables index and map because I know that I need both the variables from my record in the function and in the function I also need the function in this is my beltry so what I did in it. I store the values in the index of the last store the values in the index of the last store the values in the index of the last index i.e. the size of these orders minus index i.e. the size of these orders minus index i.e. the size of these orders minus one and now I have stored all the values of these orders in the map, one and now I have stored all the values of these orders in the map, one and now I have stored all the values of these orders in the map, meaning which value is on which index, I have stored it in my map, which is named MP. And now I did it yesterday in starting the function from the record, what is my start index zero and what is the index size -1 size of post order means its is the index size -1 size of post order means its is the index size -1 size of post order means its minus one now here is my function how will the base of the function come till my left painter right Till then the function calls will be made, but as soon as my left becomes bigger than the right, that means there is no one present there, my index is also pointing to the note, where is it in this order, then that position will be stored in my store. Presently which note is the index pointing to, so for that I created a new note with the help of new keyword and stored the value of 'Hogi present' which and stored the value of 'Hogi present' which note is the index pointing to in the post order. That became my store in the current, now to write the current, I had to do the function again yesterday in which I passed the values from meddplus one and did the right because I know that whatever position of these orders came, it would be made mist and hoagie and made. All the notes on the right side will go to the right subtree, so I added the right side of Mad plus one to the right and for the left side, I added all the notes smaller than Mad from left to Mad minus one. All will come in left sabri and finally I returned my current now let's run this code and see ok guys thank you this is also
|
Construct Binary Tree from Inorder and Postorder Traversal
|
construct-binary-tree-from-inorder-and-postorder-traversal
|
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** inorder = \[-1\], postorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= inorder.length <= 3000`
* `postorder.length == inorder.length`
* `-3000 <= inorder[i], postorder[i] <= 3000`
* `inorder` and `postorder` consist of **unique** values.
* Each value of `postorder` also appears in `inorder`.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
* `postorder` is **guaranteed** to be the postorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
105
|
223 |
hi so today we are doing 223 rectangular problem statement is pretty simple all we got to do is calculate the area of two overlapping rectangles they might be overlapping might be not but we have to calculate their combined area so for example this rectangle and this rectangle have to be calculated and then you subtract the area of the rect of the rectangle that is overlapping between the two and then you get the combined area and that's your solution very simple stuff and also pretty simple solution but first let's look at the first solution which is presented by Big D O T as you can see it works but it looks like this so the calculation for the first area and the second area are pretty simple you basically just subtract the um so here for example ax2 you subtract it from ax1 and then that's uh your length and your height will be done the same way so a Y2 minus a y1 and that's your height you multiply those two get area one for area two you do the same thing but for B values um OT Mr OT decided to change the variables to a b c d which made it even more complicated since now you don't even know what variable blocks which but whatever we're going with a solution for now problem is with calculating the third area which is the area of the small rectangle overlapping here so if you don't want to do it easily you can do it this way which is basically you check each and every case so if area one is not is equal to zero eternity two area two zero area one so on and so forth and if all the areas are the same if all the values are the same like between uh drag one and triangle two you're returning one if all the variable values are different then there's no overlapping if the return area wants this area too and it gets even more complicated but as you can see this is not the right way to go about it I mean that's 70 lines of code when it could be solved in one line This Is by MD 2030 it's pretty simple you calculate everyone the same way area two the same way but for area three you'll get the minimum between the right side so here the minimum between ax2 and bx2 is bx2 obviously is sorry it's ax soup since axu is three here and bx2 is nine then you subtract it from the maximum between ax1 and bx1 and you do the same thing for the Y's for the Y values and that's your third area then you all you got to do is return this first area which is the second area subtracted from the zero there you can even make it smaller um the number of lines of code I mean oh sorry not that by just doing it this way and it's the same value so it's less clear on what's Happening I like to use variables so whatever and that's your answer that's all bye
|
Rectangle Area
|
rectangle-area
|
Given the coordinates of two **rectilinear** rectangles in a 2D plane, return _the total area covered by the two rectangles_.
The first rectangle is defined by its **bottom-left** corner `(ax1, ay1)` and its **top-right** corner `(ax2, ay2)`.
The second rectangle is defined by its **bottom-left** corner `(bx1, by1)` and its **top-right** corner `(bx2, by2)`.
**Example 1:**
**Input:** ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
**Output:** 45
**Example 2:**
**Input:** ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
**Output:** 16
**Constraints:**
* `-104 <= ax1 <= ax2 <= 104`
* `-104 <= ay1 <= ay2 <= 104`
* `-104 <= bx1 <= bx2 <= 104`
* `-104 <= by1 <= by2 <= 104`
| null |
Math,Geometry
|
Medium
|
866
|
1,046 |
is the weight of the eighth stone and you are here playing a game with the stones here and on each turn we choose the two highest Stones heaviest stones and smash them together so that smashing condition for this we have is the two highest weighted Stones we will have so net X of the less than or equal to Y in that case if x is equal to then we destroy both the stones otherwise if they're not people like means if x is less than or equal to y didn't want to do it excellent and Y will be set to Y minus X so at the end of the again there is at most one stone left or at most one stone left means it can be either zero or one and written the weight of the last remaining store if there is no Stones left then return zero as I said at most one stone will be in the left if that one stone is left then they return the value rate of the ones to otherwise if no stores so given this example I'll explain this clearly what they have told so if you look into this example so we have one two three four five six stones right in this the heaviest stones are which one seven and eight the other the heaviest Stones present now so we know that 7 and 8 are not equal hence what do we need to do they are not equal X is destroyed so 7 will be destroyed X Y which will be actually 700 base because X is less than or equal to Y I have given the condition so x 7 is destroyed and y will be y minus X that is 8 minus 7 that is 1 so 1 will get converted the array and we add it so now here total at bus 6 now it contains five elements so 7 and 8 are replaced by one with logical if you think so then we combine we look for other highest two stones here that is two and four so again two and fourth not equal so you do 4 minus 2 that is two so two is added and remaining foreign and after this all you could see okay stones are two and one so again they are not equal so you do 2 minus 1 that is one so these two get replaced by one so one that's one and the remaining one are present over here in this if you see one is the only highest thing so one they are refers to both or get this right so you left it only one and this one we have at least one value at the end right so you written that value itself so in what case there will be like returning zero case so let's say take the example of one two three four so one two three and four so in this case here this is array and we start with the three and to the highest and subtract that will give you one so next will be one comma two comma one and again in this highest work two and one so the difference will be one only because they are not again this could destroyed because they are equal so you get zero so we return 0 in this case because both get destroyed press it so written zero so that's okay now how to solve the problem as a tool let's take an example like let's say one two three or let me just say four two one five and three okay so it's better how do we get the two highest sweater Stones if you sort the array the last two elements is the highest targeted strong so you first saw that one two three four and five so once you sort the array now all we need to do is so I'll just return that sorted array here directly one two three four for any array maybe once you do Aristotle sort of that array that will be resolved so these two are the highest zones so we will Define two variables highest and second highest I so highest will be nothing but this array is nothing but Stones no so stones of if n is the length then this is length highest will be stones of n minus 1 and second highest will be stones of n minus two since it's a length uh the last element will be zero Index right so lastly would be n minus one and the previous element will be n minus two so here n minus 1 is 5 and N minus 2 is 4. so now we check whether these two are equal or not so that you have to give the if condition if highest equal to second highest if that is the case then this both should get installed so once you get destroyed with setting but n equal to n minus you have to do so that both will get destroyed and yeah that's it so if they're not equal then what should be the case here in this case they are not equal so they are not equal what you have to do is um the second highest or whatever you have second is equal to S uh okay we said okay not secondized so if these both are not equal practical what we're doing we are destroying the one of the element I mean we have to destroy this and this should be 5 minus 4 1. but it will result in Array one comma two comma three comma one right so practically what you are doing is logical if you think so this we get distorted that is n minus value and this will be nothing but 5 minus 4 so s of n minus 2 this position will be 5 minus 4 that is second highest minus highest cut it and this get Disturbed how to get destroyed this U to n minus instead of n equal to n minus 2 because one element another will be destroying so u n minus so basically the logic is actually what they said is you have to destroy this and this value should be nothing but her second highest minus second highest so that is nothing but uh so 5 minus 1 that should be one but if you think so when we sort the array it should be like this now so last image how to retain that is pseudo n minus you destroy this and this is nothing but 5 minus 4 for this Square 0 that is s of n minus second highest now you have these are the conditions which we require to solve the problem yeah highest minus second highest yeah that's it so after this you have is equal to X second S and S of n minus 2. so once you do everything let's check for all the cases so initially Phi and four you have is there equal no they are not equal so s of n minus 2 will be highest second I so this will be one so you get one here and every time in the loop you have to do erase all sort and we will have while condition because n we are only defining for different function we will have so what the condition should be inside this item will tell you for a while and yeah every time you have to solve that once you get this again you sort the array it will be one comma two comma three so now 2.3 at the highest and second so now 2.3 at the highest and second so now 2.3 at the highest and second highest so highest is three and two so they're not equal again s of n minus 2 this will be 3 minus so that is one and let's get this Draw N minus so it will be 1 comma two comma one again next Loop you go so the condition will be n should be greater than 0 here actually um are not greater than zero greater than one why I'll tell you see now again you do a restaurant sort so that is with one comma two so you will have uh one comma one three ones because this is one comma one in this case these two they are equal this time so we will do n equal to n minus 2 that is both will get this one by this time we have only one element they said at most time if they don't have any other element to restore compare it to hence you written one in this case uh written one because the weight is one of this number so you just written s of n minus 1. if n is equal to 1 that is length is equal to negative written s of n minus 1 what if the layer where else part that is length is zero they said at most one so if the length is 0 then we return 0. so for that case if I take one two three and four see these two LT so four and three are they equal no so you do 4 minuses that is one so one two one it will only Shuffle it one two it will be again these two are not equal I get 2 minus 1 it will be so these two are equal so this can be stored and array will be zero so in this case you return 0 here if n is equal to 1 then you written s of n minus 1 that is only one element which is present fine so okay now we will code this off so int n equal to Stones dot length Stone start length next to give the while condition wide and greater than 1 so in highest first will declare highest equal to stones of n minus 1 then in second highest equal to stones of n minus 2. now check if second highest is equal to highest then n equal to n minus 2. otherwise stones of n minus 2 will be equal to highest minus second highest and N minus V2 in this case because stones of n 1 is to be written so and every time you have to sort the array so arrays dot sort of stones at last you have to check if n equal to 1. then you return stones of zero first element only one element will present else written 0. yeah successfully submitted if you have any doubts please drop it in the comment section we'll come up with another video in the next question and please subscribe to the channel and keep learning and like the video thank you
|
Last Stone Weight
|
max-consecutive-ones-iii
|
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000`
|
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
|
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
340,424,485,487,2134
|
78 |
what's up guys this is the polyglot programmer and i'm here to do one other problem uh i th this program has different names uh different places like on the platform ago expert it's called power sets uh this in here is called subsets but it's basically uh the same thing so uh let's go so uh basically given uh a distinct uh list of distinct set of distinct integers uh um nums uh return all possible subsets so basically he wants a power set a parasite is the all possible subsets uh in of the list and uh a set is a list of non-repeating uh a set is a list of non-repeating uh a set is a list of non-repeating items so it's kind of redundant this thing it doesn't need to say these things if you said given a set of integers is already unimplicit but all right uh so there number ways to do this some people prefer the request recursive solutions to be completely honest i don't i think the iterative solution is a way better and simpler and easier to code also to be honest and the way the iterative solution is that you gotta imagine uh like for example if you have a an empty array i'll be the power set of this would be this right uh if you have an array of one what would be the power set of this would be an empty and this and if you had a list of two what would be the power set of this would be this then it would be this then would be this so do you see what i'm doing here so like for the this one is more visible so we can start our subset that we're going to return with empty list and then for each item in our original list we just iterate over whatever was in our subset list and append the current item to it and then append that to the current list and then we keep doing that until we reach uh the end and that works so if we want to code this you will see that is that it is uh super easy so like subsets uh here we define oh okay define this here and then uh for num and nums right uh we iterate over for i in range in my subsets uh right so here we're iterating over all the subsets for each number that we have in our list and in here it's easy so we just create just get we just basically create a copy of whatever is there so subset current subset is uh subsets i will just get the one that is the current item i index sorry and then we added uh subsets append uh current subset plus the current number that's it and we return subsets if i didn't make any mistakes this is it so this is what they were expecting same order nice okay oh that's nice last them less than a hundred percent of the online submissions okay faster than 87 so this is a good pretty good uh in terms of uh complex time complexity this will be o of 2 to the power of n yeah times m and for uh space it's uh it's the same thing yeah uh because for every item we are for every item we need to iterate over every other item and to create all the possible subsets so you can see that for three here it's easy to see we have one two three four five six seven eight right so it's more than double so yeah so that's it uh see you next time hit the subscribe button
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
1,318 |
hello friends so today we're gonna discuss this question from leadcore weekly 171 problem number one three one eight minimum lips to make a or b equals to see the question statement is very simple it states that you are given three numbers a b c and you have to return the minimum flips which are required such that a and b the power of a and b is equal to c okay let's see the example to get a more inside on this question as we can see a in the bit representation is equal to this and B equal to this and C equal to this okay if you do an or of a and B what we get is a zero okay because zero and zero R is equal to 0 but as but we haven't but we want on this place and or of a value of one so if we just flip any of them it will become 1 in this case we want a value of zero in the seed but both of them has one as a value so we have to flip both because if any of them remains as one it will again give a value of 1 as I hope you know bit or how to do bit or okay so what the main basic function are there are four cases let me take you if both are 0 both of the bits of a and B are 0 then the answer will be 0 and if you want and we want upon in that case what we can do we can change any one of them to 1 and then I when we do 0 with one or the answer will be 1 so in this case we just want to make any of that number equal to 1 if any of one of those number is 1 and other is 0 the bit or is equal to but if RC has you we have to make this number equal to zero says that now the or of these two bits equal to zero so again one more operation is required in the same case we have to make this little so one flip is required but in this case if both of them are 1 and we want to 0 we have to make both of them equal to 0 so in this case two flips are required so we just have to check in both a and B at a given position at a given bit position which of these four conditions satisfied and then we have to just come the bits where the number of flips required I've just written down this code I move from a 2 0 to 32 bits and I stood XYZ as the position of that bit from the I equation from the left and as we can see if I also told you all the four cases and I've also written in the comments how we are taking all those four cases in this case only we are taking plus two total plus two and all other cases we are just adding total plus and then after it will just return out the output as we can see if Z equal to zero said we are depicting is see I think I'll just tell you one case like in this case a and B has it right with equal to 0 so if a and B would has that I had it equal to 0 and C is not equal to 0 as you can see in this case C is not equal 0 and both a and B are equal 0 so just we have to making fun of those equal to 1 and our case is solved so one flip is it worth so 2 plus if a and B of the add this is not to zero both of them are not equal to 0 and C is equal to and the I admit of C is equal to 0 so we have we required two flips and same for these two cases that's it we just increment a total whenever be encountered any case and then we return the final output I hope you understand the logic thank you for watching and I'll see you in the next one
|
Minimum Flips to Make a OR b Equal to c
|
tournament-winners
|
Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation).
Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
**Example 1:**
**Input:** a = 2, b = 6, c = 5
**Output:** 3
**Explanation:** After flips a = 1 , b = 4 , c = 5 such that (`a` OR `b` == `c`)
**Example 2:**
**Input:** a = 4, b = 2, c = 7
**Output:** 1
**Example 3:**
**Input:** a = 1, b = 2, c = 3
**Output:** 0
**Constraints:**
* `1 <= a <= 10^9`
* `1 <= b <= 10^9`
* `1 <= c <= 10^9`
| null |
Database
|
Hard
| null |
1,838 |
so hi everyone uh in this problem we have to find the frequency of most frequent element so let's say we have uh something like 1 2 4 8 uh and 13 and you can uh only increment any element by uh at most the amount K right so K is some given value some given amount by which you can uh increase an element so you can take any amount count from K and by using that you can increment any of the element in the ideal case when you are lucky and K is very big enough so K is almost approaching to Infinity in that case you will you would like to have every element uh equal to some single value right you can't increase 13 because uh 13 is the biggest number in my array and if I increase 13 uh I have no benefit uh because I can I want to increase an element so that it can match some existing element so I can increase it to match 13 so I can increase 8 by 5 units so that it will become equal to 13 I can increase 4 by 9 unit so that it can become equal to uh 13 I can increase uh 2 by um 11 uh if I add 11 that will become 13 and in one if I add 12 that will 13 right so this 12 this 11 this 9 this 5 I'm getting from the K so if K is big enough I'll uh increase every uh element except the uh largest element except the largest one right but uh we are not always lucky and we don't have K as infinite always right it may happen that uh the gap between last element so let's say we have element a instead of these uh certain elements let's say we have element a element B element c d and e in my array and I'm keeping them in a sorted order so you can assume that a is less than b c is B is less than C and C is less than D and D is less than e so it may happen that um the gap between e and D is very large the difference between e and uh D is very large but the gap between C and D is not that much and same with of b and a right so the amount that uh we require to convert C to D so the amount that we require uh to convert C to D is not uh as large the amount we required to convert D2 e so we will not run out of the given Kota of K right so it is uh we can uh with the with a very small amount I can convert C to D and B to e and in that it may happen that K is just equal to this Gap and we can only convert D to e but can't convert C to e and B to e right so we never know which element uh we should pick and convert rest of the elements equal to that element right but one thing is sure one what one thing we are sure that we have to pick one element from the given uh array and make uh or I should say try to make other elements and of course those other elements are smaller than this element try to make other elements equal to this pigged element through increment operation and we have a limit on increment we can't increment as much as we want so we can increment uh so pick throw increment within some quota within some quota and that is equal to K so we can spend only K amount of um value uh to make other elements equal to the given element so what we can do uh first of all uh to make sure that uh all the element which are less than the given element are on the one side of my array so if I pick uh in my given array if I pick any interm element at index I to make sure that all the elements which are less than this element are on the um left of it that is here and not on the right of it to make sure that we should show we should sort our array right so the very first uh step is to um sort the given array to have the Lesser elements on the uh right side of every element so this is step one of our um procedure to solve this problem now once I got a um once I got a sorted array let's say it is a b c d e and f so I'll start from the rightmost element and I'll pick f I'll pick F I'll try to convert e to F and I can choose the amount from the given K so let's take an example so let's say I have 1 2 3 4 5 and 6 and let's say given Kota is of um five right so what I'll do let's say given Cod is uh of three units so what I can do I'll pick six and on picking six I'll try to convert five to six so I'll need one amount of uh value so I'll just decrease one from here and I'll get two and since I converted to six I spend I spent one amount again to convert this to six I need two amount so to convert this I spend all of these two amount so I got the maximum frequency equal to three right and again if instead of a six uh I'll this time I'll I will not go for six I'll pick five and try to convert all the small lesser elements to five so to convert four to five I need amount one so again if I spend one I left with two and 3 to five I need two so I spend this again I got three uh as the as my maximum so in this case uh we'll definitely we'll only get maximum window equal to maximum frequency equal to three but it may happen for that uh the elements which are very close to each other um they'll give me some uh large number of frequen very high frequency but the element which are very far away they'll give me uh some high frequency it will give me some very less frequency right we can't convert uh large number into the given element which are very far away so if this is how we want to proceed then how whatever uh algorithm look like first of all you will if you think of Brute Force you will start from I equal to n minus1 so this is my given array nums I start from IAL nus1 and I'll go till uh I = to0 so whenever I at index till uh I = to0 so whenever I at index till uh I = to0 so whenever I at index I when I at index I so in my array when I at index I will uh Traverse from right to left from I till zero for each I'll do that I'll Trav from I to zero and one by one I'll pick each element and try to make it equal to nums of I so whatever value I'm having at I'll try to one by one match each value uh equal to that of I by keeping in mind that I have the limited quota of K so using that quota I will try to convert I when I run out of K when K becomes zero or less than zero I'll stop and count and I will count how many uh how many elements I have converted into I so that will be my answer to uh that particular element I do that for every single um element in my array from right to left and what will be the time complexity for that uh end times we are traversing for each element and in the worst case uh around in the in first time I will I'll Traverse n minus one elements then n-2 Traverse n minus one elements then n-2 Traverse n minus one elements then n-2 then n minus 3 so on to u n minus U so basically for I index I'm getting I'll Travers for n minus I element so on upper bound it will be of B of n sare time complexity right but if you look at the constraints uh if you look at the constraint we have uh the length of our AR is 10 to^ 5 so uh the length of our AR is 10 to^ 5 so uh the length of our AR is 10 to^ 5 so 10^ 5 uh this gives us uh gives us a 10^ 5 uh this gives us uh gives us a 10^ 5 uh this gives us uh gives us a signal that we can't use B of n Square time complexity 10^ 5 means we are time complexity 10^ 5 means we are time complexity 10^ 5 means we are allowed to use n log and time complexity right so okay this n we can use for iterating for the um element which we take to convert rest the elements into that and to search for the um Elements which are which we want to make it equal to that uh fixed element that we have that we should do in Logan time right that we uh should do in log uh log and time and since the array is sorted and the time complexities uh want us to uh use the Logan op so there is a high signal that you should we should use binary search so we have to use binary search to do that but how to use binary search to find out uh the number of elements which I can convert uh so that it become equal to NS of I so if you look we have some element here a b c d e f g h i let's say so what I'm doing uh let's say uh I have fixed this element I and I want to uh convert as many as ele as many as I can as many elements as I can into this I right so first of all I'll try to convert H to I if I'm succeed if I succeed I'll go for HG if I succeed G to convert to I then I go for f if I succeed again then I'll go for e but if I fail at e I'll stop because there's no point of going the elements which are less than D because they will definitely uh can't be converted into I because they are even smaller we'll require more amount of K to convert them into I so if I fail at e then this means I have uh coverage till F and this is the size of window I'm getting so I'm we are spreading a window right we are spreading a spreading we are spreading a window in uh left side right so fixing I'll try to spread a window as far as I can if I'm lucky I will be able to convert every element equal to I and my window will be something like this I have converted every single element into I and the window size will be equal to the size of the array but if I'm not that lucky I am somewhat less lucky I may get uh I make uh convert element till b equal to I so window size will be n minus one if I'm even less lucky I may able to convert only these much elements equal to I so on uh if I'm not at all Lucky then I will not be able to uh convert any element and I'm still at the same place I so in that case windows I will only one so in the worst case uh I can have window size equal to one and in the uh in the best case I can have window size equal to the size of my array this is given n and how to find the optimal window for each element so we have to uh look for uh window for I then we have to look for window H window for G so first of all I'll do this for uh in element I and SE for the best window I can go for then I'll start for h i look for best window for H and for all the optimal windows for each element whichever is the maximum in size that will be my answer because the window size is nothing but how many elements you have converted into uh the given element so the most frequent U answer will be the maximum of all of them and one thing is that uh let's say I am uh able to transform uh these uh elements these elements uh these much elements uh into I so what is the desired sum is that I want to convert H into i g into I F into i and e into I when e is converted into i f is convered what be the desired sum will become whatever is the size of window times this value I right this value I and what is the actual sum is e+ f+ G + h i actual sum is actual sum e+ f+ G + h i actual sum is actual sum e+ f+ G + h i actual sum is e + f + G + hi I so we want to is e + f + G + hi I so we want to is e + f + G + hi I so we want to increment uh this actual sum so that this window size will become equal to this much window size time I and I can only contribute k amount to this window right so what I need uh take a window and add K to it so if sum of window plus K if sum plus K so if I'm adding K to the sum of current window and that sum uh is greater than equal to desired sum then that means that window is visible that window is possible so let's if I uh go for this window B C D E and F G H and I if I sum these values and add and if I add K that is not equal to window size times I or that is u not uh greater than the desired sum so our desired sum should be less than what we are getting from some plus K right if our desired sum is less than whatever we are getting from uh some plus k then that window is visible and in that case we'll try to look for more bigger window right so we don't have to iterate every single element I just want to find one starting point uh for that window ending point is fixed in each iteration this is my ending point and I have to look for a starting point and to get the sum of the window I can use the prefix Su technique so I can prepare a prefix Su array I can pre prare a prefix some areay and prefix samary can help me finding the window size or window of any size in B of one time so I can find V windows in vgo one time and I can look for this uh look for the starting point by using binary search so this starting point will become my U midpoint of uh so this start initially I start with low equal to zero and high equal to this uh last element from which we are spreading the window that will become a high point and I look for the midpoint so from mid to high I have the window so I have a low index here I have the high here and I have a mid index here so our window size is from mid to high right if this window side is feasible I try to look for more bigger window in that case I will do I will update High to Mid minus one right but if that window size is not visible I'll reduce the size of window in that case I'll just update low with uh mid + case I'll just update low with uh mid + case I'll just update low with uh mid + one so these operation will take log Logan time in worst case and we'll do this for uh every single element of my array so for n elements we are doing this uh search of window and window SE time is login time so overall time complexity will be B of and login right so if we uh let's try to code it first of all the step number one sort the array so I have sorted it now by sorting uh we have made sure that for each element the less the Lesser elements are present in the uh left of it right of it left of it right so on once I uh sorted it and now I need to prepare the prefix sum which will be able to compute uh the sum of my window in big of one operation in B of one time so first of all I should uh get the size of my nums in equal to nums St size now let's prepare a um prefix some array which is again of size n and let's initialize it with zero and since we are summing the elements in prefix sum So to avoid the Overflow I'm taking the type to long so we know how to prepare the prefix sum nums Z will uh become my sum at preum zero then I'll go for rest of the index is i1 I less than n i ++ pre ++ pre ++ pre sum I will be equal to nums of I + three of + three of + three of sum IUS one so after that I got my prefix sum now I have to search for the optimal window size for every single element starting from I = starting from I = starting from I = to uh n minus1 till I equal to Z right so let's do it for in I = to n for in I = to n for in I = to n minus1 and till I is greater than equal to0 I just decrement I so my this I is nothing but ending index of my uh window so I is ending window of window and I will uh store the answer in this variable initially I'll kept it zero and I'll keep on looking for optical window size for each nums of I and I will store the maximum minute maximum Windows an answer so I'll get maximum of whatever the window SI I have answer till now and I declare a uh separate function which is get uh when uh get Max window size right get Max window size so that get Max window s will uh accept this I index as parameter it will take this preum uh vector and it will take this nums to get the value at that ending index and it will also take the amount which we can spend that is our Kota that is K and this will give me the maximum window size corresponding to nums of I and I keep on finding this window SI for each element and maximum one will be my answer and in the end I can just return answer right so let's do it the only thing we are left with is uh code this function of uh get Max wi size so this uh first of all this int I is nothing but uh end index and idx right and we have the vector of prefix sum let's call it by reference that we don't prepare a copy and we have original array Vector then our qua that is K now initially uh my low value will be zero and high will be equal to the ending index so I just put end idx to equal to high and we want to find the start index which is of course uh the mid uh mid value mid Val uh which is of course a mid idx between low and high right we want to find and we will store that uh starting index that we can use uh later to return the answer so when while low is less than equal to high what you will do first of all I'll find the mid Index right so let's say mid idx is equal to why let's say it is only equal to low plus High by two this is my mid index now what is the D desired sum right but first of all what is the window size so window size is from mid till uh ending index so it will be end idx minus mid index + one that will be idx minus mid index + one that will be idx minus mid index + one that will be the SO size from index I to J is nothing but Jus I + but Jus I + but Jus I + 1 right so the desired sum will be uh window size times nums of uh the value at uh ending end Index right now the Su we get uh by adding K in this current window so how can I get the uh um sum of this current window for that we'll use this prefix sum right so to get the uh sum from index I to J you just have to do prefix sum J minus of prefix sum IUS one and we have to handle the case when uh I is equal to Z that is starting index is zero so if mid is so first of all let's declare in uh long sum plus K uh sum of this actual sum of this window plus K and if mid is equal Z that is mid is nothing but start of this uh window if mid equal to zero then I don't have to do preum uh of end minus of preum of uh start minus one because we are starting from zero always to add in my prefix sum so sum plus K will be will only be preum of and idx plus the amount of quota we are adding in it K if mid is not equal to zero then Su plus k will be like this sum plus k equal to pre size of sum of this window will be pre of sum and idx minus pre of sum starting index is M which is mid right mid uh minus one so discard the some till mid minus one we accept the sum from uh mid to uh and idx and of course we will add the quod K in it now if this desired sum is less than equal to sum we are actually getting that is sum plus k then we are good to go we further try to increase window size right but before that we'll store we will store this uh starting uh Point start the start of this window in this start variable so I'll store Mid in start and I look for more bigger window for that I just have to update High equal to Mid minus one if that is not so if desired sum is not less than equal to some plusk then we should uh decrease our window size and for that I should update low to mid + mid + mid + one so once we are done with all of these iteration start will have the starting index of most optimal uh window and I can just simply return the size of this window by doing end idx minus of start + one so this will uh do our job it is accepted and we are done
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
245 |
hey so welcome back and this is another leeco problem so this one is called shortest word distance three actually and typically I do daily legal problems which are these ones here but uh for this question it's actually from like the premium weekly questions that you can pick from and so let's take a look at it so I don't want to give you the solution just yet we'll go over it but skip to the ending if you don't want to hear any of this so basically what you're given is a word dictionary but it's not really a dictionary it's just an array of words and you're also given word one and word two and all that you want to do is given these two words you want to find the shortest distance to link them together or the shortest difference distance apart they are and so in this case you can see that there's two words that match the first one makes and then one word coding that matches that word inside this words dictionary and so the shortest path isn't from coding to this makes but it's actually these two here because they're one distance apart and so you'd return one in that case so just quickly show it again so from makes to coding this distance would be considered two in this case since you would have to hop twice but then from makes to this coding you'd only hop once and so you want to return one and then for and this is the catch here is that okay not only can you have multiple instances of each word but you can also have just trying to match makes twice and so in this case there's two instances of makes but then also you have both words that can match and so you can't just say okay the distance is zero you have to say that the distance is one two three in this case to get that so you have to handle this special case but other than that's all the tricks that are in this it's a fairly new problem it doesn't look like it's asked very much but it's asked by LinkedIn and Amazon but let's give it a quick try so all that you have to do is you need to Define two different variables here you have to Define index one and index two and so these will both be preset to negative one and what I want these to be this is kind of a two-pointer solution this is kind of a two-pointer solution this is kind of a two-pointer solution for this problem is that we'll have one pointer pointing to the kind of current latest index of word one and then you have word two and you'll have another pointer called index two that will point to like the next lane or the latest instance of that a word that we've encountered so far and so what we're doing here is we're just going to iterate through this array from left to right and we're going to update these two index variables and so say we're at index zero it doesn't match any of these words so we continue on then we say okay we've now matched with word one here so let's update our index one so that index one is now equal to one here in this case so then we move onwards to the next one which is perfect which doesn't match either of these words and we go to coding and we say okay that matches word two so now it's update our index 2 in this case to equal 0 1 2 3 10 equal index three and then we want to get the minimum or the current distance from those two ones so you just do three minus one so that in distance is two so then we move on we say okay now we encounter makes which it matches our word one so we actually want to update our index one pointer since we have a new latest location for that word one and so then we set that to two here we perform that calculation again so then we do three minus two which is then just one and so you want to take like the minimum of these two different distances which is there for one okay so that's a simple case and once again that explains why we have index one and two and so then if what if we're dealing with cases where we just have makes so for that we just it's a special case where you say okay we're actually we'll still declare this index too but we're never going to use it and so we're going to say okay say we encounter uh makes here so we set index one equal to the index one since that's index location one and then as we're iterating along and then we say okay we just encountered makes again because these two words match we're going to enter a special case where all we do is we subtract the distance from this current one to with index one and so we just say Okay zero one two three four so when we just say Okay 4 minus the last previously seen index of this word which is in the next one we get three okay and so this would then be updated to then okay this is that location 4 here and so say if we find makes you know later on in this array say we found at index like seven we found another instance of makes then we'll just say Okay seven minus four is three right and so you just continue only using index one it might make more sense once we show you the code so let's go ahead and implement this we're going to want to return like the minimum distance which will initially set to Infinity which is you can just do it this way so you don't have to import any Library and this is just because I at first we want to just set it to Infinity so that it gets shrunken down and we know what these constraints we are certain that these two words are going to be in the dictionary so we're never going to return Infinity and then from here we just want to iterate through every word in our words dictionary and we want to get the index as well which in Python you just do numerate which gets us the current word and the current index enumerate words dictionary and then from here we just want to say okay our word is equal to word one we want to handle processing for that case and so we want to say okay if we've seen our previous or other word before so this is handling okay if we've seen word one then we only want to calculate the distance if we've seen word two before and so we know that we've seen it before if it doesn't equal negative one because initially it's preset to negative one but once we see it that will be updated and so then we go in this case and we calculate the new Min distance which will equal to the minimum of itself and this new distance that we're calculating which is the distance between word or the distance between the current index minus index.1 or no sorry minus the index at 2. and this isn't word two we want to say index two there so if we've seen word two before then we would have updated this index we want to minus from the current index because that represents the latest visit to this word one here and we want to minus it by index two because naturally because we just saw index.i we know that because we just saw index.i we know that because we just saw index.i we know that this number will be greater than this number because this number was seen in the past okay and so after that all you want to do is update our index one to the current index because we just this is the last now scene instance of our word one and so we're going to handle this the exact same way but kind of flipped forward to so if this equals word two here then we'll want to check if we've seen word one before we're going to want to update the previous C scene index for this word two at the end of this and then we just want to subtract it from the last scene for index one and so the final case here is that special case of okay what if these word one word two are the same so I like putting at the beginning it's usually where I handle my special cases and so we want to do very similar logic here but the difference is that we'll never actually end up using index two in this case and we're just going to be using index one and we can check this by okay if word if the current word is equal to word one and it's also equal to word two okay that looks good let's try running that accepted and submitted so yeah that's a pretty good solution it's O of n time and we also have o of one space complexity so it's oven because you just Traverse the array itself we only do it one time and so it just kind of grows with the input linearly and then for space complexity it's over one because we don't use any extra data structures here all we're using is simple rays and the array that's passed to us so yeah I hope that helped and good luck with the rest your algorithms thanks for watching
|
Shortest Word Distance III
|
shortest-word-distance-iii
|
Given an array of strings `wordsDict` and two strings that already exist in the array `word1` and `word2`, return _the shortest distance between the occurrence of these two words in the list_.
**Note** that `word1` and `word2` may be the same. It is guaranteed that they represent **two individual words** in the list.
**Example 1:**
**Input:** wordsDict = \["practice", "makes", "perfect", "coding", "makes"\], word1 = "makes", word2 = "coding"
**Output:** 1
**Example 2:**
**Input:** wordsDict = \["practice", "makes", "perfect", "coding", "makes"\], word1 = "makes", word2 = "makes"
**Output:** 3
**Constraints:**
* `1 <= wordsDict.length <= 105`
* `1 <= wordsDict[i].length <= 10`
* `wordsDict[i]` consists of lowercase English letters.
* `word1` and `word2` are in `wordsDict`.
| null |
Array,String
|
Medium
|
243,244
|
133 |
Loot Hello Everyone Welcome to my channel today in this video Marriage Solving Key Problem Clone Graph Very Famous in Interviews Where is the Decade Problem is Famous Indian Learning List Veervikram Google Microsoft Facebook of the Big Companies Are Stay Connected Happy Return of the King of the List of Indian State for Simplicity and Values in State for Simplicity and Values in State for Simplicity and Values in Which is the First Indian to Win The Giver You Must Read Who is the Giver No Danger Reddy Clean 100 Example of Original Notes in the Same 2009 That Graph But Not Mean That Do n't Forget to Subscribe to the Channel Problem Solved Traversal and like subscribe will quote language de node from this is not visited channel david notification will create a copy of this order will go to the name of the floor som will go to the 93 Suv Cars 1994 Will Be Know A For Creating Agency Less Like The Best Way To Also Keep Effigy Don't Mark Animated Notes Will Keep Visiting subscribe our Channel Graph Map With Which Mapping Original Graph Node Of Original Graph With Did Not Know What Will U Will Always create and will make you will not enter subscribe this Video plz subscribe The Channel Other wise quick copy half so ifine maps content no veer is not returned from the story the process of current update the original song play list for no indian loot Is the name of the first of all they need is a gap between the original name to naukri 4G SIM graph wear 1234 ka white is the first will guide you know one will not one to the power fuel and mark also the best mapping from one to the New Wave In To-Do List Will Not Cause Evil Effects To-Do List Will Not Cause Evil Effects To-Do List Will Not Cause Evil Effects From You And Will Be No Two and Four subscribe this Video Too Half Lift Will Get Market * * * * A Man Will Get Two and Have Already Been Created Jism Clock Close Studio Chief Over Year To Governor Not One Morning Processing No One Will Not Basically Choice Today And Forever In To-Do Basically Choice Today And Forever In To-Do Basically Choice Today And Forever In To-Do List Of One This Approach Will Explain The Little Over Implementation Effigy No.is Null Appointed Panel Mist Otherwise will Effigy No.is Null Appointed Panel Mist Otherwise will Effigy No.is Null Appointed Panel Mist Otherwise will not play list a bluetooth no merge side the current mode * wash bluetooth no merge side the current mode * wash bluetooth no merge side the current mode * wash why also give me the map from noida authority will not let you will definitely benefit to know you not well subscribe Video will treat all that you will not Not from which you will do that Awadhi Edition Notes of Vic and Which is Related Call Mode on G Dot Ronit Double Toe Deep Sea Definition of This York States Copyright Law Nil Process Notes of Instead you will create this note content for education a day you will Not Rise After This Will Also Did Not Dare Devils According To The Current Note And Sahi Never Stop This Is Not And Will Be Mode Switch On Which Is The Biggest What We Do Subscribe To Kuch Der Is The Unheard What Is That Swadeshi For shot The Swadeshi For shot The Swadeshi For shot The Point Her Daughter Does Not Get Values Which Contains Point Her Daughter Does Not Get Values Which Contains Point Her Daughter Does Not Get Values Which Contains No Dear Ones You Have To Watch This Year The Meeting Will Do Something Celebs Ko Subscribe And 10 Notes Vansh The Number Of Units And Share Subscribe Like These Quizzes With 300 Bones Butt End Complexity Number of Notes Subscribe
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
1,444 |
Hello everyone welcome to my channel very interesting problems date i uncounted in dp lots of good questions when i will explain to you we will make diagram and tree diagram then you will understand very well we will first solve it brother ok Then let's see if we can memorize it, we will do it, otherwise first we will understand recognition, that is the most important thing, you should understand it first, how to write recognition, name of question, number of send off, cutting n pizza, okay Google and Tiktok have Asked this question, let's understand the question by looking at the input output. So see, you have given pixels in the shop. It's okay. In macros and form, pizza is fine and there is nothing in it and where there is red, it is Apple. It is there, let's assume that it is there, and what does the meaning of 3 mean that it has to be cut into three pieces, that is, there are three people, they want pizza, now there are three sides because all three have not got pizza, okay, so we will divide it into three pieces and cut it. If the pizza is okay, then some rules have been mentioned for cutting it. Okay, first of all, whichever piece you cut and the dog brother the day after tomorrow, it should have at least one cherry in the piece. Okay, you cannot give empty dot pizzas. There should be at least one red cherry in his piece, only then he will be happy, so the first thing is that this is the poor Atlist, either give a grater, you are equal to one, or the other one, you can horizontally cat, the pizza is fine, it is fine, above. Now let the dog part remain below the upper one. If the upper dog is fine then you will have to divide the left one, you will have to give it to someone and on the right one, do further cutting cuttings. Whatever you want to do is fine, then remember that the upper part is horizontal and vertical. We will have to divide the left part, okay, so now I ask you how many such unique ways are there in which you can cut it into 3 pieces, okay, and every piece that every person will get will have at least one of them. There should be an Apple, more than that is a good thing, but there should be at least one Apple, okay, how many such unique faces are there, so the description of the question was very nerve-wracking, but very nerve-wracking, but very nerve-wracking, but now when we make the diagram and understand, it will become very easy, okay? So first let's understand this by making a diagram and this will also give us an approach as to what we have to do. Okay, so let's take this example and understand that my pizza is in this form and this MGN means three cross three. Ka is 2D Oh is and K = 3 means 3 Let's Ka is 2D Oh is and K = 3 means 3 Let's Ka is 2D Oh is and K = 3 means 3 Let's say in PCS So I have made three guys here, why are there three sides now because both of them have not got all three pieces yet, okay let's do one before starting everything I am asking you a very basic question. Okay, I am going a little lower. I am asking a very basic question. You must know that obviously Maa, let's take it. This is a pizza. Okay, it is a pizza, so take anything Maa. Take anything. Okay, take anything Maa. I will tell you. Mom, take the cake, okay, I have to tell you, no brother, it is not to be cut into one piece, does it make any sense? Give the entire cake to someone, if something is cut, it will be cut into two pieces, this is what it means. What happens that if K = cut into two pieces, this is what it means. What happens that if K = cut into two pieces, this is what it means. What happens that if K = 1, then it means that this one piece is a child, then give that one to some person, right, this thing is clear, then how is this base, I told you so that there is no confusion, I told it here itself, let's move ahead. Coming back here, let's look at it, first let's make a diagram. Ok brother, I have two options, one is that brother, you can card it horizontally and the second option is that brother, if you can card it vertically, then horizontal. If you cut then you should have many options whether you have given CAT from here or you have given CAT from here, I am seeing two options, I will give all the options to try, ok then look at the thing now, let's admit that first I did it because of my mother. That I took a bite from here, okay then it's okay, I gave the upper one and why are you giving the upper one because look, there is at least one apple in it, so this guy will be happy, so now I am making this guy happy with the cat. Now I have cut it and made it happy, that is, one monkey is now happy. He got this apple in which there is one apple, at least it is okay, it is very good, there are two monkeys, so here I write k = 2. are two monkeys, so here I write k = 2. are two monkeys, so here I write k = 2. Now I just have to divide this into two bands, this further, this has to be divided into two bands again, okay, so here I will have the option, brother, cut this vertically, before that, okay, we will proceed here too, but before that, look at this thing, I What did I try just now that I could have cut from here, there may be another option, if you can cut from here also then try all the options, what was said in the question, find out all the methods and show how many ways you can do it, so now I would try from here. I am okay, I will try from here. Ha = means I = 2, if I Ha = means I = 2, if I Ha = means I = 2, if I cut horizontally, what will happen? First, I will see that brother, these two slices will go above, okay and will that be left at the bottom? Look, don't divide down now, child. Are these two children? Okay, these are two children. How will you sit? Brother, there is no apple in it. If not, then brother, this will be the wrong way. If I move the cartoon roll number horizontally from here, then I will be able to divide the slices correctly. This cannot be explored in the lesson, so I have made it a race, okay, I have made it a race, pay attention but make that in the diagram when you practice, but I have made a race, okay for now, that means I am further in this. If you have to explore, then one person is happy here, but no, now these two people are children, so it is okay, there are still two options, either horizontal, then vertical card is okay, so let's reduce one, where can we cat horizontal, this is the only one. The option is not visible here, if you cut horizontally, then it will be happy here, then it will be set, it is okay, that means this method has also gone wrong, that is, it cannot explore in the lesson, so I am racing this thing. I am giving OK, this thing has been raised, only vertical can be done, but if I make it horizontal, then I write zero here, if nothing is found from here, then I make it set as no option, it is okay if it is vertical. If it comes to it, then there are two ways, if it is cut vertically, then there are two ways, see how if you give a cat like this or if it is cut from here, then one will go here, sorry, it was something like this, one dot here is okay, the rest will become this. This method is done, I took the cat from here, if it is ok from here, then it will go back here, ok, then it is ok, and what was said in the vertical that brother, the post on the left will be given to you, so I have given the post to the person on the left, because brother, in this Atlist is one apple and the back one also has apples, so there is no need to take tension, it means you are going right, so this is one method, one way has been removed from here, now one more possibility was to cut vertically. There was another possibility of cutting vertically, so look here, if the left one gives the post, then I will give it to the left one, if that guy will be happy, then the second guy and the third guy also have the right thing for the girl. Look, there is an apple in it. So this bill also be happy so one way will be found from here that brother distribution d ok so look from here I got two lessons ok from here to me and yes which is this equal tu tha na two slides in two parts to two people Had to distribute, here only one K = 1 to two people Had to distribute, here only one K = 1 to two people Had to distribute, here only one K = 1 had to be distributed to people, so we returned from here one, from here the answer will come from here, one answer has come. Okay, so if we look at it, from here, we got two answers, two ways, no two. After that, I have extracted the text, look here, I have made a drawing like this, see, this one is done, two parts have come out so that I can easily make these buns in a unique way, look at all the slices of pizza and all the sizes, this is the minimum. One apple is at least, this is how much answer did I get from the left side, two answers came from the left side, that is, two things were found in which I took a horizontal cut, then by making a vertical cut, I got two answers like this is ok and This is fine, now let's come here, now let's come to the vertical one, but in vertical also I have two options, either I will do it from here or I will cut from here, then the diagram will be like this [ diagram will be like this [ diagram will be like this Aa So what did you say in the question? If the one on the left gives it to you, then it is okay. If I give it to the one on the left, then it is okay. First of all, he will be happy. If the first one is happy, then he will give it to the one on the right. Look at the part, there are apples, those on the right are all coming. There are apples in it too, so don't take tension, it means that we have cut it correctly, this vertical cut is correct, okay, and one thing is possible, here it happens, okay, and now look, it happens here also, and this method is done, okay. The one on the right has an apple, but did you notice one thing? The one on the right has only one apple baby and I have two people, so how will you cut it brother, there are two people, both of them want an apple in their respective sizes. But look in the right slice, pay attention, there is only one apple here, it would be wrong, I cannot explore this thing, brother, there is at least one apple in it, then that person will be happy, but for the two people who have children. You will have to check in the right one also, at least two people have had children, there should be at least two apples, or they should be bigger or more than that, then look here, there are two pals here, still see, isn't that thing valid here too? I was saying OK, it is not valid here, so I have given it a cat, no, if I have given it a cat, then I will remove it, I am okay, no answer will come from there, it is unique, I will not be able to distribute it in the correct way, okay, so this is a vertical cat. Gave it to the one on the left, now what, brother, there are two options here too, this kid ISP can also do horizontal cut, but tell me one thing, can you do horizontal cut? But there will be one, right, we can cat it in a way, okay, it is given to the one on the left in the vertical, so I have given this, the other guy also became happy, okay, here and in the last, and this guy's child has become a guy's kid. What has happened is that neither will we give it to him nor will that person be happy where neither I have distributed it uniquely to everyone, that was the one thing I said, okay, so how many texts were received from the right side, just one thing, how many were sent in total, due to which you Total 2+1 pizzas were distributed, this is three way. Remember your answer was also 2+1 pizzas were distributed, this is three way. Remember your answer was also 2+1 pizzas were distributed, this is three way. Remember your answer was also three, so I understood that I will have to make horizontal cut because I will have to try all of them and not just one horizontal cut. Maroon ha = horizontal cut. Maroon ha = horizontal cut. Maroon ha = 1 pe or everywhere tu pe similarly for vertical cut also observe that thing, pay attention to that thing, now see this is what happens, I am making the story in points right now, with what points will I be able to make my story and How will I convert it into code? Okay, so you will have to write a but loop. For whom to do horizontal cut? Let's do horizontal cut. After that, who will look at another one? For vertical cut. Okay, but when you are cutting. So you will have to do another check also, while cutting, you will have to check that not only what is going on the left side, whatever is going on it, there should be at least one apple in it and in each vertical card on the right side, what was there in the left side. The one which is going should have at least one apple or more and the one which is going back on the right side should have at least so many apples so that all the people who have children can get apples of at least that value. If it should be equal, then it should be bigger than that. If the count is fine, then what are the two more things that need to be kept in mind that brother, write the code, the dog that will be Apple, the account of Apple that will be in it should be equal to at least one, give it greater, you should be equal to one. I want it to be okay but the lower slice back in which I have to do further slicing is fine, how much apple should be there in it, as many children as you have, give it greater, equal to as many children as you have, so write here what has been done, what have I done? I write one because at least one person will get it here. Okay, similarly, if I make a vertical cut, here also you will have to pay attention. If you slice this possibility, then look, the reconstruction is going on, is n't it? Further Sabarmari Krishna is going on, so that. So you must have guessed that there is a resection, it is not written that after making a horizontal cut, then I will hit the resection slices. Similarly, when I make a vertical cut, I will hit the resection slides. So keep this thing in mind. If you want to keep it then I have come to know a lot of things from the story points, okay now let's come to the further part, now what do we have to do further, so okay we have understood so many story points, okay now remember one more thing, not the story points, another thing has also been written. Let's say that if we take only the cake and one piece, then what does it mean that we give the whole slice to the guy, there will be a guy sitting, okay, so just see that there should be at least one apple in each slice. Want a garden equal to one, okay mother, I have given you one pizza here, which means that the entire pizza will be given to one person, give it to him, but I have given in the question that whatever happens, the person is getting the pizza at least. There should be at least one apple, so it's okay, so again you should at least keep in mind that the pizza you are giving should have at least one apple in it should be one or multiple, okay, so that's it. Okay, so everything is going simple, look at us, we will definitely write about it, now there is just one challenge, what did I see while solving it, brother, I am saying that I did it very easily, but the slice of apple is there in it. The account which is there should be given greater. Apple's account in the slice is equal to the garden. Apple's account which is the garden should be on the right side. If you want Apple's camera, then tell me, it is given very easily, but how will you remove the Apple account, it is okay, you can remove it, believe me like this. Mom, if I erase it's okay, let me clean it a little, you have to remove the Apple account only, otherwise like Mom, you cut it from here, okay, then you can remove the Apple account by putting a loop on it. Yes, the person below will also need an Apple account to see that the brother below should also be an Apple child or the mother. So what does this mean for the people that you will write look literally every time, because now you will be able to find out that way. If you write a loop on Kitna Apple Hai Like mother asks what is the challenge of brother, how to withdraw the account of Apple, okay, so the story points which were just now were done by me with ease brother, that was also done by me too that I Ford Loop is written and I have found out where to cut Horton, so you will remember when this was my pizza 012, so remember, you can cut from here, we will start cutting from tire size = 1. One will start cutting from tire size = 1. One will start cutting from tire size = 1. One can also cut on one side and can also be cut on the right side and h+, so the fruit loop is can also be cut on the right side and h+, so the fruit loop is can also be cut on the right side and h+, so the fruit loop is very easy. I wrote that brother, we have to cut it, okay, so let's take the mother, we have cut the fruit loop, we have cut it horizontally. It falls on you in slices, mother, you have taken it out, it is okay, so it is okay, what will you do after taking it out So father has given you life, now you have to do the lower size one, it is okay to do all the above tomorrow. No, they will do it tomorrow and we have to remove his Apple account. The most important thing is how will it come out of Apple, so now I will just tell you separately that who will remove Apple and how will it come out, then you will be ready to write the complete code and told the story points. Here, all this is very easy, is n't it? Check out Meta's Apple account every time, this is the challenge. Here too, you will have to check by taking out the Apple account, okay and look here, it is an Apple account, isn't it? And if this equal is easy, then how will the base come, then it is nothing, okay, I have to calculate the apple count every time, it is okay, but by writing the loop, you are cutting horizontal, vertical. We will check all the possibilities, we will follow up and do the reconstruction. After extracting Mentha's number from Apple account, how will it be obtained, then I want to understand it separately here, okay, this is very important, look at it, first of all, what do we do, first of all, let's take an example and write down what was given in the example. Okay 012012 and Apple has given A Apple is very important, he said that if you cut horizontally then you will have to give the upper slice, okay this lesson of the studio is constant, now you are saying what is the benefit of this part is constant. Come on Maa Laiya, whatever cut you are making, the bottom right corner has not been kept constant, it is not changing every time, isn't it because look like Maa Laya, if you cut horizontally then this part will go back, so look in this, it was constant either. If you cut it vertically, it will be cut, this part will go back, this part, look in this is a constant, understand that, okay, now let's do one less, okay, I know Okay, 012012, okay now, Apple Studio, which region, which slice account, you? You are storing it, tell me, okay, the most important part is the same, look, remember I said that this part is constant, so you know what I mean, what will I keep from i to and k, extracting area, this is one, right, from here onwards this is the whole M-1. And this area till N - 1 will whole M-1. And this area till N - 1 will whole M-1. And this area till N - 1 will know how many apples are there. Okay, wait a little, okay, pay attention, this thing is very important, mother takes it and I don't know it, I already know it, so now look, pay attention to me. If its Apples of I have to extract the Apples of I am writing here Apples of I Maa lo, I don't know right now but I know the Apples of I comma ke plus one here I was saying this I know so Apple First of all, see brother, it is from Apple, then see what it means, how many apples are there from here to here. Remember, I had defined the same thing that I comma J means what is being made, how many apples are there. So this is known, now I have to find out whose Apple ID I want to find out. Okay, so tell me one thing that I came here with this whole thing today, all I have to do is this pen guy, check in this pen how many. If it is okay with Apple, then I can write like this, see, it is important to pay attention, I can write like this, Apple Safai Ko, what will happen in K Plus One, Apple Shop Welcome Ajay Plus, I will do the table, do this, if there is any question, okay. That too sometime in the freezer, but I picked up this concept from there. Okay, so I am repeating again that if I have to remove I, comma, and I take the mother of I, K, plus one, I know I take I, K. Let's take the mother of plus one. Do you know what is the meaning of plus one? I know this much, neither have I defined it like this nor what is the meaning of apple cider. Apple size ranging from M minus one and minus one which is being made. I know as much as how many apples are there in so many parts, it is okay, now it is clear, what do I have to remove the comma, what does it mean that it is complete from here till here, this much I know is fine. I just had to draw this is the head of the pen, it's fine, I will draw four looks in it and run it from here till here, it's fine, so if seen according to that, then this is a tutiya, see what kind of flower it will be, okay, now see. Remember, to fill i, it was necessary to know the i comma plus one, so now let's start filling it in the reverse order so that I know the next part, so I start filling from here, okay, you are a comma, so see first. Let's take 2, is there any apple in it, is it okay? If there is no, then I have marked it as zero. Okay, then look here, what does it mean, there is only one apple in it, okay, it is Bharat, that means it is okay here. So, how many apples are there? Well, now I am Bharat, so what does it mean that from here till here it is okay, zero apples, it is okay from here till here, sorry okay, now let's take the filling, so it means this much. How much apple is there, it is completely known that there is only one apple, okay, so there were two apples which I got from here, so we did plus one, mine became three, okay, so what did we do, we made one, and hey, who is mine? This one is ok, so now pay attention to one thing, what benefit will I get from it, ok, let me take it as a mother, I will make a clean diagram and show it to you, see, I have made it clean so that you can understand it better. If it is possible then we have taken this one from Apple above, okay how is it India, you will know that too and this one has loops on it, so I will write the value of this too, from here also now after seeing the visual you can write that Mother, let's take it, you have to fill its value, what does it mean, how many apples are there in the entire area from here to here, right? You were filling all the apples but there are loops, okay, so how many total apples are visible here, if three apples are visible here. Maa take it, we have to fill it, okay, so how much is there in this amount, it is necessary, so there are two, here, one, here, zero, here, two, there are also two, okay, 321 221 000, okay. This is filled, now let's see what is its special feature, how will it help, I am fine, now see, remember what I said that when we used to cut, mother, we cut horizontally, here we used to check this, brother, please check this. We used to check whether it has Apple in it or not, and also we used to check that the one which is being cut below should also have Apple in it, how many Apples should be there, okay, then we should have known the Apple account, I was concerned that If you need to know the Apple account, then remember that you cannot easily find out the Apple account of so many words. Now you can find out this part of this part, its value means Apples of one comma zero. Okay, so we have found out that which is known by cutting. Which means sorry, do you know how many apples are two apples from one comma zero, mined both of them and cut them horizontally, okay, remember I told you that by doing horizontal, you will do very well, okay, so check further, which is okay. We will give these upper slices, which is the child, which is the slice, which is the child's slice, which part is this part or this part, is this part ok, so tomorrow we will have to do it in this manner, then tomorrow we will have to check before doing the reconstruction, so remember I Said I will keep the check dal, first of all I will see that in the upper slice which I am giving to the guy, I should make at least the number of apples in it ≥ and the lower slice ≥ and the lower slice ≥ and the lower slice which is the remaining slice in which I have to cut further. That is, what is its value? Apple is one comma zero, that is, we will store it in the lower slice. What should be the value of lower size in the lower slice? Either greater than equal to that. It should be -1. You must have remembered that I had It should be -1. You must have remembered that I had It should be -1. You must have remembered that I had told that for all the people who have children, they should get at least one apple in all the slices, either give a grater or give equal amount. I should have started, not import, I had also told you earlier that it is okay if this happens then it is okay, my this happens, if this happens then it is okay, my answer is plus one, then the answer will be equal to you, sorry, whatever the answer will be, plus this is equal to you then Tomorrow we will do the lower slice, but it will be there tomorrow, okay, we will do it on the lower pizza tomorrow, okay, it is similarly vertical, let's take it, okay, then we will take out the left slice of the vertical one, is n't it okay, the vertical one, like mom, let's take the vertical one. Let's draw here, take the vertical mother, take the cat from here, okay, how will you know that, easily know how it is known that the right second has been taken out and we take out the total. If we subtract this right slice from it, then we will not take out the left side. Okay, I know one thing that if the flower has to be taken out then what will happen to those apples of 00. Okay, so what will happen to the left, brother, it was not taken out easily. If you look at the left side has not been taken out. Apples of zero, I will make them right. The slice will be taken out on the left, I had told that now I have become a court, peace is ok, so first of all I have to write the code like a story, here it is ok that I had written a function named question, ok and the slice I got It's like it's an obvious thing, like mother takes it, I cut it like this, it's okay, so the upper one is finished, the lower one, I need to know from which index it is starting, hey that is my pizza, from which index. It is starting from this index, it is ending, so I know every time that we are going to end here, but we should know this every time, okay, so when the pizza comes in the beginning, then it is obvious. Now I have a phulka flower, I don't know that the pizza starts from 0 and the end will be the same every time, okay, so I will say that I am starting with I comma G and what is I com A in the beginning? Let's go, I will do it tomorrow. Solve 0, right? And yes, we will also have to keep the value of 'K' Solve 0, right? And yes, we will also have to keep the value of 'K' Solve 0, right? And yes, we will also have to keep the value of 'K' that how many people have to be distributed. Right now, that is important. So, this was a very simple part. Okay, brother, we need to know about our research function. It will be something like this, okay, this is my solve function, it will look like this that my slice of speaker starts from IK, top left corner and top corner, sorry, bottom right corner are fixed, N - 1 and -1, that is, right corner are fixed, N - 1 and -1, that is, right corner are fixed, N - 1 and -1, that is, every time. If it is fixed then it is fine and it is fine, first of all what I said was that brother, first of all check that Apple Eye Coma J is fine, then nothing can be done if it is returned, what does it mean, I will do it, I am giving an example. = 5 is giving an example. = 5 is giving an example. = 5 is fine, there should be at least that many apples for the number of people who have to slice them, this is fine, one will be this, second, you will remember what I had said that brother, if there is one, this is equal to you, then there is one. Give it to a person, I have to give the whole pizza to a person, when there should be at least one apple in it, that is, if there should be an apple, then I will say, okay, there is a way to distribute it, I will give the whole apple. I will give it to this guy, okay, we will make the return one, otherwise how can I make the return zero, brother, I cannot give it, till now it is clear, we will make horizontal cut, okay, you can cat with ha = i + 1, okay, so that can cat with ha = i + 1, okay, so that can cat with ha = i + 1, okay, so that above. The first slice should go to the one above. Okay, give i+1h li and till h+ Okay, from here we give i+1h li and till h+ Okay, from here we give i+1h li and till h+ Okay, from here we can cat. Okay, now we have given cat, now if we have given cat, then the above slide will go. The above one will go. Slice Banda will be happy and I will do further cutting on the lower slice but I will have to check also, right, how many apples are there in the lower slice, okay, we have cut it horizontally, so how many apples are there in the lower size below? I want these ones, so what will happen to Ha? One second, what will happen is how many apples are there in this entire area, so I have taken out this, okay and I have to take out, how will I get the total, what will happen, as much as I have. Are there apples? Make lower mines in it It's a good thing Kitne bande ke mines one Okay, so there should be K - 1 Kitne bande ke mines one Okay, so there should be K - 1 Kitne bande ke mines one Okay, so there should be K - 1 apple >= Okay, this is okay Answer Plus Okay, if all the others are okay If I distributed pizza to the people, then the answer will be returned from there, so I will do it tomorrow, the solution will end here, okay, now coming to the vertical cut, okay, it is very simple, now I think, without looking, write the dog vertical cut, so the diagram was made first. Let's take the diagram, I know how to write the code, generally it is ok, first cut from here, my mother, I want to write a cartoon from the story, then I have to write a fruit loop, remember I was here, K was here, okay, so where can we do the vertical from where V = here But you can do it with K Plus One, you can make a vertical cut with K Plus One can make a vertical cut with K Plus One can make a vertical cut with K Plus One This is complete, this is complete, how many apples can be found in this amount, the whole apple will be taken out, okay, only then I will add the answer to the answer. You will have to check the answer. Okay, so you can do this and write the complete code starting from 123455. Which was the two part brother? Can you tell me a good way to calculate the name count of apples? The one which we had written is one named Apples. We have taken it, right, this one is logical, okay, I will say that when this apple wala is not this apple wala, I will write the follow-up, it is apple wala, I will write the follow-up, it is apple wala, I will write the follow-up, it is written here, I also had a lot of fun in learning, so I learned by doing dry ring. How is it being populated, it is fine and just taking this point into account, I have written this code. Okay, so now understand the story of this code and the 5 points explained in it, let's enter it in the lead code, create the code from the story and see, it gets submitted. This is also changing, is n't it? So it is changing, I and sometimes it is changing every day. Look here, now the pen is changing, look here, three variables are changing, so what will I do? I will take one more DP of three dimensions, okay, I will start with the old style, so first let's write the description, then let's do the layout, then let's start coding it, exactly the same story points that I told. The code written according to this story points is ok, let's keep two variables - 'row' and 'pen' to is ok, let's keep two variables - 'row' and 'pen' to is ok, let's keep two variables - 'row' and 'pen' to make noise, 'm' is pizza dot size make noise, 'm' is pizza dot size make noise, 'm' is pizza dot size and 'm' is the size of pen. If mine is fine, then what I told you is that if you have to file Apples of Eye Coma, it is fine, what else has to be done, this one is fine for filling the information and this one, you should know how to make it, there are many questions based on this, fine. Hai li dene plus So Apple's account will be increased, so this is what I have done, okay and Apple sir, I have not yet defined it, I should have done that, so now see, let's see the maximum length, how much can I give? I have given 50 rupees, so what do I do? I am late in preparing the length of the apples. What can I see? Now I have made all of them. Why did I make this just so that I can easily find out how many apples are there in which slice, okay? Find out how many apples are there but what is the fastest way to store them once and if you can find out then I will also write here Apple of Apple I am Mango's Tu Minus One Tu Degree, are you sending us right? How is it that if I am talking about pizza from my heart, if the total number of apps in it is < done then brother, there is no option, < done then brother, there is no option, < done then brother, there is no option, make the return zero, at least I would like to have Apple. So that I am sure that it is okay and the second test was that if only one piece has to be given, that means what if you have to give the whole apple, then you have to give the whole apple, otherwise the return will be made zero, okay, now these two lines. You can also combine simply return is equal to one, which should not be confused so that you can know that if the total count of apple is greater than equal to one, it means that a way has been found in one unique, then one way has been found in which I can read that I will give this entire apple to a person and if it is not so, there are not so many apples, there is not even a single apple, then the return will be made zero, no, they are there, let's keep them here, what did I say? Firstly, I am taking out the late ones, meaning what was the meaning of giving it to the left upper one or giving it to the guy, so let's see first, this is how to take out this, I did not know that you can take out the lower slice apples easily because you have Horizontal HSC through and K, so this gives me the entire apple in the lower slice like this, but from MS to Mahsun, it is okay, so in the lower slice, I got to know the apples, I have written it above, it is okay and if I want to extract the upper, then total, apples, total. Slice should be greater, give equal to you one, from which I am going to run Recon, okay, this should be greater, give equal to you, minus one, because in the rest of the monsoon bands, I will slice it and give it. If both of these are true, that means they are totally fine. Answer Plus Is Equal Tu Solve Kya Karenge There is an apple on the left side, because of the slippers, how much apple is there in it, that's why I don't know, I will take it out later, okay, I will have to run Recon on it, right slice apples, okay So I know the right slice of Apple. I know which row of apps it is. I have cut it. It will be V. It will give me Apple. From I comma way from M-1 to N-1, I have to right slice it. I M-1 to N-1, I have to right slice it. I M-1 to N-1, I have to right slice it. I know the whole apple of the slice. If I want to find out the left slice, then what will be on the left side? Total minus the right slice. I know the total. I can easily extract it. I have to give the left slice. The guy will have to see. The left side should be fine. If so, then it is a very good answer plus it is ok, here it is making a vertical cut, neither Rohtak will remain nor is the whole code, this one was important. Hey, how to do the form, ok, there are many ways, I told you this easy way, now one The thing is given in the question and not to find out the moduli because the answer can be big. It can be numbered. In the answer, find out the modulo. The modulo power of the tank is 9 + 7. So what do I do in general? 9 + 7. So what do I do in general? 9 + 7. So what do I do in general? I am just defining it here. It is saying that it is okay to do mode everywhere, like here from where we are extracting answer plus, it is equal to you i.e. answer plus, it is equal to you i.e. answer plus, it is equal to you i.e. answer plus and here we write like this, modulo mode, apply mode outside also, okay, everything is correct. Must be going here, now let's see if the answer comes or not, it's ok, after submitting it, let's see if brother without memory session gets solved or not, it's ok, just wrote the request, we'll give it ok, I think, it's ok ] And we have how many three values can we keep DP of equal tu mines k is clear till here and whatever answer will come out here I will store it here DP of i comma j = ok now let's see the answer i comma j = ok now let's see the answer i comma j = ok now let's see the answer then example The ones should be passed. Let's see after submitting. This time the total should be submitted. Okay Joe D. Look at the test cases. It's very good. We also got the March match. If you were following me every day then you would have got this. ok next video thank you
|
Number of Ways of Cutting a Pizza
|
number-of-steps-to-reduce-a-number-to-zero
|
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts.
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
_Return the number of ways of cutting the pizza such that each piece contains **at least** one apple._ Since the answer can be a huge number, return this modulo 10^9 + 7.
**Example 1:**
**Input:** pizza = \[ "A.. ", "AAA ", "... "\], k = 3
**Output:** 3
**Explanation:** The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.
**Example 2:**
**Input:** pizza = \[ "A.. ", "AA. ", "... "\], k = 3
**Output:** 1
**Example 3:**
**Input:** pizza = \[ "A.. ", "A.. ", "... "\], k = 1
**Output:** 1
**Constraints:**
* `1 <= rows, cols <= 50`
* `rows == pizza.length`
* `cols == pizza[i].length`
* `1 <= k <= 10`
* `pizza` consists of characters `'A'` and `'.'` only.
|
Simulate the process to get the final answer.
|
Math,Bit Manipulation
|
Easy
|
1303,2288
|
507 |
all right let's call the perfect number so you are given an integer and return true if a is a perfect number or that's why i return false so a perfect number is a positive integer that's equal to the sum of a positive divisor so this is pretty much it right so uh for the example this is 28 right so how do you actually know 28 divided by 2 we can get what 14 and 20 divided by 7 you can get 4 right so 2 plus 14 7 plus 4 and 1 2 plus 14 7 plus 4 right and you only need 1 which is 528 divided by 1 and you get 28 but in this case i we don't want 28 but you need one for sure and seven has nothing to divide so when you go to one times seven be honest and you cannot you have to exclude the seven itself so basically this is supposed to be a super simple question you use a for loop and how do you go through you starting from i equal to two yeah we at the end we plus one at the end so we don't have to like starting from equal to one so we know we need to increment by one union when we check if the sum of the integer is equal to the given value and if that's true level i can just return true and then basically this is supposed to be super simple and this question is about math so um so here's the basic so i'm going to say 9 is actually equal to 0 or now it's actually 1 i'm going to return false right so which means this is not valid number but um i mean num cannot be equal to zero be honest so i mean whatever so let's talk about the song so i'm going to add every single up every single year job and then i will just have to return if my song if my name is equal to some plus one right so i just mentioned you have to increment one unit uh plus one in the end to just compare and then i need to say for loops for i q i less than no and then i plus and then in this case we know that we are trying to what the maximum for the number is actually what i times i less than 28 right so which is what uh one moment so here's it so how do you know 20 is basically square root of 28 right so right side uh you have to know the maximum the ranges i times i which is square root of 28 so okay i can just making i can say methods for be honest right but in this case i don't want to do at least i want to do 8 times i and this is supposed to be the same but if you use meta square and then you will get rid of the remaining number uh either way it's fine right so i'm going to just check if my normal i is actually equipped with zero i can actually add my number so how do i end my number so if i know my 2 is a positive divisor for 28 i can know my the other one is 14 this is because what this is because if i say 28 divided by 2 i know 14 right so basically 14 is actually equal to 228 over 2 and i can say okay 14 and 2 is actually uh i can add 14 and 2 to the sum right so i can get rid of these two and then four and seven exactly the same thing right and then let me say i'm going to say um i plus num divided by i and you don't have to worry about i equal to zero because i cannot be equal to zero right and this is a solution so here we go something and yeah so there's about time in space for the space is simple it's gonna be constant for the time this is actually uh the square root of one be honest and uh this is supposed to be easy and i will see you next time bye
|
Perfect Number
|
perfect-number
|
A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly.
Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`.
**Example 1:**
**Input:** num = 28
**Output:** true
**Explanation:** 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.
**Example 2:**
**Input:** num = 7
**Output:** false
**Constraints:**
* `1 <= num <= 108`
| null |
Math
|
Easy
|
728
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.