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,903
Do it 200 Hello brother, today we are going to discuss the important thing that has been given to us is that in winters village, if anyone wants a job then he can do it and if no one else among us can speak English then We have to return half so if we see once what is the meaning of Sab Singh then it is given that who is the most Vijay Singh Soy on this account if we say in example I call it 420 6 If I say that in my example Two that of that subject I can say that and one of mine will give this total thing is okay and 6 from others that we all can say that all these photos so we can say that 2016 Subscribe So we can say that this What can happen if we subscribe to our channel and we have to return the last value and the inter revenue is a number, it should be formatted, so if we talk about this case, then see here, if you have not subscribed, then we will do it here. And if we look at the example a little carefully, because our aa right mode digit qualities, so what we are saying is that this is the entire string and our largest value and retailer, so we can return this trick only. If we talk about the contest then we have given that the name is daughter in the admins good thing is even, its length can be in the middle of exam clear face and we have given that If you have to choose then it is only in its content. Before going to the solution of their problem, let us keep them in mind about some important contests. Like Lord Krishna, what is the meaning of Lord Interior and how will we see it that if I say that my number is there then you will accept it. Hain free live hai tu ko 7828 surya my friend this is what we have to pause in this largest oil and what is here yes so what can I see that if I come in we are a number then and when do we say that everyone knows that So how do we if and there is Shubhendu then this and number will become A similar for if I put any number in there is 1000 likes nine to the 3246 Shyamveer white mode this is what it is and that if this is what that is then I can take this The whole number is mine, so we can say this concept, using this point, we can say that if I travel right click in the towers of the string, if I just when I do, then my next flight mode is on. If you do it then what should I do that I have to return it on my saliva just avoid was the largest value and if I come to know that this which if I am trying is mine then what should I do that Ramesh number then give him a If I return in the format of trick, then this is what I am waiting for, this is my answer, so in this case, 352 forces will loot this WhatsApp and see what I said, what will we do if in the room of one of my friends, from its side, right, left. We will do towers and see that whenever I get it, we will do its tax, so we will join it, subscribe this point, loot, this is our function, larges and number, agreement is given in it, string name, which line is this, it depends. If it does this, then you can use ours, click here I am, I have subscribed, and if I have forgotten this [ subscribed, and if I have forgotten this [ subscribed, and if I have forgotten this , then it is done, now I understand, so if my If black is true then what will I do, I will return Nandasa office hours Function Let's see a little how it works if you subscribe This is my 24 carat prayer is pressed here AB So this is my first agreement So this incident talking tom that they don't know listen refers to the starting index show the setting and this is second and different this represents the number of limits phone number movie Ae loot number and balance so present here is what I gave What will I do if I find this here? Subscribe because we are two. One is my inductee and one is my number. This is the answer. If you have not subscribed to these tips then no. Subscribe Like and subscribe So if I say that then I am the answer If the mouth is that this kids is a character here, if Mr. has a different last year, then this is a little more difference, subscribe to this, then this can be here She is returning to me. Am I a teacher? What happened brother? She is returning similarly. If I am waiting for lakhs of rupees, I do agriculture, I got a job from zero. If I make her a reader from zero to hero because of the class. So give me only one thing which is needed, right then we are doing it that this number is required, name size, this name is required, give me an individual number, I am subscribing to it, Xerox Festival, he is concerned about this, both the characters, if these tips. We can do porn till it gets over so this is it If I am here and here if I want to check the number then this will work if not otherwise then this was the solution for today I hope you like it Felt like thank you loot
Largest Odd Number in String
design-most-recently-used-queue
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** num = "52 " **Output:** "5 " **Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number. **Example 2:** **Input:** num = "4206 " **Output:** " " **Explanation:** There are no odd numbers in "4206 ". **Example 3:** **Input:** num = "35427 " **Output:** "35427 " **Explanation:** "35427 " is already an odd number. **Constraints:** * `1 <= num.length <= 105` * `num` only consists of digits and does not contain any leading zeros.
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
Medium
146
1,027
hey guys today we're going to be solving a code question one zero two seven longest arithmetic sequence this is a dynamic programming question it's a very popular question and if you have been struggling with this question don't worry about it because it is not a very intuitive the solution to this question is not very intuitive I struggled with it as well if you have been it's fine I hope I can give you a give you an explanation that you can easily follow so let me just explain you what the question is we have given an array of integers and we are supposed to find the longest arithmetic sequence that we can in the array now the sequence can be increasing or decreasing doesn't matter so as you can see in 3 6 9 12 the maximum length that you can find is and I hope that everyone knows whatever what an arithmetic sequences and arithmetic sequence in the sequence of numbers in which the difference between every between all consecutive numbers is the same so like 4 3 6 9 12 the difference between consecutive integers is 3 and the total number of numbers in the sequence is 4 so the answer is 4 and it is an increasing sequence if we look at this example the longest arithmetic sequence is 20 15 10 5 which is a decreasing sequence now I think the question is easy to follow what also helps with the solution to this question is that they only asked for the length of the longest sequence are not really asked for the numbers which make that sequence so that makes the solution a little easier cool so I won't waste too much time and trying to explain how you arrived at the solution because I couldn't I looked up the solution and I understood it and now I'm just going to present the solution and explain it to the best of my abilities cool so this is a DP problem what we this is not a very typical dynamic programming problem in which you have a 2d table now not all dynamic programming situations are like that but usually you would find a 2d array and which will build and you'll find the result at the bottom right or the top right or maybe a single array of which the last element is the answer this is a different kind of dynamic programming in which there is some memoization and you do look at previously calculated results to compute the result of the current element which is why it is a dynamic programming solution so what we are going to do is if we have an array of n lengths we are going to maintain another array of n lengths in which every element of that array is a dictionary meaning we have a dictionary for every element in the original array and this dictionary contains the difference between this contains information which indicates the difference between this current element and every previous element plus the number of times our difference has occurred before that previous element now that has a lot to processes it's really not that difficult it's I think it's best if I type it out on the IDE and explain to you rather than trying to verbally explain it so let's just go with a simple example what I mean to say is if we have a numbers array of 3 6 9 12 we will have maintain our DP array of four elements which have their own dictionary okay in which every element is a dictionary I hope dictionary or hash table either it's the same it's a it dictionary or hash table contains a key and a value and the keys is a hash value so it's order one access time cool so what we will do is now for three there is no element before it okay let's just assume that the dictionary for dictionary element three is empty it's an empty dictionary please note that dictionary and hashmap are the same I am more used to excuse me saying dictionary because I must have developer but it's the same as a hashmap and Java so don't get confused on that okay so the first element will be an empty dictionary okay now we have to calculate for the second element four six we have to calculate the difference of six with every previous element now there is only one previous element which is three what is the difference between six and three so we will make an entry in the dictionary for six saying 3 comma 1 3 is the key and 1 is the value now what does that mean that means that the difference 3 has occurred once before 6 which is true right we've only seen three before it and the difference between 6 and 3 is 3 okay that is what that means now moving on to 9 now we have to calculate the difference of 9 with every previous element of 9 so we will calculate the difference of 9 May 3 and the difference of 9 with 6 now the difference of 9 with 3 is 6 okay so we will make an entry of 6 and how many times have we seen this difference or till now once so we will say 1 now what is the difference between 9 and 6 it is 3 right it is 3 so we what we'll do is we'll enter 3 and 2 yeah this is the crux of this problem okay what we did is we will subtract 9 from 6 we will so we will subtract 9 from 6 is that previous element that we are currently inspecting we're inspecting all previous elements of 9 but if the current previous element is 6 we will inspect the dictionary of 6 and see how many times 3 has appeared before 6 so basically we will use the dictionary of all previous elements to construct the dictionary of the current element what I mean to say is when I calculate a difference of 9 and 6 I see that the difference between 9 and 6 is 3 I also see that 3 is a key in sixes dictionary and I all and then I see that 3 has occurred once before 6 because there is an entry of 3 to 1 in sixes dictionary so I take that value 1 plus the 1 to account for the difference between 9 and 6 I hope I explained that well that is really the crux of this problem if you get this will get the entire solution because it's not difficult after that point if you get this point anyway I think we can move on you will understand this as we code but this is the core concept of this problem now I will calculate the difference of 12 with all previous elements the difference between 12 and 3 is 9 that difference as only has never occurred before 3 right so basically when you inspect the difference between 9 &amp; 3 I also look at three is between 9 &amp; 3 I also look at three is between 9 &amp; 3 I also look at three is dictionary to know how many times that difference has occurred before 3 right and nothing has a like there are no elements before 3 so it's an empty dictionary yeah and that's why 3 has an empty dictionary I hope you get that now why because there are no elements before 3 so there's nothing to calculate different calculate the difference with ok so 12 minus 3 is 9 that difference it's 9 and it has only occurred once so I entered 1 then I calculate a difference between 12 and 6 now 6 has never seen a difference of 6 before it right there is no entry for 6 in sixes there is no entry for the difference 6 in the element 6 is dictionary so again this will be six one and then finally I will calculate difference between twelve and nine now I look at 9s dictionary 960 says that until 9 the difference 3 has occurred twice ok now I take that value and I added to put up the two like update the entry in nine stick study so this will be three cool so that basically what that basic and we will be maintaining a max value throughout in the loop and we'll keep updating that in the loop that is more of the coding logic calculating the max value from this is very easy understanding this is more important so now what does this TP array mean so 3 what we can see is the difference 3 as I awkward twice before 9 now if we are actually in please note that we are actually counting how many times have seen this difference right so the final result B will be that max value plus 1 because you need two numbers to make a difference right so if we have seen the difference 3 thrice it means four numbers were used to create those three differences right if I say that I've seen a difference of 10 it there has to be two numbers are mental difference 11 + 1 or 12 + 2 or 15 and 5 difference 11 + 1 or 12 + 2 or 15 and 5 difference 11 + 1 or 12 + 2 or 15 and 5 right so what I basically want to say is if the number of time that the number of values in the final sequence will be one more than the number of times we have seen that difference okay now I explain all that there is next name with the concept of this solution it's it is an order n-squared solution because we will have n-squared solution because we will have n-squared solution because we will have a an outer loop will which will iterate through all the elements in the array and then we have an inner loop to iterate over all the elements before this current element right so it becomes order n square I think that's enough to start coding I'm sorry about the notification sounds that I am getting I should have switched off my phone anyway I think we are ready to start coding it's a it's if you understand this concept it's a very easy solution right okay I'll get right to it that's character okay now let's just comment this out so that we can keep forever into this okay please note that the minimum array length is 2 so we don't have to make any empty array checks they're basically saying that you will at least have the minimum answer is 2 because they will adhere if there are two numbers they do follow form an arithmetic sequence right like any two numbers in the world so they're basically saying that will not give an empty array we'll make sure that you have at least some sequence and the minimum length of that sequence is 2 so I'm not putting in any empty array checks please know that I'm going to write up for both I'm going to write verbose food there's a lot of redundant code that I could avoid but just for the sake of clarity I am going to write some I'm going to introduce some extra variables that I don't really need basically is what I'm trying to say the length of the array I'm sorry I've been saying hash map but what I mean to say is I'm sorry that I've been saying dictionary but it's the same as a hash map in Java okay so it's an integer to n teacher hash map and this will be an array we'll call this the tepee array creating a new instance for this of the same length as the original array okay this is base this DP is basically this array this entire array okay moving on this is the max value is the final answer okay this is what will also return so as I said it will be max value plus 1y have I initialized it as 1 because that is the minimum number of times and I'll see a difference even if there are only two numbers which is the minimum array length I will see dark difference once right and the final answer is the number of numbers that form that difference which is 2 because you need two numbers to make a difference okay let's move on this is so a trading overall numbers say and I equal to 0 I'm sorry if I am poured into slow Java is not my first language ok it's rating over the outer iterating over all numbers let's pull out the current element that we are inspecting semicolon now let's pull out the dictionary actually let's instantiate the hashmap for this current element because we are going to construct the difference dictionary for this current element it's not there so I'm instantiating a new hash map for this current element and please note that I'm using dictionary and hash table interchangeably it's the same thing it's a key/value pair data same thing it's a key/value pair data same thing it's a key/value pair data structure now okay just I'm just gonna assign this to a variable current map just for clarity okay so current map is the empty sorry empty hash map of the current element that we are going to construct now I'm going to iterate over all the elements before the current element so for all J before I'm sorry I've messed up the indentation okay so what is the difference between the current element please note that it's this solution will also account for decreasing sequences because that difference will be stored as a negative number but it's only a it's only an entry in the dictionary so it doesn't matter if this will cover increasing and decreasing sequences current element - let's pull out the current element - let's pull out the current element - let's pull out the previous element that we are currently inspecting right because we do need that okay this previous map is the dictionary of the current previous element that we are inspecting okay now let's say this is the new value that we are going to put in our current map okay now the previous map could have seen the difference that we are currently inspecting okay so if I am the current if I am the previous element I have been reached by some current element by a difference it is possible that I have seen the difference between me and the current element before me and it is also possible that I have never seen it before okay so if I have seen it before I just pull out that value if I have notes in there before I'll just initialize that as 0 and add 1 to it please note that I'm adding this plus 1 to account for the difference between the current element and this previous element that I have arrived at because of that difference I'm just accounting for that difference and that's the plus 1 that I'm doing it okay moving on we have to update our current map yeah we have to put this current difference that we found and the new value okay it is possible that this is the first time using this difference it is also possible that we just added on to our difference that we saw before and what we are doing so you should take what we can realize at this point is by seeing how many times a difference has occurred how many times the same difference as awkward earlier but actually calculating the longest arithmetic sequence because we are trying to find the maximum number of time that we have seen a difference right cool and arithmetic and the law and an arithmetic sequence is a sequence of sim same differences we are continuously looking at how many times have found this difference earlier oh yeah we have to because current map would be a copy so I will assign it back please note that this can be done in a more concise way I am only writing it this way so that it's more verbose and it's easier to understand and finally we'll update our max value so we update this max value continuously so this is where I said that it doesn't matter which numbers are forming the sequence it only matters how many times we have seen this difference and how many numbers are forming the longest arithmetic sequence the which numbers are forming it doesn't matter which makes this problem and solution easier that's it that's really it let's see if it works as you can see it's an order n square solution oh I'm sorry then for that semicolon n as I was saying this is an order in spit oh god I'm so sorry for missing these semicolons okay the base case for past what I am saying is this is an audience for solution because you can see there are two for loops over the same input array let's summon this okay that's it I hope I did a decent job in explaining the solution to this problem I did find this challenging which is a bit when I've course ordered which is why I wanted to make a video about this solution I hope you're staying safe take care and happy coding have a good night good day wherever you are see you bye
Longest Arithmetic Subsequence
sum-of-even-numbers-after-queries
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`). **Example 1:** **Input:** nums = \[3,6,9,12\] **Output:** 4 **Explanation: ** The whole array is an arithmetic sequence with steps of length = 3. **Example 2:** **Input:** nums = \[9,4,7,2,10\] **Output:** 3 **Explanation: ** The longest arithmetic subsequence is \[4,7,10\]. **Example 3:** **Input:** nums = \[20,1,15,3,10,5,8\] **Output:** 4 **Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\]. **Constraints:** * `2 <= nums.length <= 1000` * `0 <= nums[i] <= 500`
null
Array,Simulation
Medium
null
1,319
hello everyone welcome to my youtube channel learn to code in this video we are going to talk about problem 1319 number of operations to make network connected from the code so as you have read the question basically in this question we are given few disconnected components of a graph our task is to connect all of them in the minimum number of steps so what are these steps in one step basically we can take any edge and connect any of the two vertices from that edge that means in this example this edge is removed from here and then one and three are added from that edge it is not necessary that the edge should be either be added to one as a vertex or two as a vertice if there must be a some other component name it 4 then we could also add this edge to 3 and 4 so as we know that for a graph to be connected if there are n vertices we need at least n minus one edges so our first task will be calculate the number of edges and if the number of edges are less than n minus 1 then we can written -1 as stated in the then we can written -1 as stated in the then we can written -1 as stated in the answer because it is not possible to make the graph connected now how are we going to do this a connected component of size k requires only k minus 1 edges to make it connected if there are lesser than k minus one edges then it is not connected and if they are more we are free to remove one of those edges and use it wherever we want so and how are we going to do this that means that in this question as firstly we need to take into consideration the number of different connected components and then one by one we are going to add so supposingly if there are five number of connected components that means we need at least four edges to do so and that will be our answer so basically the question boils up to the point that now we need to calculate the number of different connected components in the given graph so one way to do this is make a graph from these edges and then traverse using dfs and count the number of connected components but the simpler way will be using union find algorithm so if you are not familiar with union file algorithm i'll request you to read about it and then come again to the question so let's start with the union find algorithm so as we know in the union fund algorithm firstly we treat each and every vertex as a single component and edge by edge we make them connected so let's start by a vector root so this vector will basically denote that which connected component is our current vertex a part of this means that root of a vertex will basically give us an identity that this belongs to this component this vertex belongs to this component if we see in the example then supposingly if we take 0 as a base root for this connected component then root of 0 root of 1 and root of 2 these all will be equal to 0 so let's initialize this route so basically right now we have initialized our root vector where each and every vertex is its own single component so after this what we are going to do is connect each of these vertices one by seeing the edges given in the connections vector so let's traverse the connection vector so now we got our two vertexes which are connected through this edge so our task is to make these two vertexes belong to a same connected component so basically what we are going to do we are going to find the roots of these two vertices so lets term them as r1 which is equals to root of vertex v 1 and find r 2 which is root of vertex v 2 and write the following function 5. now in this function if root of some vertex is not equal to that vertex this means we need to traverse this vertex one more time towards its parent or else as if root of vertex is equals to vertex we are going to simply return this vertex so basically after finding these two roots now if these two roots are equal then this means they are already connected but if they are not opponent so to unite them simply what we can do is root of r1 is equals to r2 and these two vertices now belong to a same connected component you can also do it either way root of r 2 is equals to r 1 but for right now i am going to do it like this now as we have traversed to each and every edge and we have initialized all the roots or from the specific indexes or vertices we can tell that root of a vertex will give us the connected component which it belongs to by that i mean that root of 0 will give you 0 root of 2 will give you 0 and root of 3 will give you 3 so now our task is to count the number of connected components in this graph and how are we going to do so simply by observing our terms we can say that here root of 3 is equals to 3 and in this connected component there is only one vertex which roots value is also equals to the number of that vertex that is 0 root of 0 is going to be 0 but 1 and 2 are having the value 0 as their root so this means if root of a vertex is equals to vertex it represents one single component sound the different number of connected components we can simply do a for loop in which we traverse to each and every vertex and if the root of that index is equals to itself this means it denotes one connected component and as we earlier said earlier discussed that if there are two connected components in our graph then we only need one such step to make it connected so our answer is going to be answer minus 1 and we are going to return that in our function again there is one more way by which you can find the number of connected components and that is simply count the number of unique root values that means that if the number of connected components are 4 then you can traverse to a root vector and count the number of unique elements it is definitely going to be 4 because either a vertex is going to represent itself as a root or its parent vertex is going to represent itself as a root so either way the answer will be same and the answer to this problem will be answer minus one number of connected components minus one so thank you for watching the video i hope you got the basic approach by which we solve the question if you have any doubts please let me know in the comment section and if
Number of Operations to Make Network Connected
unique-number-of-occurrences
There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network `connections`. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return _the minimum number of times you need to do this in order to make all the computers connected_. If it is not possible, return `-1`. **Example 1:** **Input:** n = 4, connections = \[\[0,1\],\[0,2\],\[1,2\]\] **Output:** 1 **Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3. **Example 2:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 2 **Example 3:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\]\] **Output:** -1 **Explanation:** There are not enough cables. **Constraints:** * `1 <= n <= 105` * `1 <= connections.length <= min(n * (n - 1) / 2, 105)` * `connections[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no repeated connections. * No two computers are connected by more than one cable.
Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.
Array,Hash Table
Easy
null
1,832
what is a pan gram is nothing but a special type of string which has all the letters of the English alphabet occurring at least once so it will have every letter A to Z and they can be repeated multiple number of times but every letter will occur at least once you understand this problems becomes fairly simple to solve so let's see what we can do about it Hello friends welcome back to my Channel first I will explain the problem statement and we look at some productive cases going forward we are going to start with the Brute Force approach and then try to see how we can come up with multiple Optimal Solutions after that we will also do a dry run of the code so that you can understand and visualize how all of this is actually working in action without further Ado let's get started foreign first of all let's try to make sure that we are understanding the problem statement correctly in this problem you are given a string and you have to check if it is a pentagram now what is a mangram is just a special type of string which has all the characters of the English alphabet from a to V at least once so to understand it better let us look at our sample test case so in our test case number one I have this string right and you know that this is a very popular string which contains every letter of the English alphabet all the way from a all the way up to V right so for this particular test is you need to Output true as your answer because you can find each and every character from a all the way up to V right similarly if you look at a second test case I just have a small string right and you can easily see that this will not have all the 26 characters so for this particular test is you need to Output false as your answer because you cannot find all the different characters and hence this string is not a pentagram so this problem is relatively very simple to understand so how do you go about solving it when you think about this problem in the most naive way what comes to your mind what you can do is you can start with each and every character you start with the character a and then you will try to find this character if you can find it in the string right you start reversing the string from the beginning and you see that hey you found an A so you are good right similarly what you're gonna do is you will start with the next character and that is B once again you start reversing your string and hey you found a b similarly you will do this for every character all the way up to the last character and that is V correct if you are able to find each and every character then yes this string is a paragram if at any moment you encounter a character let's say x and you do not find the character X anywhere in the string then this trick will not be a paragraph and you can return a false so technically this method this methodic transfer each and every time but do your problem with this approach in this approach you are iterating the string again and again right try to think about it for every character you are starting from the beginning and going all the way up to the end what happens if your string is very large let's say you have 10 000 characters then for every alphabet you have to Traverse the entire string again and again right so this will waste so much of your time approach is not desirable and you will be asked to come up with a better or improved solution so what do you do about it once again I have this sample string with me right and you know that the letters in the English alphabet are fixed you only have 26 characters correct so one approach that comes to your mind is okay what is somehow you can store hey what are the characters that I have already encountered so what are you gonna do is just create an array of the size 26 so you see over here that I have an array that has a size 26. so you can see that the index 0 should correspond to the letter small a and the index 25 it will correspond to the letter Z correct and once this array is initialized all of these values they will be set to 0 correct since this is an integer array so what you can do is you can start by treating your string character by character the first character that you encounter that is the character T right and T is the 20th character in your English alphabet given an array starts from 0 so that means this should appear at the index 19 right so what will happen technically is somewhere you will have a index 19 over here in your array right and its value will be also 0 right now correct so as soon as you see the character t T is 20th position its index will be 19 so go on to the 19th position and change this value to 1. now move on to the second character is second character the second character is H correct and H comes at the eighth position in the English alphabet eighth Ovation means a seven index and you will go at the seventh index in your array and currently its value would be 0 once again right whatever be the value just change this value to 1. similarly what you're gonna do is you will keep on doing this for each and every character for every character that you encounter just change the value in this array to 1 right now once you have iterated through this entire string if a character was present its value will have changed to 1 right and if a character was missing then you can never approach that Index right think about it a string did not have the character y then there is no way that this value would have changed to 1 correct and once you have completed the iteration of your entire string just look at your array once again if you find any value to be zero that means there was at least one character which did not occur in the string and hence you can say it to be false if you found all the values to be one that means you have encountered every character at and hence the string will be a pen right now this is a very efficient approach because you are iterating through the screen only once but there can be some cases where the interviewer asks you that hey can you even optimize this problem even further try to think what happens if you get a string that looks something like this you could have all the letters of the English alphabet A B C D all the way up to Z and then once again you have all the characters ABC all the way up to Z and then once again you have ABC all the way up to V and this is repeated several times so what will happen in this case you will encounter each character one by one right and once you are done with the character V you have already filled up your entire array and all of the numbers are fun correct but you have all of this string still remaining you will have to pass this entire string there is no way that you can check hey am I already done so in those kind of edge cases you can try to come up with an even efficient approach and that is where we can try to use a hash fit how do the hash fit work if you're new to Hash fits I would highly recommend you to check out my video on hashpath first because that way you will be able to understand it even better so coming to a problem once again I have my sample string with me right now the purpose of a hash fit is that you cannot have any duplicates in a hash fit correct so what I can do is I can create an alphabet set and in that alphabet set I will add every character I will add all the characters from a all the way up to Z right so in this hash fit now I have every character and what I will do is I will start by treating the string character by character once again the first character is T right so just look in your hash fit and remove the character t is gone right now move on to the next character and that is H once again go in your hash head and remove the character h now the next character is e go in your hash fat and remove the character e so what is happening with every character you will go in your hash fit and try to remove it exist when the character will get removed if not does not matter right but there is a neat advantage over here what you can do is after removing every character you can check if your hash fact is empty because think about it if I have the same trick with me that if a b c all the way up to Z and then once again A B C all the way up to V and this is repeated several times as soon as I encounter all the characters that means as soon as I'm at this position I will have to remove every character in my hash fat right and if I check that hey if my hash fit empty then I no longer need to process all of this remaining string right so that is saving me some time and hence I would recommend the approach of using this hash fit because it looks neat and clean and it saves you some time as well So based upon this approach now let us quickly do a dry run of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right I have my sample string that passed in as an input to the function check if bankrupt oh and by the way this complete code and its test cases are also available on my GitHub profile you can find the link in the description below so moving on to the driver what is the first thing that we do first of all we create a hash fit that will contain all the characters right and as soon as I create this set what I will do I will try to add all of my characters all the way from the small a and all the way up to Capital C so once this Loop executes my set will be complete right you can see that it has all the characters from a all the way up to V right now moving on we start a for Loop and in this for Loop we iterate over each character one at a time correct and for every character what do I remove this character from my set right so when I encounter T I will try to remove T from my set T gets removed right I will do this for every character and at any instance if this alphabet set is empty that means I have encountered every character and I can simply return true as my answer if this Loop completes and I still have remaining characters in my hash head that string was not a pan gram and I'm gonna return a false the time complexity of this solution is order of n because you have to iterate through the entire string in your worst case and the space complexity of the solution is order of 1 because it needs a constant space of only 26 characters I hope I will be able to simplify the problem and its solution for you as per my final thoughts I just want to say that these type of problems are fairly simple it's always a good idea to make sure about all the edge cases just try to find out from your interviewer or when you're reading the problem statement try to find out if this problem is case sensitive is a small a and a capital A treated as different characters it could also be a good idea that you can ask what is the domain of all of your characters do you have to include any of the special characters as well sometimes there could be a problem that okay what are all the keys of the keyboard and then try to construct a paragraph so just keep all of these small things in mind and then these problems will be really easy to solve so while going through this video did you face any problems or have you seen any other such problems which talk about A New Concept and once you understand it the problems become very easy so tell me everything in the comment section below and it will be helpful for anyone else who is watching this video as a reminder if you video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what other type of problems you want me to solve next should I start creating more playlists should I start focus on a specific type of problems do let me know until then see ya
Check if the Sentence Is Pangram
minimum-operations-to-make-a-subsequence
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Array,Hash Table,Binary Search,Greedy
Hard
null
345
hi everyone today we're working on the leak code Challenge number 345 reverse the vowels of a string and in this challenge we're going to be giving the string s and they want you to reverse only the vowels in the string so leave the consonants exactly in place and Swap and reverse the vowels as you go through the string vowels are defined as a e i o and u and they can be both lower and uppercase so we need to account for both of those possibilities examples right here if the string is hello you see in the output that e and the O will be reversed it's a slightly more complicated string like leak code right here the two e's would be reversed and then the next two vowels this e and this o would be reversed and would swap places so in order to do this we're going to start by declaring a variable called vowels which I'm going to make a string a e i o u and we're going to do both upper and lower case there so we can account for both of those and then after we've done that what do I need to do next here we need to split this into an array so we can look at each character individually so I'm going to Define this as uh let's see let's call this letters equals s dot split all right and now we're going to need two pointers to basically go through this array one from the start and one from the end to check if each individual letter is a vowel or not and when it each pointer the start pointer and the end pointer are both pointed in a vowel that's when we'll make a swap so we'll make the start pointer be zero and the end pointer is going to be letters dot length minus one so that will be pointing to the very last index in the array and we're going to do this with a while loop so while start is less than end okay so while this start pointer is uh distinctly less than not equal to or greater than the end pointer because once they meet in the middle either equal to each other or they cross and we'll know we will have looked at all of the letters in the array so while the start is less than end the first condition we want to check for is if the letter is included in vowels and we're going to check both of them the start and the end pointer so if vowels dot includes and it's going to be letters at start and then we're going to do the we're going to say and do the exact same thing the whole stat includes letters at end so it's checking if both the start pointer value and the end pointer value in the array are vowels and if they are then we're going to use kind of the shortcut destructuring syntax which allows you to swap two values in an array so I'm going to go letters at start the letters at end so this is destructuring and we're going to swap those two things and letters at start and now once you've made that swap we gotta increment the start variable and decrement the end pointer so that they're moving in towards each other in the array so we'll do start plus and end minus all right so the next condition we're going to check else if is going to be I can just grab this copy this down if vowels includes the letters at the start so basically in this condition we're checking if the letter that is at the start index is a vowel but we're not including this second part the and so this would be the case for example if we were looking at right here in this the second example if I'm kind of on the second iteration here and we're looking at this e that's highlighted and potentially the end pointer is pointing to that D what we want to do is keep the start pointer where it's at but continue to decrement that end pointer until we find another vowel so we're simply going to do end minus in here and outside of those conditions else if your start variable or the start pointer is not at a vowel we want to keep incrementing that until we find the next vowel so at this point well let's go ahead and take a look see if we've got this correct console.log console.log console.log the letters array and we can check if we're at least making our swaps correctly oops what's the error here if vowels.includes letters vowels.includes letters vowels.includes letters at ends typo should say end right there okay let's show this again all right well we knew it was going to be the wrong answer but we take a look at the array down here we did in fact swap those vowels correctly so now to finish this off we should be able to do return letters dot join to join the string back together we'll run it make sure it's working with the test cases looks like we're good on these two test cases we'll submit and that works and gets accepted here so hopefully that'll make sense how we do that process this is kind of a useful thing to know how to do both the use of two pointers one starting at the end of an array and one starting at the beginning and moving in towards the center and also this if you've never seen this is a helpful little bit of syntax to use when you whenever you have to swap two values in an array so hopefully there are some things in this video you found helpful
Reverse Vowels of a String
reverse-vowels-of-a-string
Given a string `s`, reverse only all the vowels in the string and return it. The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. **Example 1:** **Input:** s = "hello" **Output:** "holle" **Example 2:** **Input:** s = "leetcode" **Output:** "leotcede" **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consist of **printable ASCII** characters.
null
Two Pointers,String
Easy
344,1089
394
Hello friends welcome to your channel today is our day 49 of challenge so let's go straight to the screen and start today's challenge so the number of today's question is 394 and the name of the question is decode string ok Yesterday also we had given some similar type of questions, basically it is going on the string, now we have some questions, yesterday we had given a little its opposite question, today we will see and understand what is it, okay, so let's go ahead, given n coded string is okay. Basically we have been given a coded string in a certain way. We have to encode it, that is, we have to bring it back to its original form. Return its decoded form. The encoded rule is of the encoded string and the encoded string inside the sequence is repeated exactly. K times Okay, note that the K is guaranteed to be a positive number Okay, we have to do the string from K times Okay, now you have unequal input string is always valid There are no extra white spaces Square brackets are well form one The debris string is in a well-formed structure. Okay, so in a well-formed structure. Okay, so in a well-formed structure. Okay, so we don't have any special issue with that thing. Now what to do is let's understand a little about the question. For this, let's take our example on our white board and if we understand further, then this is I picked up the part from here and took it directly to the new page. Let us understand that this is a very interesting question. We have given string A in the bucket and then B. What should we do basically like if 'Y' is written then it means which is dead. if 'Y' is written then it means which is dead. if 'Y' is written then it means which is dead. What will be the answer in that, twice B and Y N time, A and A, so if we have to find out the answer of Y, then this apple was quite simple. If you understand this in the example, then what is there in it and C, again it is okay, what is there in it? What has to be done is basically what has to be done in it like t time c is written so we have to convert it into what is c, after that what will be left of our string is 3ac c, so now we have to convert it to what is the number of times. Time A S And A Then this is the answer, the part A S A is also there, I hope you have understood what to do, we have it inside the string, okay, let's take another example, we took this example from lettuce. So see how if we don't have inner brackets then we can go on solving the outer brackets. A B C two times of E S three times of C S D and S D And e This is the answer or not A B C CD Yes CD And e Okay, so this was our answer but what is it, they did not give very good examples so that we could understand the question very well, so we Let's take some examples of our own, so let's go to the next page and take some examples of our own like I have taken t of a b of CD and I have written 'of e'. Okay, so I have taken this e'. Okay, so I have taken this e'. Okay, so I have taken this example like this, now what should we do? Basically, we have to encode it in such a way that if two off e is written then first of all the internal one e is to be solved, that is, after solving this, what string will be formed, our 2 off a off CD is two times e, so twice e. Write e, ok, after that, this bracket, I have solved this part, ok, now let's solve the inner bracket again, then what will become of a, then write as it is, ok, th of 3d, right? So D e again once CD e ok now we will understand its approach meaning keep patience a little question it is very important to understand then two of A B C means this same string now twice means what I did with this I would quickly rewrite it as A B C D E F S D E F then again Y was A B C D E F So I got this my answer. Hope so the question is understood, what is actually to be done in the question, okay, how to decode it, there are a lot of things that have to be handled in this question, okay, so for now I have given you the question, I hope, so you understood. If you haven't got it then go back and watch the video a bit, you will understand how it was done. Now I got to know one thing from this that first of all I have to solve our inner brackets. Okay, I hope this is clear to you. So what do I have to do, let's make an approach, I will go straight to this part, I will solve this problem on the next page, okay, so I will take this one to the next part, now see what do I have to do, basically what I have to do is to go while travelling. First this, then this, until I get the closing bucket, there is no e. Ok, ya gone here, but when I get the closing bucket, then I have to go back and first go to this string. The character that has to be made is so many times that the string should be repeated. Some kind of approach might be coming in your mind. Now we have to first push in the string and then take it out immediately. When this type of approach is made, I feel like this. Somewhere there is talk about the stack that first we will keep pushing them into the stack and then as soon as we come to the closing bracket, then I will keep on popping, while making the string while popping, I will get some kind of feeling, okay? There is hardly any feeling because its approach is like this, basically what will we have to do in this, nor will we have to make two statuses, okay, now let's go to the direct approach, how will we approach this, okay, now to approach this, you don't have to. What to do, first of all, okay, you understand what you have to do, in a minute, I will delete one part, okay, so we will get some string like this, what will we do, we will create two stacks, let's stick, okay, now there are many things in it. But we will cover it slowly and gradually, let us make two columns and one in which we will put all the numbers or whatever numbers come, we will put them all in a little while, in which the word 'actor' means string, in little while, in which the word 'actor' means string, in little while, in which the word 'actor' means string, in which we will put the string. So I make two stacks, make two boxes, first one in which I do my turn. Now as the first number came to me, I pushed T and said, but after that till the closing bucket comes, I pushed in the box, first I opened. Push the bucket and then push A, after that push B, after that the number came, so I pushed three here, after that an opening bracket came, again I pushed where and pushed it in my start. Then came C, then came D, then what do we have, T came, I take this part a little higher, okay, cut the current to D, I brought part Y, okay, and I cancel it, okay, what do I do? I have to do this, I took two to Y, it is a big example, I know, but it is easier, after that E and A and then one F, we pushed, okay, so I hope so, now I understand what I am, closing bucket, just like closing bucket. Will it come or not will I start what to do otherwise if it came we didn't have to push ok why did we push what we had to push then sorry for that I pushed by mistake ok now what do I have to do as soon as we have Here comes a closing bracket, a closing square, but then what do I have to do, till then I have to make a string B, a string will be formed, pop inside it, keep popping, what was formed first, F came first, before that, we will see this part, which method. It will take a lot of time from the front, so I popped both of them, while doing the popping, then I lost the last square bracket, so till now the stock is empty, okay, now come to me, okay, this part is part of this part. How will I know how many times I have to repeat the number stack? So I popped it from the number stack and repeated it twice. How will I repeat it? Now as soon as 'e' comes twice, as soon as 'e' comes twice, as soon as 'e' comes twice, I pop it again. Where will I push it from, I will push it inside my stack, the string one would push it inside the stack e and e, okay now see what to do, now I have pushed this part into the stack, now our loop will run again, closing again. Whenever the bracket and closing bracket came, what we had to do was to keep repeating until we got the bracket. Again we made a string and then made a string. First of all came e and after that d was added and next c was added. Okay. This part is very simple, we will do it, so we have done these three things and also popped the square bucket. It is very difficult to pop it, so after popping it, I have to see how many times I repeat it. If I have to do it three times then I will repeat it three times CD E F So what will I do now by picking it up and popping it also or what do I have to do after popping it or this whole part is done Put this whole part in the beginning again C D E F C D F and C D F A Let's put this whole okay now what then again we this one again ya what is our closing bucket whenever we get what do I do To check, I again created a string, okay, again created a string, created S again CD F then CD F and I had this part that came next to it and added what B and first of all B came. Now I have this string formed and till now our stack is empty, the whole stack is empty. Now what do we have to see, the loop is also finished, the stack is also finished, okay now how many times do I have to repeat it. So I picked up this part completely as it is. I picked up this part and repeated it as it is. So this is our answer. My approach is like this. Let's take a small example and maybe to make the approach. Have you understood, okay, still a b-end-of-CD, small apple, what to do now, or whether you are working or taking this apple, haven't taken it, stuck it in the email, repeat again and again, it may be okay, what should I do now? I will see, now what I have to do is that first of all make a stack, let's make two stacks, one with our numbers, one in which we will store the strings, no problem, it is very good, what did I do, here one Made a numbered stick here is a stringed stick. Now whenever I get a number, I will make a number, then I will make a numbered stick, then a character has come, there is an opening, so we have put an A, then A has also been put, B has also been put. After that came 1. Now, if we are traversing this 13 character by character, then how should I make this 13, we will see in the code itself. It is not a big thing, it is just that, I will show you. I wanted to know that this type of case can also happen, so I have to somehow put 13 here, so first I put 13, Y, 13, after that came an opening bracket, again I put an opening bracket, then came C, then came D, then came A closing bracket. Now as soon as the closing bracket comes, what do I have to do? First of all I have to pop, I have to make a string, while making a string, I have to make a pop, I have to make a string, I have to pop it, okay, then make a string, CD, first D comes out, then C. It turned out to be a rotten string and we will pop it too. Okay, we have popped the closing opening bracket. Now what do I have to do? How many times do I have to repeat this? 13 times, so I will repeat it 13 times. I hope you are understanding this. The thing is fine after repeating this string CD 13 times then I write it CD in 13 for now so that there is clarity and I picked it up *13 so that there is clarity and I picked it up *13 so that there is clarity and I picked it up *13 from here and also pushed it here and stacked it. Okay, now after pushing inside the stack, what do I have to do, I have to continue my loop again, then I went from here to here, then I came here again, closing bracket closing. As soon as the bracket came to us, what do we have to do, then again we had to pop it from the stack, so I said cd133, we already had it, that means CD is written 13 times, okay this is just written for the short form, then came a b, then came a. A has joined, I have to come forward and join, what happened after that, I popped this also, popped this too and one here we had the opening bracket, removed that too, now how many times do I have to pop this, I have popped 13. It was two times, so what did I do with it, A B C D in 1, is it something like this part of ours is done, okay, so now let's start coding the code, then we will do a dry run, then you will understand, okay code. A little bit first ho inger ta inger integer ger inger will call it number e nuc ok a string will be formed our off type str will be formed s this I call it main stc our main stc inside it the ctor will go to that main bo new ok I hope so the thing is clear How were both the letters formed? After this, what did I have to do? I had to travel in the string. The best thing about traveling in the letter is that we travel by making a loop and then make a loop for int and e0 and lesson ad let us plus this thing. Done, now I need a character, let's take out character c character, addot k at aa, so I have taken out the character too, now what is character, if it is a number, then how will we recognize that there is an inbuilt formula for the character number, this character dot is a digit or if this thing If we want to do no, we can also write the character directly, character e is greater than eg 0, it is fine, meaning if it is greater than the zero character and because look, the character which is one, the number which is one, is between zero and no. Lesson. When I said equal to no, then first of all I thought about identification, how would they understand the value, now what do I have to do, I have to see basically, till the number is not much, I felt very value and Chuck Kar I E Lesson Ad As long as A is small, we have to work and as long as that character is I, what is that character, it is a number, then we have to work in this loop, so I will check P addot K. At a dot sorry adot k at care at a is greater than means this condition is completely fulfilled I can put it is greater than equal to 0 and ns dot care a I must be less equal to no okay so I have put Y on First check that whatever is happening, now I have to make a number, how will the number be made equal to num in 10 plus, I said, first I have converted it into integer, it is ok, now this part is the one with conversion, we are in this video. We will discuss a little bit, we cannot discuss it completely because the question is not about conversion of string but how to convert string into character, that is fine. If you do not know this thing then you can write in the comment box. I will make a special video on it. Okay. I have done minus, I have done zero, okay, so we created the number in this type and whenever this number was being created, I said okay, very correct, now let's see how this conversion will happen, let's learn a little about it. From late, we have thaw and came first in character, we got it done from zero, it comes in the middle of na, one yes, so I got it moist treated from zero, it is okay, got it moist treated from zero, I got it checked, which is the value of aa, 0 ahi add. If there is still one, then this condition is obviously true. If the value of 10 is zero, then 0 * 10 value of 10 is zero, then 0 * 10 value of 10 is zero, then 0 * 10 0 plus add cut minus 0. What will happen from 1 minus 0? Whichever character was there will be given the injury 0 pv kitna hum me kya gayas ab me kya me ab me again soo now again soo chala ne now what should I do again sloo chala then what am I after Pk then I have given the condition also What would have happened if ps conductor mentor ir me p so I converted 13 after that what happened again aa plus became ya but now what happened aa p aa come here now what will happen after coming here let's see 9 Neither 10, 13, nor 10, the value of PS has become 131, it has become 131, now what to do, see now, I have to put this one thing in it, when I came in it, now I see this part, now I am in this character. Now what will happen if I go out of here, I saw that brother, this was equal to the character, okay, this is between zero and no, here, now we are here, so he saw that this part has come, so now what is this? As soon as you leave it, this thing will not come here, so A will not increase in the name because this condition is false, but what it will do is that by skipping A from here, I have to move A back, tell me that A is Don't stay, you come a little behind A. Okay, so I am telling A to come back a little, so what do I have to write for this? Write i minus p here so that it comes to the correct position, then again a. Look at the one which because of the loop, I will move ahead, in that my A would not have been skipped, that is why I am Aa minor and what I did, whoever became my number, I will push it, what number S, so number stack, dot push in the number stack, I pushed it. Given Nam So I pushed whom in the number stack My No In this way I have handled that thing Now Else If What can be the character If Not Equals Whose One of our closing brace's closing bracket Closing bracket's If Not Equals We did not have to do anything, we had to push it in the main stack, now we cannot push characters in the main stack because what type of main stack is string type, so I will have to convert the character to what type, in string it is character plus. I asked, then this problem came from it, main part else, if we have what is closing bucket, see these two numbers are not opening, if there is no closing bucket, it means is the closing bucket, the statement is ok, the condition, I also write the condition then. Condition then a closing bucket condition else but I have to condition then close or this is what I write For the two to maintain the loop variable To bring the loop variable to the right position I did this The variable is very fine so I wrote this Okay now what do I have to do Okay now whenever I have a closing bracket in me I have to create a string then I create the string attr mt kept okay now how long do I have to pop I have to do this until I get an opening bracket, while I wrote, pop from the stack until I get an opening bracket, okay, while the opening bracket, okay, until I get an opening bracket, okay, while the stack is here. Not equals to an opening bracket not of stuck ok now what do I have to put in T R so I wrote add po plus a ok what will happen with this the new character will come forward and get added ok it is quite simple i mean you will do a small witch So you will understand that from late we had ABC string, so A was inserted, B was inserted, C was inserted, it's a small one, okay, let's try it, for now the string was empty, C was popped from the stack, C came first, plus MT string, so what became C is formed, okay, after that came B, now plus B is added to it, then P is formed, then ABC will become a string. Okay, we have done this logic in this way, so I hope this part is also clear to you. As soon as we made the string, now we made the string, we made it, now look, the first thing we have to pop from the stack is an opening bracket, so I will pop one more time, why let's understand from 12, from lets we have something like this OK, so two will go in our number step. Then came an opening bracket. Then came a b c. As soon as the closing bracket came, we came here and made a track. ABC became a string here. ABC came, after that ABC came, we poked this from the stack, so this also got popped, so I wrote another pop, yes, but it is okay, so I hope this is also clear to you. In what way are we understanding the code together? It is not that we will understand the code together. We are understanding it simultaneously. Okay, pop it from the stack. After popping it from the stack, what do I have to do now? Basically, how many times do I have to repeat it? Take out that thing: Basically, how many times do I have to repeat it? Take out that thing: Basically, how many times do I have to repeat it? Take out that thing: Int Repetition Number Minute Repetition Number Where do I get the number Stuck So I wrote Number Stuck D Pop Number Stack Dt Pop I popped that put from the number stack How many times do I have to repeat Now look for this I will make a string builder why because what is happening again and again is the above mentioned task but there I thought I will be able to explain it to you better. But to explain a little, I have used that Equals to New String Builder. Okay, so we have created a string builder here, now the number of repetitions I have to do in it, what will I do, I will repeat, while I said repetition number is greater. Then 0 while repetition number is greater than zero till then what do I have to do A bud append I will append only that many times I will append SDR SR only that many times and by minus the repetition number every time I will minus the repetition number I will go, I will do minus every time, when this work is done, when I will have the string repeated again and again, okay, now what I will do is I will push inside the stack which is our main stack, okay main stack dot push would pick it up from here. Let me copy and paste it main stk dot push what str what will I push, this is A B which is made A B dot string, do not forget to convert it into string, it is very important to convert it into string also, we have used string builder. I converted what I made into a string and pushed it. Now when I pushed, my entire work was done. I wrote my entire logic. Now I have to create my answer. To create the answer, I again created a string builder. String builder answer equals to New String Builder Ok, I created a new string builder, let's keep it MT for now, what will I do now, I will keep removing things from the stack until the stack is empty and do something while the stack is dot size is Greater than stack size until greater than zero is greater than zero till then I have to work. Now see in which way ask answer dot insert now don't see how to insert. If I have to insert reverse to the starting position then I would say Keep inserting at zero position. Keep removing the stuck one and keep inserting. Okay, now if you have any doubt then keep patience for some time and everything will be understood. The code is quite big and there are quite complex questions in our answer. Ban Written Answer Dot is ok, now everything looks fine in the code, I will run it once and see if there are some issues, then here some people are telling errors. Edit is ok, but there is no big mistake on this. It keeps happening and some canon find is not added, but what do I have to write on this, I am fine, apart from this I have ticked which liner is telling this in the very summary line. But after C, I wrote the dot size, but even after the main score, I hoped, so to do this, the name of the main table itself was a little mistake. Do it, okay, I made a mistake on the proof. Dep, which was a correct function, I had to write dot. Equals d equal whose exactly one of my opening buckets is equal to one of the opening buckets till then I have to do this thing again and again while doing a little bit of mistake three buckets are the main bucket ok now ok maybe ok this code is enough It is going well, please submit, I deliberately did not delete the debugging part, it is okay, I reshoot the video, the reason behind it, because you people should also know how to debug the error after seeing it, I want. So I could have made another video but I did n't make it because I know it's okay, mistakes can happen to anyone, it can happen to me, it can happen to you too, so there is no need to be afraid of mistakes, when they happen, there is no need to be afraid, mistakes mean it's okay. Do it okay, it doesn't mean that you have become de-motivated or I am mean that you have become de-motivated or I am mean that you have become de-motivated or I am not able to do it, no, sit comfortably and do the de-fuck, just stay calm for sit comfortably and do the de-fuck, just stay calm for sit comfortably and do the de-fuck, just stay calm for a little more and keep doing the de-fuck, okay then a little more and keep doing the de-fuck, okay then a little more and keep doing the de-fuck, okay then look, it is submitted now. Let's go straight to the try run. Well, we can do the try run here too but we will not do it here. Let's take the code from here. Okay, so if I skip this part a bit, let's take it here. Do to New. The page is fine, it was pushed till the main stack, till now the code has come, what should I do, one second, some issue came, but we were till this, now what to do, I have to pick it up from here, okay, so the complete code is picked up from here. Let's take the complete code of D2Current or complete it in this way. I hope so you can see it bit by bit. Now let's take the applet and T of A, B and T of C. Let's see how our code will be formed. Okay, let's go. First we create a pointer, the I pointer which is here, okay and let's create two stacks, one number stack and one of ours. Let's make stacks for a minute. Well, this will become one of our number stacks. So this is one of our number stacks. Name. Stuck and this is our string stuck and hope you know what to push and the first conductor came, what number do we have, yes, we did this, but I am not explaining this part again because I explained it earlier, okay, so push directly. So I got T to push, we were like, after that we got an opening bucket, or after that because there is an opening bucket, we went straight to the main stick and got pushed, then came to us, A, then we pushed A also, then we got Pushed B also and then came to us U We pushed and then came to us C again came to us Bucket A Open bucket again came to us C We pushed C also and then came to us It again came to us Main Part of What have we got, we have got this part, now let's enlarge this part a little bit, now the main need of this part is to make it overall, now let's see what will happen now it is saying make acer st, after making the M string, puck main from the main st. Keep looking at the peak of the stick and if it is not equal whose if our opening square bucket then pop it, first I popped it again, then C popped it, then we have pop it then pop it, first I popped it again, then C popped it, then we have an opening bucket, pop the opening bucket as soon as it comes. Till it pops, I would have canceled it, we would have understood, we did till now, what to do now, I have to find the repetition number, I have got the repetition number, I have come to this, now I have made a builder, I have made it, but whatever its meaning is, this So I said, as long as the repetition number of my G is greater than zero, then what should I do? How many times should I append the CD, then one more time, CD, then CD is appended, okay, the repetition number will be minus, push it into the main stick, then Push one CD and then push one CD. Okay, so I hope you understand. Now the loop will run again. The loop is running. Continue, our loop is running. After the loop is running, we are here. But after coming here, what do we have to do? Again the closing bracket comes. Now whenever the closing bracket comes, what we have to do is to create a string. Okay, so all this was deleted. Create a string again. We have made a string SR, what have we put in it, from the main stack, keep checking by going to P peak P, till this bracket of ours is not the opening bracket. We first made CD, after that BA, this is the string. Ours became quite correct, after that we popped this too, after popping all this, did we have this? After this came to us, we removed 'th' this time in the repetition number. we removed 'th' this time in the repetition number. How many times will it become A B C D A Again A B C D Once again A B C D What has become of me O what has become of us is ours By becoming the main stack, push it into the main stack. I have pushed it into the main stack. We have also pushed it into the main stack. I am not eating it directly. Okay, it fell into the main stack and it has also eaten this stack. Now we are done with the loop. After coming here, the loop will end. Now let's extract the answer from the main stack. See how the answer was created. If you push it to the answer dot insert zero index, then this entire answer becomes mine. Let's see whether this will become the answer or not. First of all, our If I solve the inner bracket, what will become A Sdi and I have to repeat it three times, okay so A B C D, okay A B, two times A B C D and A B C D So we got this answer three times, so I hope you must have understood it very well. If you have any doubt in this case, you can ask in our telegram channel and keep replying to us. And the challenge is going on. So good tomorrow our 50 days will be completed. When we do tomorrow's questions then it means 50 days will be completed and you have done 50 questions not quote so it is a moment of happiness so everyone means tomorrow so share very well. Make sure that our 50 days are completed. If our challenge is okay then it is okay to share it very well. I hope you guys will share it very well. So see you guys tomorrow where we will be meeting for the next question. Saath to till then thank you and go for it questions kar hai to thank you
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
126
welcome to january's liko challenge hope you all are having a great 2021. uh today's problem is called word ladder now given two words begin word and a dictionary word list return the length of the shortest transformation sequence from begin word to n word such that only one letter can be changed at a time and each transformed word must exist in the word list so if we had two words hit and cog we are able to change one letter and if that letter is inside of our word list we can move to that letter and then we can continue on the algorithm until we hit cog here we can see we can go from hit to hot to dot to dog and then to cog which is going to return to us a length of five it's done four steps but there's a total of five words inside of our i guess path so this problem is basically a graph problem right we want to have some sort of graph probably a dictionary with the word as the key and then a list or a set for that matter of all the words that it can go to and those words are all going to be inside this word list and only have one character uh difference so the main part that we want to figure out is how do we figure out if two words only have one character difference so let's go through our approach we do have some constraints here the most important one to note is that the length of each word inside of our word list and our begin word are all the same so i think we can assume that we don't need to worry about length of the words they're all going to be the same so the very first thing i want to do is write a function to check if only one character is different okay once i have that i'm going to create my graph using that function then i'm going to do a breadth first search here using a cube and if we are able to find the n word we can find n-word then return we can find n-word then return we can find n-word then return the number of steps that we took to get there um and we'll have that inside of our queue so we'll track that inside of the queue here right so very first thing is to write our function and we'll call this one character and we'll have input two strings now um the first thing we want to make sure is that they're not the same because we don't want to end up adding in a word that's the same because you know i don't know all the characters are matching so instantly if we say all right s equals t then just return false immediately now otherwise what i'm going to do is go through for i and range of the length of s and i'm going to make the assumption that all these are the same we want to count how many characters are different so here i'll have a count and start with zero and we'll say right if s of i does not equal t of i then increase our count by one now finally we just want to say hey is the count equal to one and if it is then we can assume that with these two strings only one character is different so that means uh their you know transformation path is acceptable so okay so now we have this function and now we want to create our graph so i'm going to call this graph and we'll make this a default dictionary make it a list or we can make a set but i'm going to make a set here now for let's see um wanna make our dictionary so for all the words i guess i'll call it s in word list and one thing to note is i'll actually have to add this begin word here if you look at this example you can see that the word hit is not inside of the word list um but we need to add that into our graph or otherwise the algorithm wouldn't work so what i have to do is say put that begin word right here and then we'll say for t same thing word list plus begin word we're going to say if one character only one character is different then we want to add to our graph the s and we're going to add the t which is going to be one of the words that we can travel to from this word so it's kind of like an adjacency list but it's a graph right now for our bfs and to do that we want to start off by creating q call that eq and we will make a tuple of the word and the number of steps that we've taken so far so here this would be what the begin word it's all right and so far we've taken zero steps and keep a note we need to also have a visited hash i'll make it a set to make sure that we don't get into any infinite loops so if we've visited this node or this word before then we don't need to continue the algorithm because we've already been here there's no need to there's no path that's going to make us go back like repeat the same node okay so now we want to do our bfs if i should say while q first pop off our candidate i guess should i call this um i call it node and step equals q dot pop left all right so what do we need to do here first we need to check have we visited this place before and if not then we could add to our queue so if node not in visited i suppose we're going to add it first and we want to add all the places that we can travel to that's going to be for i call it next in graph of node add to our cue a tuple of the next note and the number of steps that we took plus one now i should probably also add uh if not if nx is or not in visited just in case we've already been here um yeah it'd be the same issue like we've already been here before uh we don't want to actually add that again because that's just a waste of time so we'll do that and i should also believe add we need to check here right if the node is equal to the n word then we're done so all we need to do is return these steps uh but we're actually gonna have to add one here because uh we want to return the total length not just the number of steps that we've taken the entire length otherwise if we can't find anything we get out of this loop then we return a zero because suppose this algorithm isn't possible so let's see if this works may have forgotten stuff so let's check okay that looks like it works and i would submit this but i already know this doesn't work this would it's going to hit a time limit exception and the reason for that is time complexity wise we are going to do a n square right because we have a nested loop here for all the words in the word list or list so that's n squared times m which would be the length of the word and that apparently is too long imagine that some of our test cases have a word list that are humongous right thousands of words um yeah i could go to 5 000 well then this is going to be a huge amount of time to take right so what can we do here because we lose a lot of time creating this graph is there a better way to do this well there are a couple ways but one way i thought was pretty clever we could create a string right and we'll call this alpha and have every single word abc e f g h i j k l m n o p i q r s t u v w x y z and what i'm going to do is instead of doing a nested n for n squared i will instead go through each character inside of the word and check all the different letters like try to check every single different letter inside of that word so if i had the word like uh abc then i'll check uh starting with the first letter i'll track okay bbc and then what about cbc dbc so on and so forth and then also check the second character which would be like abc so that would be aac abc acc and so on and so forth and depending on how long the word list is this is actually going to be faster because this guarantees only 26 characters so in total it would only be n times m times 26. so how about we do that let's forget about this algorithm here and try to instead create every possibility check to see if that's in our word list and if it is then add it to our graph um so let's get rid of this is not very efficient what i'll do is have a word set which is just going to be a set of all the word lists and i need to add again the begin word and let's see we'll do the same thing here and now for say i in range of length of s we are going to create some temporary strings and try to um create like all the possible difficult combinations inside of uh our alpha like changing each character inside of a word so what how we can do that is let's take our word and we'll say um let's see for s in word 0 to i and p2 will be s uh plus one all the way to the end now we need to go for all the characters inside for alphabet so we'll call this a in alpha and we're going to create some temporary strings here and say all right temporary will equal to p1 plus a plus p2 now if this temporary is in the warts set and make sure that's not equal to the s that we're checking now then we'll add it to our graph we'll say okay add to our graph the s add temp and this graph is going to end up looking the same it's just that time complexity wise uh depending on how long this word list is this could be faster everything else should remain the same this algorithm should remain the same so let me see if this works okay looks like i messed something up let's see here let's take a look at what this graph ends up looking like and i may have just messed something up hmm okay so it does not equal yeah so that's i felt okay that looks better and it looks like that's the answer so let's get rid of this let's try submitting that and there we go accepted yeah so time complexity wise this would be n times m times 26. now there are some other ways we could do it the solution here they give you is a little bit different but they use a mask and they use that mask character where they i think use an asterisk in each side of one of these characters and use that instead to indicate to us whether we can go to the next one or not and that works too i believe that time complexity is like m squared times n or something like that um but you know what like i like this solution because it's easier for me to understand using masks kind of got confusing so i think both are acceptable and that's that so thanks for watching my channel and remember do not trust me i know nothing
Word Ladder II
word-ladder-ii
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 _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`. **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\] **Explanation:** There are 2 shortest transformation sequences: "hit " -> "hot " -> "dot " -> "dog " -> "cog " "hit " -> "hot " -> "lot " -> "log " -> "cog " **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** \[\] **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 5` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 500` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**. * The **sum** of all shortest transformation sequences does not exceed `105`.
null
Hash Table,String,Backtracking,Breadth-First Search
Hard
127,2276
1,284
hey welcome back today we're going to continue our journey to bfs so we're going to talk about this minimum number of the flips to convert a binary matrix to zero matrix so basically the question is asking you have a matrix and m times n and in one step you can choose one cell and flip it with all the four neighbors as long as they exist so flip is means that you change one to zero or zero to one because we have binary matrix the binary matrix is defined as a matrix with each cell is either equal to zero or either equal to one and return the minimum number of the steps required to convert the matrix from the converted entire binary matrix to a zero matrix and return negative one if you cannot and zero matrix is a matrix with all cells equal to zero so basically you have a binary matrix you wanna convert that to zero matrix and at each time you can pick a cell and then you can convert that particular cell from zero to one or one to zero along with all the neighbors one neighbor two neighbors something like that so we can check one of the example right here so the first step one of the possible solution is we can convert a 1 0 is this guy so we can convert this guy flip this guy so this will become 1 and its neighbor will become 1 as well and his neighbor is going to flip from 1 to 0 and then we're gonna have one zero something like that so the next step we'll do is zero one so zero one will be right here oh i'm sorry is that right here yeah it's gonna be right here so this will become zero and this could come on and the neighbor will become one as well so we're gonna get something like this and then one will be here so once we convert one and everything will become zero and bingo we got a zero matrix so it looks super hard so we don't know like where to start and uh actually the crux of this particular problem is you scroll down and check the size so m will be between one two three and n will be also between one two three and the size the sample size is like super small and that's why we can just use brute force to solve that so we can use either the fs or bfs so i think the best way to do this is by using bfs because we uh the converters between all the neighbors right and um yeah so we are we're just gonna try out everything so uh shouldn't be super hard but some tricks uh within it right so let's go ahead and write the code and so we're going to get out of boundaries we're going to get the rows and the columns and we're going to get uh okay so we're going to define the queue so this is going to be double endicum in python so we're going to have a dq and we're going to have the initial position in it actually the initial node the node will be the entire matrix so let's put the matrix into rq we also need a visited so which is a hash set to recording whatever the value or the state we already computed so we don't have to like recalculate it again and then so just like before oh by the way so we need a step so staple stands for how many steps you are taking how many layers we went before so we are dealing with one layer at each time so that's why we're gonna have the size and calculate the size of the cube now each time we're going for the entire layer and for uh in range we're not gonna use i we're gonna use a random variable that um we don't need so we're gonna oh sorry so we're gonna do it for the size of the queue and each time we calculate we pop out the node the matrix from our queue and we're going to do some processing for the node but so before that we always check the terminated position so if we want to see if this is the terminal position and we're gonna check if this guy is already a zero matrix so the property for zero matrix is that we take all the summations so this is a list of lists so we check each of the list and we take the sum and then we take the sum for all the sum of the sum and we check hey if this guy is a zero so if this guy equal to zero that means we already have a zero matrix so basically map the summation function to a summation function to the node so that makes all the internal list become sum and then we take the sum of this list and then it become the sum so if this guy equal to zero perfect so we already reached the terminal position but if not so we're gonna do some exploration so what's the acceleration we're gonna do so we're gonna go through every single coordinate this guy every single one of them and then flip this guy and along with these neighbors and then check if we can reach the terminal position or not so the way we do that is we calculate a new node how do we calculate the new node i'm gonna do it later so i'm gonna call it a separate function and i'm gonna put the coordinates in i'm gonna put uh the matrix in so the reason i wanna do that is to make the code cleaner and uh this is super simple so i'll show you guys later and also we want to check if the new node is in the visited or not so we actually cannot do this directly because we have the list of list or either list and as long as we have a list that we cannot put that into hashtag and we have to convert that to something like string or tuple so i'm gonna convert it to tuple something like this so this is gonna be new node and you know it's easier to retype it actually all right so we convert everything to tupo and we call this guy hashcode hash node okay let's put it in the score right here so we're gonna check so if the hash node is already in the visited so you already calculated so you can skip that and then the node will be adding the new node and visited will put our hash node in perfect and then so once we finish the for loop oh you know what i'm i think i'm missing something so uh instead of the flipping right so i need i and j so for i in range of m for j in range of and i need to flip every single spot so i forgot to put the values so let's put everything into the for loop and so once we finish the both for loop so because this photo is for each layer so once we finish the entire layer and then we can put step okay so now should work is a matched order okay uh i really can't tell actually so it should be matched uh and then once we finish the while loop and we can return actual 1 and then we can start writing the flip function will have our node so which is the matrix and also the inj which are the coordinates and we also need this part the boundary once we get the boundary and we can start writing this copy the deep copy we need the copy of the value instead of the reference so that's where you're going to use the library and once we have the results and we're going to flip the current value and the way we do that is taking the xor and once we take the xor and if it's 0 it will convert to one if it's one you can't do zero and we're going to calculate all the four directions for the x and oops d y in all so we can go up down left all right perfect so uh we're gonna have all the four directions and then we're gonna calculate the new coordinates the x and y will be equal to j plus d y and if uh the x is less than zero or x greater or equal to m or y is less than zero or y is greater or equal to n okay so we cannot do anything about it we're going to just to continue otherwise we do x and y will be extra one as well and then we just return the results and that should work so basically we are just flipping this particular node and we also flipping the entire all the neighbors so once we do that we return to final results which is a new node and once we got a new node and we'll push everything into the queue as long as we never visit this before and then we can check if the final result works perfect works so basically this is a solution by using the matrix manipulation so we can also use uh some optimization so maybe i'll just talk about it in the future videos okay i'll see you guys in the next video then
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
four-divisors
Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge. Return the _minimum number of steps_ required to convert `mat` to a zero matrix or `-1` if you cannot. A **binary matrix** is a matrix with all cells equal to `0` or `1` only. A **zero matrix** is a matrix with all cells equal to `0`. **Example 1:** **Input:** mat = \[\[0,0\],\[0,1\]\] **Output:** 3 **Explanation:** One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown. **Example 2:** **Input:** mat = \[\[0\]\] **Output:** 0 **Explanation:** Given matrix is a zero matrix. We do not need to change it. **Example 3:** **Input:** mat = \[\[1,0,0\],\[1,0,0\]\] **Output:** -1 **Explanation:** Given matrix cannot be a zero matrix. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 3` * `mat[i][j]` is either `0` or `1`.
Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors.
Array,Math
Medium
null
47
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video so this time guys we are using another backtracking question called as permutations two it is question number 47 of lead code and a medium level question today we'll solve it right here in this video and guys as always i want to request you to subscribe to my channel hit the bell icon for future notifications write down in the comment section below anything you want to say to me give this video a big thumbs up share it with your friends as well and now without making any further delay let's get started with the problem statement so guys if you have seen the permutations uh first question video then i would recommend you to see that first but it is similar to that basically we have got an array of numbers here and we want to return all possible permutations of this array of numbers the thing is unlike the previous question we can have duplicate elements in this array for example one is repeated twice in this array so if you know a little bit about mathematics you know that the permutations of uh n elements is n factorial so because we are having three elements ideally we should have six permutations right because three factorial is six but why we have only three permutations because two numbers are repeated here so if i start with this one i get one combination 1 2 but if i start with this second one and i start to make permutations i probably will get the same permutations which i got with the first one so that's why if we remove the duplicate combinations there are only three unique combinations we will get one two one and two double one so we have to find out all the unique permutations unique uh permutation combinations the constraints are that the length of the average from one to eight and the number could be minus 10 plus 10 and now let's get started with the solution part so guys as i told you before we are going to solve it using backtracking so here is a little bit of approach how we are going to solve it so first of all guys as we know that we are having duplicate elements in the nums array so the way to only take unique elements is by first creating a hash map so what we are going to do is we are going to store the numbers and their occurrences in a hash map and once we have stored that in a hash map what we are going to do instead of permuting the elements because you know if you are using our normal permutations if there were no duplicate elements we could have just uh done the permutations of all the elements in the array but instead of doing that we are going to do the permutations of the hash map keys and we are going to continue to uh include those hashmap keys until their occurrences or until their frequency is you know completely finished inside that map so limitations of hashmap keys until their frequency or count is set to zero so once all the keys are you know completely all the keys and all their counts is zero that means that we have got a list of integer having the perfect combination for us so once you have got that list what you do you simply store the copy of your temp list in your result so uh just like that or we'll you know if we continue to perform these steps finally we'll get a list of list which is having all the uh unique permutations okay so uh this will be much more clear to you guys when i start writing the code so let's get started with the coding part of it okay so the first thing is that we have to store the numbers and their occurrences in a hash map and we will also uh declare the result set and the temporary list okay so list integer result is equals to new arraylist so first of all we will declare the result variable which we have to write on then we will declare the temporary list the initial temporary list which we will be storing in the result error list so let's make that declaration is equals to new arraylist and now next we will create a hashmap of integer t and integer value to actually store the numbers inside the number array and their occurrences the total number of count so let's say count map equals to new hash map and there we go guys you can see that now my hashtag is create a declared what you have to do now is you have to start filling this hash map so for integer i equals to 0 to i less than num sort length i plus first of all we will check if the map does not contain this particular number if count map dot contains key nums i if count map does not contains i in that case we will put a key inside the map so put nums i and initialize the value or initialize the count to zero and once we come out of this if statement you will simply increment the count which is place for that key in the map so count map count math dot put num psi and the value will be count map dot get nums i plus 1 okay so now once this for loop is completed your hash map will contain the key as a number and the value is the number of occurrences and uh now we will actually instead of calling the dfs function we will first implement the dfs function and then we will call it in this main function so let's create a dfs function private void dfs and in this dfs function we will simply pass the result the temporary list the hash map and the numerical area so result and your temporary list and your hash map that is count map and finally the and now let's get started with implementing the dfs function first so first of all guys you simply check if the stamp list is having the exact name or number of elements as the nums array so if the templates are size is equal equals to the num star length if that is okay that means that our templates is full that means we have got our permutation so simply do result dot add new array list and you know add this temp list here and once you have done adding it you can return on it so this part is done guys now we have added our temp list this is our base condition that uh base condition is done if the size is equal to the length we have got a permutation but in case of base condition is not done what we will do we will start iterating the entries of this count map so what we will do map dot entry and count math dot entry set and this will give us the entries inside this hash map so first thing is we will check what is the key value that is entry dot get key second thing we will check what's the value of that key is equals to entry dot get value and now we will simply check if the value is equal equals to zero so if the value is equal to zero that means for that particular number the num the count value has become zero so that means that number has been included enough times in our permutation list so that's why if that's the condition then we will just continue and we'll go to the next entry of the map but if that value is that key is still having some value in that case we will add it inside our template that means there is still uh you know for example like one is occurring twice here so if the count of one is two that means there are still some ones left to be included in our temp list if the count of one is one that also means that you can still add some ones to your temp list if the count of one becomes zero that means you can not add further one city or temporary list so that will happen when we'll go inside this if condition and we will simply continue but other than that we can add that value sorry add that key inside our temp list because uh it is still having some frequency left some occurrences left and obviously guys once you have added it inside your temp list all you have to do is you have to reduce its frequency into your map because it has already been added once the key comma value minus one now you have reduced its frequency inside your count map so you are now ready to call the dfs function again as a recursion call and pass all the same things result temp list and count map and the nums array now i'm sorry okay so once you have gone through the depth first search for that particular key now you can simply remove that key from template so templates dot remove templates dot size -1 so now you can templates dot size -1 so now you can templates dot size -1 so now you can remove that key and also you can put the same value inside your count map okay so this was our dfs function guys now we have created this function so it's time to call this function inside our permutate unique method so all you have to do is pass call the dfs function pass result pass temp list pass count map and you know all the necessary arguments nouns and finally after this entire function your result will be populated and you can return it using return result now let's run this code guys and let's see if this works okay so we have got a little bit of error here so the thing is that i used sorry i used a primitive data type so you have to use an integer here integer because get k is an integer value okay and yeah also you have to put here integer actually if you do if you declare this as integer you don't have to declare uh key and value as a you know class object classes you can simply make them primitive because i didn't mention it integer here that's why i was giving getting that error so now you can see that my solution is accepted guys let's submit this code just to see uh that it gets accepted for all other test cases as well and there you go guys you can see that now my solution is accepted for all other test cases so uh that was a solution for this question guys i hope you guys understood this video and you learn something from it if i talk about the time complexity guys so the time from let's see what this question is very complex but as far as i have observed the time complexity should be something like order of 2 to the power n because we are calling the recursive function but because we are calling it n number of times so it could be dot n because we are also creating a hash map every single you know every we are also creating a hash map first so that's why n into two till five n but to be honest i'm not sure about this uh other than that if you talk about the space complexity definitely space complexity is order of n because you are creating a n element hash map okay so that was the video guys i hope you guys enjoyed this video and learned something from it if you guys have any uh suggestions for me if you can explain the time complexity of this question better than me then please do write down in the comment section below i think everyone will benefit from that and thank you so much for watching guys uh please do subscribe to my channel hit the bell icon for future notifications write down in the comment section below anything you want to say to me give this video a big thumbs up share it with your friends as well um thank you again and i'll see you guys next time until then bye
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
48
Hi Everyone Welcome Back to My Channel Today is Day 41 of our 75 Days Coding Challenge and the coding problem we are going to solve today is Rotate Image I mean the image we have given is in the form of a D array. And we have to rotate it 90 degrees, so let's see what the question is, how we have to solve it. Start so A by A, we have been given a D matrix, its rows and columns are the same, its length will be Same will happen and you have to rotate the image in place which means you have to modify the D matrix itself. We have to modify the assisting D matrix only. We cannot take any extra memory. We are going to create another matrix. Nt So if you see from the example, what do we have to do in this, tooth it should come here like this, if you see, you will rotate it 90 degree like this, then you will come in this form I mean it will reach here 456 will become Like this 789 become like this okay so there is a solution to this that first of all what we can do is change it to its daily co let 143 sorry 147 you can change that here then if you are looking at 147 if you Change it to 147. Sorry, if you want to change the rows in columns, then what will be 147? This line is its reverse, so it will be a two step process. We will first replace whatever column is there with its respective row. We will swap and after that our rows will be formed and sorry, our columns will be like this is our one column and this is our eighth column so we will replace one with N and we will swap again and this will be of middle so we will leave it. Because n we will run the loop only till the point and here if we talk about this then we will change this column with this column and this column will be changed with this column means first is set to n second and your th is n mite, we will replace it in this way, so I have done a dry run in it. Already in this first example, if we talk about this example tooth 4 5 6, then I have said that earlier we have done all the days. Let's swap the rows with columns. Okay, so the first step, what's happening? We swapped the teeth like this, Is a row converted into column 456 Is a row converted into column 789 Is a row converted Into this column OK, after that the second step is now this column has been replaced with this column, 789 will come here and 456 will be in the middle and your tooth will go last. This is our first column and this is our eighth. Column right so this becomes our a column if we talk here this will become our first column this will become our a column this will become n my column this will become our second column so second to a to first to a to like this We have to change it to swap it, so if you see this output and you match it with this output 741 852 963, then it is the same, so it is a two step process. Similarly, if we do a dry run of it after writing the code, then Let's first write the code so this is a two step process right step one we can write let's say swap rows with columns ok and then we will have step two swap like this let's say no with a columns one with A tma n mive 3 a minus 2 and so on okay this way we will spa that so the first one we do spa rose with column rose has to be spade with column now what do you do in this n ba a He has said that if our D matrix is ​​of n Ba then how will we get the matrix is ​​of n Ba then how will we get the matrix is ​​of n Ba then how will we get the matrix dot length ok so because n is Ba A then both will be same now you will have to run double loop how to swap the rows and columns Right D is the matrix row aa What do you do to do lesson a and j pps In J you will assign J and I and then in J and I the temporary simple spring is done in three steps so this is our first step sp rose v column okay now what is the second step our f loop a less a Aa plus here in a little second here we will start from J E G and where will we go we will go n batu tak because columns jo hai hamare woh ab first ko last se second ko a mive se and then sorry third ko From A min, you will go only till half, you cannot go till A, otherwise it will again become the same D matrix. If we take the total till A, then what will we have to go, divided by two j pps in this also. What will you assign in the same temporary we will have matrix i j and then i j? What will remain of the last one in the first one? One minus w will run t minus h and your in this one you tap right or you swap columns then first swap is swap rows with columns second step is swap the columns first with last and so on let's run and see accepted very case Passed, this one and this one, both the cases are passed. Okay, let's submit and let's see. All test cases are correct. So now we pass this one. Once this one is the example below, we also dry run this one. We have written the input, the first one which is given, what do we have to do with it now, we have to change it every day with columns, okay let's make a copy 4 ba f sorry four yes it is 4/4 okay so what will come in it f we do it everyday. In the columns 1 or 11 and to we did this here we do this here 2 4 8 10 13 3 sx se 15 14 12 and 16 Now we have to swap the columns okay like this so a 4 by fo ka again you make it so We are changing this column from the last column 15 14 12 and 16 OK and our Y one will come in the last one 11 and this one will come in this 13 3 s se and then 2 4 8 and 10 so we will see this one which Our D matrix is ​​this one which Our D matrix is ​​this one which Our D matrix is ​​this one and this one matrix is ​​the same, and this one matrix is ​​the same, and this one matrix is ​​the same, okay 155 16 11, you match like this 155 16, everything else is the same, okay, so we have dry run this, we have also executed its program, this is why we call it I Hope Images. These are because images, whatever they represent is always represented in the form of D array. Okay I think we are good so if you like the video please like share and subscribe the channel thank you.
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
94
hi everyone in this tutorial let's discuss what is in order traversal and how we can implement them using iterative and recursive approach in my previous video tutorials i have already covered two t traversal algorithms one is level order traversal and other is pre-order traversal is pre-order traversal is pre-order traversal and the link of both the video tutorials are present in the description box let's understand what is in order traversal we first traverse the left subtree of root in order so we first traverse the left subtree of fruit in order then we visit the root and after that we traverse the right subtree of root in order so given this binary tree let's uh traverse this binary tree using inorder traversal and let's see its output let's start with the root node in order traversal we first traverse the left sub tree of root in order fashion then we visit the root and finally we traverse the right subtree of root in order so when we start from the root we first go to its left subtree now for this node we go to its left sub tree and for this node when we go to its left sub tree it is null so we come back to the root node and we print its value then we visit its left its right sub tree which is also null so we go back to this node and we print its value and then we traverse its right subtree for this node we first traverse its left subtree which is null we come back to this node we print its value we move we traverse its right sub tree which is also null then we have traverse the left subtree of the root so now we print the value of root then we traverse its right subtree for this node we visit its left subtree and for this node we visit its left sub tree which is null so we print six then we go back to this node and we print its value for this node we traverse its right subtree and for this node we first traverse its left sub tree which is null then print the node value and then traverse the right subtree which is also null so this is the in order traversal of this binary tree let's take one more example let's do the inorder traversal of this binary tree so let's start with the root for this root node the left sub tree of this root node is null so first we visit the root node which is one then we traverse its right subtree so we move to this node and from this node first we have to traverse its left sub tree so we go back go to this node three and for this node its left sub tree is null so let's print three after that we have to traverse its right subtree which is also null now let's uh go back to the uh node 2 and let's print its value and after that we have to traverse its right sub tree which is null so this is the inorder traversal of this binary tree now we understood what is in order traversal next step is to implement them using iterative and recursive approach so we will start with the iterative approach first so here i am going to use stack data structure so let's first declare a stack which is empty initially so uh let's declare a stack and then uh in order traversal we have to first traverse a left subtree so let's put the value of a root node in a stack so i am putting this node in a stack so let's put one in a stack and then visit the left subtree until it is not null so from one we visit two and for two we visit four then when we encounter null when the left subtree is null then pop the value from a stack so when we visit the left subtree of this node it is null so what we have to do is we have to pop the value from a stack so we pop this value from a stack we add the value in our result list then we have to traverse the right subtree of this node in order and the right subtree is also null after that the next we have to pop this node first we have to add its value in a result list and then we have to traverse its right subtree in order fashion so for the right subtree we go to this node so we put them in a stack and after that we traverse its left sub tree first and its left subtree is null so what we have to do is we have to pop this value from a stack we have to add this value in our result list and then we have to traverse its right subtree in order fashion and its right subtree is also null so first you can see this code and then we will further dry run this code initially i have declared a result list which holds the value of integer types then i have declared a stack which holds a value of tree node type and i am running this loop while the stack is not empty or the root the current value of a node is not null so first we have to traverse its left subtree so we keep visiting the left subtree until it is not null and subsequently we push the value in a stack then once the left subtree is null then we pop the value from a stack we add its value in a result list and then for the current node we set its value equal to its right child so that we can also traverse the light right subtree in order fetch and for this node in next iteration we do we traverse its left and right children in order fashion so uh let's start with this node you can see uh initially when root is not null we first add one and then we assign the current node to its left child so we move to 2 again we add 2 and then we move to its left child 4 and we keep doing it until it is not null and after 4 we add 4 and we move to its next child and after that this is null so the left child of 4 is null so we came out of this loop we pop the value which is present at the top of a stack so at that time 4 was present at the top of the stack so we add the result add its value in a result list and we assign its right child and in next iteration you can see its right child is also null so we pop the next value which is present at the top of our stack which is 2. we first add them in a result list and then we take its right child and its right child is 5 and in next iteration you can see 5 is not null i mean this node is not null so we first push them in a stack and then we take its left child and in left child it is null so we again came out of the slope uh this loop we pop its value we add the value in a result list and then we assign its right child so in next iteration so now its right child is null we came out of this loop and we popped the value which is present at the top of this stack and the value which is present at the top of the stack is one so we pop its value we add in a result list and then for the current node we assign its right child and its right child is this three so in next iteration this node is not null so we add its value in a stack and then we take its left child now for left child we add them in a stack and again we take its left child which is null so we came out of this loop we pop its value so we pop its value we add them in a result list and we take its right child so in next iteration again it's right child is null so this loop will not execute we pop the value which is present at the top of the stack which is three we add them in a result list and we take its right child and its right child is this seven so in next iteration this node is not null so we push them in a stack and we take its left child is null so we came out of this loop we pop the value which is present at the top of the stack we add them in a result list and we take its right child now this time if you see the stack is also empty and the root is also point to the null so we came out of this loop and we return the result list and the result list is this so this is how we can implement in order traversal using iterative approach now let's talk about its time and space complexity so its time complexity is big o of n and its space complexity is also big o of n so now uh let's implement in order traversal using recursion and reque writing recursive code is pretty straightforward uh let's write it here is the recursive code for in order traversal this is the main method and from here i'm calling this in order helper and in order helper if the root is null we return else first we traverse the left subtree once we're done with the left subtree traversal we add the value we add the root value in a result list then we traverse its right subtree and in recursion whenever a function call itself all the calls are put in a call stack so you can imagine uh let me draw a stack and you can imagine whenever we call the function itself we will put the function context in a call stack so let's start with the root so this condition is if the root is null return the empty result list which is not the case then we call this method in order helper and again this is not null so what we do is so first let's say we already started with one so we put them so here imagine we i'm putting the function call in a call stack so i'm just writing here so that you can visualize it then what we do is we visit the left sub tree so we call this function so this function call itself and passing uh the i mean uh the left child of the current node address of the left child so basically uh this two so again i'm putting two and this function calls are in pause state it is waiting to get the value from uh so for example this uh this method call is put in a call stack and pause a state it's waiting to get the value get the return value from this call similarly this one will wait to get the value from its next call so now again we pass the address of its left child and this function again call itself so let's put 4 here and after that again we pass the address which is null so it will return from this call it will return so whenever uh the function get the return value it will be popped from the call stack so when this is part from the call stack we reach at this statement we add its value and then we reach at this statement and for this again we pass the address of its right child and this function will call itself but it is null so again it will return the null value so this time we reach at this call stack and it will be popped from the call stack and we reach at this statement we add its value then we reach at this statement and we take 5 so 5 will be added here and again when 5 is added here so after that the call goes to this line and for this 5 we take its left child and its left child is null so we return the value and when the value is the return so we come back to this statement we pop the value we add them in a result list and then we go to this statement again it will call for its right child so i mean this will go so i have already explained the complete processing iterative approach so this is the recursive code and it will also work similar to the uh similar to the code which we have dry run in iterative approach only the difference is uh in iterative code we have externally declared the stack in which we put the values in a stack we pop the values from a stack and we perform the inorder so here when we write the recursive code i mean internally it's put in a call stack whenever it will uh get the return value it will pop the value from a call stack so it will goes like this and after the complete uh traversal i mean up after the complete traversal we uh we get the values of a in order traversal so now uh you can see writing the recursive code is pretty straightforward so now let's talk about writing recursive code is pretty straightforward now let's talk about its time and space complexity so again it's time complexity is big o of n and in recursive call internally it's uses a call stack so it's uses uh the memory internally we are not explicitly declaring a stack and pushing the value in a stack and popping the value in a stack so it will it is done internally so the space complexity is also big o of n so that's it for this video tutorial for more such programming videos you can subscribe our youtube channel you can visit our website which is https college thanks for watching this thanks for watching this thanks for watching this video thank you
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
301
so we have remove invalid parentheses probably here so essentially you were given a string and there are a certain amount of left and right or open or closed parenthesis so your goal is to match them so they're a valid a pair of um valid number pairs of parentheses and you can ignore all the non-parentheses char all the non-parentheses char all the non-parentheses char and let's jump right into it so essentially the id so the approach would be first you figure out what is the number of redundant open and the number of redundant close parentheses you keep that encounter and then since the problem asks for all possible results it's always good to resort to dfs when you're asked for all possibilities and then given this open and closed counter we will remove randomly any combination number of open and close parentheses but how do we know that it is valid we will simply just run again this helper function if it has zero number of redundant open parentheses and zero number of close parentheses then it is valid and what do i mean by redundant number of close and open parenthesis for example here in this example you can see that we have one redundant close parenthesis so if we remove this guy right here or this guy right here they would be a valid pair so for redundant open parentheses we can see in the example here these four guys they form a valid string and however this sub string right here you can see that there's one redundant open parenthesis and then for this example right here there's one redundant open parenthesis so you can remove one of the three guys right here and four and you can remove one of the two guys right here to form a valid string so let's jump right into it so first we want a helper function to help us get the number of open and close parentheses we'll call it count open we'll call it country redundant and input of bs of course and we'll handle that later count redundant string and once we have that we'll just have a result empty list and we since we mentioned before we ask for all possible results is always good to use um dfs for such statement so then we will have a dfs and we will input here will of course have original string and open and close counter we'll also have to start just to mark what's the starting point of current recursion and lastly we'll have the results for recording all the value and then we return the results and this is our um that first search so we have the string we have the open and closed at the starting point and we have the results and of course the starting point we will start with index 0 and for our access statement for dfs what do you think the access statement should be so since our goal is to remove a randomized open randomized number randomized openness close parentheses of course given the number we only stop when there's no more both open and close parentheses to be removed so for example if we have one redundant open parenthesis and one open one redundant closed parenthesis we stop once we remove one open parenthesis and one close parentheses so the axis statement should be if open equal to zero and close equal to zero that's when we stop then we will record the string and like we mentioned before the third step is to see if this randomized removed version is valid so we'll define a valid helper function and we throw the current string in and if it's valid we will append that to the result and here we directly append the results since we will directly modify on this input string as we go down the recursion then we will do a scan of the string so for index in range of starting from start and end at the length of the list so if index bigger than start and start index is equal to as the index minus one we continue it looks kind of weird that why we're doing this step here is because for example at this step for example if we're given a string like this by removing this open parenthesis and this open parenthesis we're essentially achieving the same goal so this will be open close and this will open also be open closed they're the same and we'll go back to this to see why this is necessary for improving performance then we'll name the current char current character as char and they'll be starting from uh that will be at position index and here's the removal step so if we still have stuff to remove and it is open so if open just for clarity's sake we will mark it as open bigger than zero and the current chart it is say open we can remove it and how do we remove it is that we simply just get that index on original string so self.dfs s until i and starting from position i plus one so we skip the current index so we skip the chart and open minus one since we just removed eight open parenthesis and close remains the same since we didn't do anything regarding close parentheses and start will remain the same our start will actually be indexed since we already just moved to index and results will remain the same and if we still have close so if we still have redundant close parentheses to be removed and the current chart is in fact close parenthesis we can remove it the same format for remove here and since we remove a closed parenthesis open remain unchanged and close is reduced by one and index and results and if we have any uh non-parenthesis and if we have any uh non-parenthesis and if we have any uh non-parenthesis character you can see it is never handled and just leave it as it is in the original string and if the current parenthesis is open but there's no more redundant to be removed we just don't remove it and same goes for the close parentheses and now let's work on our helper functions and like we mentioned before a string is valid if it has zero number of redundant open parenthesis and zero number of closed parentheses so what we can do is simply call the count redundant function about to implement and open and close same format as in the main function and if open equal equals zero and close equal to zero it will return true so is this a so it is a valid string so once it returns true here return will append this valid string to the final return results and let's jump right back to this two lines right here so like we mentioned before if the current index shares the same character as its previous positions we can simply continue because by removing either one of them we will get the same result and there's just no point so we by doing this skip it saves us some time and then let's go to the last helper function it was count redundant and we'll start out by initialize our open and close they're both zero so they're the number of redundant parentheses so again for rns and if are equal to open parentheses so then open plus equal to one and if char equal to close parenthesis then if there's open to match it so if we have open and close it will form a pair so it is valid so if is if there is open then open minus equal to one so it will reduce by one so if there's no open parenthesis available so for example right here it start out by having a closed parenthesis we know knowing right away that it is a redundant closed parenthesis so close plus equal to one so we'll turn open and close so let me restate that close open is the old number of open parentheses that is unmatched by a cold parenthesis aka is a redundant one and the closed parenthesis is the number of closed parenthesis that's never match or can never find a preceding open parenthesis before it so it is redundant so let's go through the logic one more time to see if we make any mistake here so first we count the number of open and close redundant parentheses then we randomize the in a randomized order remove the required amount of open and close and we check and once we remove the required amount we check if it's valid if it is valid then we add that to the final return map return list so open close equals to the return value helper function right here and we call on dfs and the axis statement is when we already remove the order redundance so open equal to zero and close equal to zero and if it's indeed a valid string we add that to the result and then we go through the string and this is like we mentioned before for uh time purposes we never remove um two of the same kind just to save time and get the current char and if we still have open parentheses to be removed and the current char is an open parenthesis we'll remove it and the way we remove it is simply by skipping the current index and since we remove just open remove a open parenthesis the number of open currency remain to be removed decreased by one and the close remain unchanged and the start will start from index and the results remain unchanged and the same logic goes for close and let's check on our helper function so a string is valid if it has zero redundant parentheses either open or close so we call count redundant and if both of them is zero or return true and like um here you can see it has zero redundant parentheses and let's go to our currently then count redundant so we start off by decoding open and close with zero and we scan through the string and if it's a open premises open increase level 1 and if it is close and there is a open to match it then we will reduce the open by one and the close remain untouched and if it is a closed parenthesis but there is at this moment no preceding open parenthesis to close so the number of redundant close parentheses increased by one i'll return and it looks correct we're trying to compile so okay so add so it is index not i now let's check to see if we the other is correct okay it looks correct return the correct result and let's try to submit it so it works and let's go for the time and space complexity analysis so in for space complexity we never introduce any significant extra additional data structure so it would just be this results right here which is for return value we can call it oven and for time complexity even though the code looks super complex we here we do a single scan through which is all of n and it's run here so this will be of n and for the dfs right here it will have basically it just go through all the possibilities of um combination of open and close parentheses to be removed so it will also have a big old of n since for each let me see so this will actually be all been and the entire thing will run in times as uh there is some and position on the original string so this will be of us time complexity over n squared and just to do a recap so essentially we first found out the number of open and closed redundant parentheses and we removed that amount of corresponding parentheses and we check if it's valid we return and that's it
Remove Invalid Parentheses
remove-invalid-parentheses
Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return _a list of **unique strings** that are valid with the minimum number of removals_. You may return the answer in **any order**. **Example 1:** **Input:** s = "()())() " **Output:** \[ "(())() ", "()()() "\] **Example 2:** **Input:** s = "(a)())() " **Output:** \[ "(a())() ", "(a)()() "\] **Example 3:** **Input:** s = ")( " **Output:** \[ " "\] **Constraints:** * `1 <= s.length <= 25` * `s` consists of lowercase English letters and parentheses `'('` and `')'`. * There will be at most `20` parentheses in `s`.
Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options: We keep the bracket and add it to the expression that we are building on the fly during recursion. OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed. Can we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values. 0 1 2 3 4 5 6 7 ( ) ) ) ( ( ( ) i = 0, left = 1, right = 0 i = 1, left = 0, right = 0 i = 2, left = 0, right = 1 i = 3, left = 0, right = 2 i = 4, left = 1, right = 2 i = 5, left = 2, right = 2 i = 6, left = 3, right = 2 i = 7, left = 2, right = 2 We have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.
String,Backtracking,Breadth-First Search
Hard
20,2095
222
hey guys this is just how's winning going in this video let's take a look at uh two we're giving a complete binary tree we need to count the number of nodes um so the definition of complete tree is that except the last layer all the layer all level is completely filled and the last layer have all the nodes uh aligned left well the beautifuls i think the knife solution will just use bfs or dfs just counts the other nodes right so the brute force would be with uh on time and it would open space well of course this will not be accepted because this is not there's no such thing as algorithm there just as a typical tree traversal we didn't use any characteristics of the binary to complete binary tree so i thought for him for some time and didn't think of anything so i had to take a look at a solution so forgive me and uh so i explained it with this solution chart it's really actually very simple so the only thing we need to care is about the last uh layer right the other ones are all full so we can directly calculate them so uh so for n nodes the root what is the binary tree uh okay so we first we get to the layer this will be oh the height which could be just a use dfs not the fs but check the all the left layer go to the bottom so we get the height and for the last height we can sub the full the amount of the height begins from zero so last layer maximum should have two to the power of two by h right so this kind of amount of uh note so the nodes are aligned to the left so rather than we count them we could just do binary search choose the middle and uh and check if it exists or not by so binary search on two to the power of edge numbers check if exist we need to find the find how can i say last element that exists or say yeah last element exists cool so how we can we say that if anything exists well it's simple we get the we could get the parent in x right and get pairing index and get to the root so if the odd numbers then it must be the left so we go up you should the parents have a left child of it then go for four we know it's left and two here be two right we know it's left and this is one we should we know that he's right and then we could go back from root to with this path and to see if it exists or not so cool let's try to before we implement it what's the time and space complexity okay so for two and the edge numbers the binary search will costs for log right lock to edge so it's edge actually times the check right and then the check will be go back to root and go back here so the time still this edge so the time will be edged to okay this so it's o log n this is much better than linear time wow it's clever and the space we will keep track of the path here actually so it's uh o log n wow it's much better so let's begin the first is to get the height if root is root might be nor complete minimum okay so we just keep checking the left so let's start close root while start let height equals zero i plus one and the start equals start left so root count one because the next one the size is two count one start will fail at null yeah we got the height okay max account at last layer would be 2 to the power of height cool so now we do binary search start equals 0 and equals to this minus one zero one cool so while start boosting plus meter equals four against the middle and now we need to check it is exist if it exists then there might be uh some extra node existing to the right starts equals to meet plus one if don't doesn't exist then and to go back to one right so start actually will be the next non-existing node because when start n meets at an existing index start will go to next right if start and end meets at a non-existing meets at a non-existing meets at a non-existing the end will go back so start is the so n actually and these are what we want and this is what we want so the end is what we want okay we end it and the oh i think we just do the subtraction so return the nodes of the last one would be 2 to the power okay max count to the last layer is actually the count of all the rest layer so plus n that's it and now we are going to implement the exist so function exists index will keep track of the path uh we could use the shift but it will uh cost a uh extra time because of the index shifting we will use push okay so the index while index start at here index will actually end at zero so index is bigger then e0 if index mod 2 equals 1 if it is odd number then it means it's on the right so path push right if it is even then push or left after we push we need to update the index equals mix subtract one divide by two is left index equals index to two so for in the index of three r two we because here we push left and the index will be one and then it's even so we push right and the index will be zero so right left cool and now start from root check the target no um we need to reverse it we don't shift because push and reverse will be faster start from root to check the target node so let's start equals r root and uh for oh we don't need to reverse we just pop let branch ranch equals f pop if branch equals left start equals root left or if we say branch equals star oh start equal start branch yeah and then you start goes to return force otherwise return this is it let's try god start has already defined oh i just use remove the led this is weird i use p here okay written 10 but expect six obviously we have some problem here log exist needle xs2 0 1 2 while it exists two star zero max count what is maximum the max count should be four we got eight no height this is one ah god ah minus one problem cool but if we fail one two three four something like this one two three four let's log it we exist one four and four yeah x one x doesn't exist and one doesn't exist here let's see what the path is oh not exist we exist 1 4. one right no needle is one yeah it should not exist the indic index is odd then we push right and then one becomes zero ah i see zero it doesn't mean zero doesn't mean not okay but uh actually we should break on the height so i'm sorry so the path actually for the last one should be height to height of two will generate the path of one so while minus one we should continue finally we're accepted and this time and space is here so that's it hope it helps ah very interesting okay perhaps see you next time bye
Count Complete Tree Nodes
count-complete-tree-nodes
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree. According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. Design an algorithm that runs in less than `O(n)` time complexity. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 6 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[1\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[0, 5 * 104]`. * `0 <= Node.val <= 5 * 104` * The tree is guaranteed to be **complete**.
null
Binary Search,Tree,Depth-First Search,Binary Tree
Medium
270
1,980
hey everyone welcome back and let's write some more neat code today so today let's solve the problem find unique binary string a problem from this afternoon's leak code contest and the thing about this problem is that you probably know how to solve it immediately as soon as you read it but you might not know how to code it up and that's i guess what i'm going to be focusing on so we're given an array of strings there's going to be n strings all of them are going to be unique each of them is going to be of length n they're all going to be binary strings and we want to return a binary string of the same length and that does not exist in this set if there's multiple answers we can return any of them so if there's n strings if a binary string is of length n how many possibilities are there's gonna be two to the power of n possibilities right and we're only given n of those strings so obviously if there's two to the power of n there's gonna be a lot to choose from so we can choose any of them now what's the easiest way to do this since there's a guaranteed solution we can just start at you know the zero case and then just start adding and then continuously trying a new string and seeing does it exist in this set if it doesn't exist in the set then we can return this as the solution if it does exist then we're going to go to the next string so we'll just add one to this right so it's a binary string add one and then we try this does this exist okay right now yes it does then we'd add one more and then we get this string right this binary string okay does this exist yes it does so then add one more okay now we get one so one does not exist in here so then we can return this as the solution that's the one that we returned in this case we could have also returned zero 0. now one optimization is how can we quickly check if this string exists in the given set well we can convert this it's not really a set right now but we can convert this into a hash set right now it's a list but we can convert it into a hash set what's the time complexity of this gonna be like since we're brute forcing it how many attempts how many numbers is it gonna take us how many times are we gonna have to count before we can find one that's in this set well there's only n in this set so worst case we have to try n plus one different strings and that's the worst case and then when we're checking the operation does this does the string exist in the hash set is that going to take some extra time well the string is of length n and to hash a string of length n it is going to take an n time operation so overall the time complexity you know this can be reduced to n so we can just say the overall time complexity is n squared where n is the length of any particular string and like i said the hard part about this is going to be coding it up so there's probably a lot of different approaches you can take i'm going to probably do one that's probably not the best but it's the one that i was able to come up with first so instead of actually counting you know starting at zero and then just adding one each time i'm gonna do slightly different because this is how i can code it up we can do like a backtracking approach right so you know we can say okay the first character in our string and this backtracking is gonna have a height of n so if n is two then the height of the backtracking is gonna be two if it's three the height of the back tracking is gonna be three but we're gonna generate a bunch of binary strings until we find the right one so we're gonna go we're gonna take one decision to be zero one decision to be one and just continue going like this until we reach the bottom level like basically we've gotten a length of two we don't wanna create a longer string than 2 because that's the length of these so then we're going to check this one right so this is the first one that we were able to generate does this one exist in the input it does not so then we can return this string immediately right 0. now if it did already exist in nums then we would have to try the next string right then we'd have to try this one right but the point here is even though we're doing a whole backtracking approach even though we're going to be generating a bunch of strings we're not going to be necessarily generating all two to the power of n strings because as soon as we find one that works for us we're going to return it immediately and then completely stop the backtracking so the time complexity is not going to be 2 to the power of n it's still going to be n squared this is what i was able to come up with i'm looking forward to seeing what smarter people than me were able to come up with that being said we can jump into the code now let's write the code and remember we are going to be converting the input nums into a hash set so in python you can do it kind of easily like this for every single string in nums i'm just going to add it to this hash set uh but other languages i'm sure you can do it similarly and i'm going to do this recursively backtracking right so uh two parameters we're gonna maintain what the current string or first actually what the current index we're at right so what position that we're at in the string that we're generating and whatever that current string actually happens to be so far and what's the base case going to be remember we're gonna stop as soon as we've got an n character so as soon as our index i is equal to the length of the input nums then that means we have made it as big as it can be so that's gonna be our base case i'm not gonna handle this just yet first i'm going to tell you how we're actually going to call this backtracking function we know this backtracking is guaranteed to have ever have the correct result right so we'll pass in 0 at the beginning that's the index we're going to start at and for current what are we going to pass in most languages i think you can do a string but python is kind of annoying you can't modify the index of a string so i'm going to be using an array and then at the end i'm going to mod i'm going to change the array to be a string so that we make sure that we return a string because that's what they want us to do so i'm going to create a binary string of length n initially it's going to be all zeros so whatever for how many characters happen to be in nums or how many strings happen to be in nums i think so we're passing an array of n zeros and whatever result this backtracking returns that's what the answer to this problem is gonna be so now that you know this is what we're passing in how are we gonna actually handle the base case we want to know once we've gotten a string of length n is this string and current equal to one of these in the string set how can we do that well in python first you have to take this array and then turn it into a string so you can do that like this you can join all the strings in current to be a string so let's assign that to result and we'll check we're going to return null if this result is in the string set because remember we're trying to return a string that's not in the string set so if it is in the string set then we're returning null but if it's not in the string set then we can actually return this result that means we found the solution we're good to go so as soon as we find that solution we return it immediately and then we stop our function if we don't find it then we obviously have to continue so then we do our backtracking right so like i said we're going to only have two choices so we're only going to call the backtracking two separate times we're gonna obviously for the index pass an i plus one because we wanna shift to the next position each time for current we're just gonna leave current as it is so this is kind of the case where the position at index i is just going to stay as zero right this is the decision where we choose zero and then we'll get whatever the result was returned to us and if that result is non-null right because we're result is non-null right because we're result is non-null right because we're returning two possible values either a string or null value so if it's not null then we're gonna immediately return this step is important because we don't want to generate extra strings that we don't need to if we find the result we return it immediately unfortunately this is gonna basically i'm gonna have to copy and paste these two lines and i'm pretty sure there's probably an easier way to do this code maybe you don't even need backtracking but that's what i was able to come up with so if there's a cleaner way let me know but for now i'm just gonna copy and paste these two lines so we're gonna do the exact same thing except we're gonna change our decision right instead of choosing zero we're gonna change our decision to be one so at index i in current instead of remember by default it was zero right that's what we did down here i'm gonna change it to one so that's the second decision so that's the main logic so if we find the result here we return it by default what python does is it returns null so if this if statement doesn't execute then by default it'll end up returning null and that is possible because in some of the recursive calls it could return null but at the root call this root call that we do down here this is never going to return null just so you know so that is the entire code i'll run it to make sure that it works but i already did that in the contest so as you can see down below it was accepted i'm sure it's not the most efficient i'm pretty sure there's a better way to do this problem let me know in the comments but i hope this was helpful if it was please like and subscribe it supports the channel a lot consider checking out my patreon to support the channel and hopefully i'll see you pretty soon thanks for watching
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
96
hello viewers welcome back to coding interviews channel hope you're doing great if you haven't subscribed to the channel yet please go ahead and subscribe I have created a bunch of playlists to cover various categories of problems such as BFS DFS Janek programming stacks queues linked lists race graph and so on please check them out I have uploaded the core for this particular problem to the github repository you can get the link from description below this video let's jump into today's problem a unique binary search trees given an how many structurally unique bsts that store values 1 to n so basically we are given with a number and ok and the values are starting from 1 till and right so now we need to identify how many unique binary search trees structurally possible right so basically the binary search tree property right so if you go look back the binary search tree property so the left subtree should be less than root and root should be less than right subtree right so this is the simple definition for BST right now we are saying there are n nodes or n elements we will say right n nodes starting from 1 to n right so 1 till and so there are n nodes in the binary tree right so when there are n nodes in the binary tree there could be multiple possibilities that could happen right so now we are asked to find out how many structurally unique BS trees right so structurally means so the values probably may be different but the structure should be unique right like that so let's go try to understand the process that we are going to get the logic for this particular problem right so as we say we are saying n is the number of nodes in the binary search tree right so then obviously when we are talking about binary trees there will be a left subtree there will be a right subtree and there will be a root right so by keeping that in mind right so if which one is optional in them left subtree or right subtree is optional but root must be there right so assuming that there is at least one node since our numbers are starting with one right I would assume the tree has at least one node in it right so if the tree has one node in it then that will be simply a root node right we don't have any further things right but if there are n nodes that means one of them is root node right and one of them is root node and I'm calling the there are n minus one are remaining right so one we already allocated to root so there will be n minus 1 nodes are remaining right so now our task is to distribute this n minus 1 nodes into left subtree and right subtree right so we could divide this n minus 1 nodes in so many different ways right simply saying n minus 2 different ways right so if there are n minus 1 nodes you could divide them in n minus 2 different ways so let's see what those ways are right so let's say if there is one node in the left subtree out of this n minus 1 right so how many nodes will be there on the right subtree n minus 2 right so this total are n minus 1 right one is if we move further right so let us say there are two nodes in the left subtree right and then there might be or there can be n minus 3 nodes in the right subtree right so on the whole if you add the number of nodes in the left and number of nodes in the right that should be equal to the n minus 1 right since there are we are saying there are n minus 1 nodes remaining after the root node is selected so n minus 3 plus 2 is n minus 1 again so going on with the further distribution right so if there are 3 nodes there should be n minus 4 nodes in the right subtree so on if you go right finally what we say is n minus 2 nodes in the left subtree and 1 node in the right subtree right so that is possible but there are two more cases are also possible we started saying okay left subtree are right subtree is the optional right that means what we can say is there can be 0 nodes in the left subtree and all nodes can be all n minus 1 nodes can be in the right subtree and the reverse case basically there are n minus 1 nodes in the left subtree and 0 nodes in the right subtree so that is also a valid case right so if you follow that right in the example given on the left side input is like 3 nodes right so for this one as the road the number of nodes in the left subtree are 0 here right if you closely observe the number of nodes in the left subtree of 1 the node 1 is 0 right so similarly the number of nodes right here in the right subtree are 0 right so these are the cases that we are talking about it the number of nodes in the left subtree and number of nodes in the right subtree could be 0 right and now since we are dealing with one node at a time right so out of n nodes we picked one node and we distributed the remaining n minus 1 nodes into left and right sector now let's say let's go with this example right so let us go with this example right further so there is only one node on the left subtree so we will not be able to make more than one tree with that right so that is constant but the n - two nodes on the right subtree so n - two nodes on the right subtree so n - two nodes on the right subtree so now we will have to pick one known as the root out of this n minus two right and there will be again distribution going further from the n minus two nodes so once you pick then one node as a root node how many nodes will be remaining n minus three so now you have to distribute this n minus three nodes into left and right subtrees so this thing will go on and on right so when you do this math all together right so you see same problem is being solved multiple times right so here we picked one root node right one root so n minus three remaining right so if you look this step below write n minus three nodes on the right subtree right so that this n minus three and there is n minus three here so that means we will be doing the similar calculations multiple times in here so when you have that kind of scenario right this is a good case to use a dynamic programming approach right so that you don't have to calculate the same thing more and more number of times right so we are going to solve this problem through dynamic programming approach and since we are dealing with okay there will be some number of nodes on the left subtree and some number of nodes on the right subtree and obviously there is one root node right so with that we can if we go further and calculate right we will come up saying okay for a given number of nodes the number of binary trees possible are equal to the number of nodes in the left subtree into the number of nodes in the right subtree that is the thing that we will get at right if you go further and dive into all these different options right we will end up with this formula so the number of nodes in the left subtree into the number of nodes in the right subtree for a given n right so this is the approach that we are going to use in order to solve this particular problem so this is one approach and we will come back for the second approach okay so this is first approach we are going to look at the code for right so I am calling this number trees as DP basically dynamic programming if the number of nodes is less than or equal to 1 then we are saying okay there is only one tree possible right so if it is zero nodes that empty tree right that is structurally unique binary tree so binary search tree so it is one tree if it is n is equal to 1 then also it is one tree possible so now going on further what I am going to do is a declare an array DP array which is of length equal to n plus 1 and initialize the first to 2 elements as we are saying when n is equal to 0 there is only one 3 possible right when n is equal to 1 there is only one tree possible those are the two things which we already know that's why I am initializing the base cases now starting from 2 right what I am going to do is now I need to calculate the number of in left sub trees and number of right subtrees right so that depends on how many number of nodes are in the left subtree and how many nodes in the right subtree so what we are going to do is we are we going to going through exactly this kind of distribution right so there is one node on the left n minus 2 nodes on the right there is two nodes on the left and minus 3 nodes on the right so this is a similar thing that we are going to use right so let's go and look at that so we will start with I is equal to 2 right so that's since we already know the answers for when the trees with zero nodes and when tree is one node that's the reason why we are starting with when the tree is with two nodes right and we will go on until the tree has and outside so that's what we are going to do now so what we are essentially doing is there are some number of nodes under the left subtree and some number of nodes on the right subtree right so what is that some number so there will be zero nodes on the left subtree and all n minus 1 nodes on the right subtree right and there are there is one node and n minus two so likewise so that's the reason why we have another for loop here which is going from 1 to I right so if there are 3 nodes so it will go from 1 2 and 3 that's how it is so on to the left subtree we are saying there are J minus 1 that means we are subtracting one node as the root node right so that is what we are going to get the value from the DP at it and right subtree the remaining nodes are to the right subtree so we are getting the values from left and right and what we are doing is essentially multiplying the left and right that's what we are doing and then storing that value into the DP by adding whatever the number that is available within the DP what we are essentially doing is the number of sub trees with left subtree and the right subtree and multiplying them for that n right so as J moves we will be doing that many different kinds of trees and finally the DP will be filled with the final answer for a given n so when we are going to return an output right we will be returning the DP of n right so that's the simple way of coding this dynamic programming approach let us look at the time and space complexity for this time space right so what is the time complexity assuming that there are n nodes right so this outer loop is going through n minus 2 x right so n minus 2 right and the inner loop is going from 1 to I right so typically what we say is this is when I is equal to n right it is going from 1 to n right so we will say the time complexity for this particular algorithm will be order of n square right that's what we will call let me put another bracket right here so that it's easy to understand right so that's what the time complexity and what is the space complexity so the space that we are using is the DP array which is equal to n plus 1 so let us say order of n plus 1 so are we using any more space not really right so in that particular place the space complexity will be order n plus 1 but since we are going to remove the constants from the Big O notation it will be order of M all right so time complexity is order n square and space complexity is order n so now let's go with the second approach right so approach to right so in this approach what we are going to do is instead of going through the formula I mean instead of going through all the formula that we came up the left sub-tree into right came up the left sub-tree into right came up the left sub-tree into right subtree right so there is a formula that is derived out of this so if you do keep on doing this number right so if you keep on doing this the going through the two for loops and adding all these numbers and all right so there is a number mathematically that we will be able to get it right so there is a formula directly that you can get for a given and how many unique binary search trees are possible right so that is called combination so it's based on the combinations ok so it's simply how to how you have to understand is you we are saying if there are n nodes right combination of n nodes right so that means we will say okay combination of zero nodes in the left subtree and combination of n minus 1 nodes right plus combination of 1 in 2 combination of n minus 2 right so that's what we are going to have until combination of n minus 1 into combination of 0 right so this is what we have been doing as part of these two for loops right so zero nodes n minus 1 nodes one node n minus 2 nodes like that right so these are all we're adding them that is what is C of M right so mathematically if you solve this equation right it will come up as 2 n combination of n right by n plus 1 right 2 n C n by n plus 1 right so this is a combination so in other words we can write like this also at this one right C of 2 to N comma and Y n plus 1 right so this is a so the answer for this complete equation is this combination of 2 and C n by n plus 1 so if you know what is a formula for n C sorry and C are right so if you if this makes real sense for people right and C are right so which is equal to n factorial right and factorial by r factorial into n minus r factorial right so that's what is a formula ok so NCR so now we are going to write this two and C n by n plus 1 in this format right so by following this powerful what it becomes n is here - and R is n right it becomes n is here - and R is n right it becomes n is here - and R is n right so there is n plus 1 anyway with that we need to put so in place of and there is 2m right so that means what it will become is 2 n factorial right 2 n factorial by R factorial is what R is what n right and so n factorial into n minus R what is n 2 n R is what and 2 n minus n is and so n factor one more time inverter it will become and there is a by n plus one right here so into n plus 1 right so this whole thing will be under this as a denominator so this is a formula right that we will end up with this is approach to so now what we are going to do is simply substitute n in here and get the answer that's it so let's go look at that approach so since we have to calculate the factorial right I wrote a private method to calculate the factorial for a given number right so it takes M and then calculate the factorial and returns the product so just by following this right so here I need to calculate the 2 n factorial cost and n factorial so if I calculate these two so that is what I am doing here to factor 2 n factorial I am doing and then returning that thing to n factorial by n factorial into n plus 1 that's what I am returning so this is a simple approach right so this one if we go look at the time and space complexity right so we will say ok all we are doing is okay taking n and doing the factorial calculation for 2 n and factorial calculation for and so that means we will be going through the factorial calculation of 2m how much time we will be taking here for factoring calculation of factor 2 n it will be order of 2m right order of 2n plus so just to remind you I am calculating the time complexity right order of 2n plus what is the time it will take 4 factorial of n order of n right so that will be order of 3n since we are going to remove the constants from Big O notation it will be order of n right time and what is the space are we using any extra space here no apart from these two couple of variables we are not using any more space that means we will say okay the space complexity is order of 1 right so in this particular case what we are saying is we have time complexity of order of N and space complexity is order of 1 right so if you compare the two approaches there is an improvement of order of N in terms of the time complexity and also order of N in terms of the space complexity right so if you have any further questions please post them in the comment section below this video I will get back to you as in a second I have posted this code to the github repository you can get the link in the description below this video if you haven't subscribed to the channel yet please go ahead and subscribe and share among your friends please click on the bell icon so that you will be notified about all my future videos thank you for watching I will be back with another problem very soon till then stay safe and bye
Unique Binary Search Trees
unique-binary-search-trees
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. **Example 1:** **Input:** n = 3 **Output:** 5 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 19`
null
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
95
1,935
hey everybody this is larry this is me going with q1 of the weekly contest 250 maximum number of words you can type uh hit the like button hit the subscribe button join me on discord let me know what you think about this from this contest whatever german you know yeah um so this one is pretty straightforward to be frank uh you basically have a set of broken letters and then for each word you just check to see if any characters um or you know any character in the word is in broken letters so this is the way that i did it um you first put everything in set just for so that's slightly faster and technically you can also put everything inside of a word and then you do a set in the section as well but this is what i did instead which is that for every character we make sure that it is not in s which is the forbidden words and of course this is gonna be linear time because for every character and every word in total we do one lookup of instead which is all one presumably so yeah so this is going to be linear time um or alpha space where alpha is the number of working letters pretty i think this is pretty um a good practice to on the fundamentals so yeah let me know what you think and you could watch me solve this problem live during the virtual contest next um am i recording yeah i am recording okay had to double check okay malfunction you turn the number of words in text that you can okay should be straightforward i know i have to okay hopefully this is good it should be close but um i don't have my mouse so it's a little bit awkward as well 110 is such a bad thing though um let's see like it doesn't it's not it doesn't give me confidence and um i've been doing this thing where i'm slowing down a little bit to make sure i get it correct because five minute penalty is pretty expensive okay so hello code is what i expect to print out that is what i'm printing out so let's go also this is not real i guess so that's why i'm a little bit you know i probably would have submitted it already during the contest maybe i don't know let's see give it a submit okay that's good uh okay admin but yeah hit the like button to subscribe and join me on discord let me know what you think about this problem explanation whatever you need to do i'll see you later stay good stay healthy and i'll see you later bye
Maximum Number of Words You Can Type
minimum-number-of-operations-to-reinitialize-a-permutation
There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** in_ `text` _you can fully type using this keyboard_. **Example 1:** **Input:** text = "hello world ", brokenLetters = "ad " **Output:** 1 **Explanation:** We cannot type "world " because the 'd' key is broken. **Example 2:** **Input:** text = "leet code ", brokenLetters = "lt " **Output:** 1 **Explanation:** We cannot type "leet " because the 'l' and 't' keys are broken. **Example 3:** **Input:** text = "leet code ", brokenLetters = "e " **Output:** 0 **Explanation:** We cannot type either word because the 'e' key is broken. **Constraints:** * `1 <= text.length <= 104` * `0 <= brokenLetters.length <= 26` * `text` consists of words separated by a single space without any leading or trailing spaces. * Each word only consists of lowercase English letters. * `brokenLetters` consists of **distinct** lowercase English letters.
It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution.
Array,Math,Simulation
Medium
null
724
hi everyone today we are going to solve the readable question find the pivot index so you are given array of integers num and calculate the pivot index of this array so the pivot index is the index where the sum of all the numbers directly to the left of the index is equal to the sum of all the numbers strictly to the index right so if the index is on the left edge of the array then the left sum is zero because there are no element to the left this also applies to the right edge of the array so return the leftmost pivot index if no such index exists return -1 index if no such index exists return -1 index if no such index exists return -1 so let's see the example so you are given one seven three six five six and output E3 because the pivot index is three so zero one two three here so let's see the left side so total number of uh left numbers is one plus seven plus three so total 11. so let's see the right side the total number of right side is 5 plus 6 and 11. so two totals are same so that's why uh in this case uh pivot index is three okay so let me explain with this example so I copy this inventory from example one so first of all initialize next sum with zero and uh I already calculate the total number of all values so total is 28. and basically iterate through all numbers like one by one and then in each iteration I calculate the right sum so how can we calculate the right sum it's simple total minus left sum minus current number so when we take the example one uh pivot number with index number is not included so that's why we need to exclude the current number so okay so let's begin first of all we find one so calculates the right sum total 28 Minus left sum 0 and the current number is one so total 27 so now light sum is 27. after that compare let's sum with light sum and if they are same we should return the current index if not are the current number to lift some so in this case they are not same so how to connect the number to lift some so now let's sum is one and then maybe next now pivot in the index is one and then again calculate the right sum and the total 28 Minus left sum is 1 minus current number seven so light sum should be 20. and compare two numbers like a left sum and the right sum and they are not the same in the case at the current number to that sum so now left sum is 8. and then move next so pivot index is now two and then again total 28 Minus depth sum 8 20 and the current number is -3 so 8 20 and the current number is -3 so 8 20 and the current number is -3 so Total light sum is 70. so let's check so right now our right side is like a six five six so total is six plus five eleven plus six seventy so let's get and uh on the other hand left side one plus seven eight looks good and then compare two numbers like I left sum and the right sum and the eight passes seventy so they are not same in that case are the current number three to left sum so left some now 11. and then move an X so pivot index is now zero one two three so again calculates the right sum total 28 Minus left sum 11. and there's 17 minus 6 so write sum is now uh 11. so compare two numbers actually they are same in that case return current index so 3 so that's why our pivot index is three so let's check uh left side total number or left side is 1 plus 7 8 and 3 and 11. on the left and on the right side total number is five plus six and eleven so yeah it looks good so that's why we should return our index 0123 that is our basic idea to solve this question without being said let's get into the code let's write the code first of all get the total number of all values so sum and the nums and then initialize the left sum with zero so this is a lesson and then start looping for I in range length of nums and then as I explained earlier so calculates our light sum all right equal total minus left sum minus in the current number so this is a dry sum and then if right equal left in that case the term current index if not the case uh the current number to left some so left cross equal numbers and then I actually that's it so if we don't find the pivot index then return minus one that's it so REM is submitted yeah looks good and uh time complexity of this solution should be order of n because I delete all numbers right one by one and the space complexity is actually o1 because I don't use external data structure just a variable yeah I think space is a constant time so let me summarize step by step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of find pivot index step one initialize total of all values and the left sum with zero Step 2 start looping calculator right sum by total minus next to sum minus current value if the right sum is equal to the left sum then return the current index if not out of the correct value to the left sum step 3 data minus 1 if you didn't find the pivot index yeah actually that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave your comment I'll see you in the next question
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
1,646
Hello Hi Everyone Welcome To My Channel It's All The Problem Get Maximum Engine Related Are Sour Given In Interior And Are Number Of Land And Plus One Generated In The Following Verses And Subscribe Where All Lies Between Two Subscribe Button For Inclusive Velvet 16000 Subscription To Solve This problem solve older post third standard for 500 for the force will create a are size five plus one is six element so let's find no with six element and use it to force two to the software if it I would like to welcome to cases question Hai one plus one ki which is equal to two numbers of ki i plus number five plus one kal morning bhi potai ko swapn egg bhurji speed come to 2 how to and s victims of 3 hum to pass winning candidate number 2 which is nothing but names of Way Similar Number To Which Is Number One Plus Two Which One Plus One Two 9 Bluetooth 2nd Floor And subscribe The Amazing Element Only To Take Care Plus One Subscribe To This Video Channel Thank You For Running From Two To Two Question What Will Happen With Civil Code To You For Equal To 20502 A Plus One Vikram 2068 Saur Jyeshtha Putra Is Condition subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the A Sanam Shubh Ansari Farmaish Dowry of three the victims of Two numbers of that one plus a number of two flashlights co continue with benefits which comes for btc course poonam saaf ho how to and share insaan question is vikram five physical two a number of two plus number of pati saif clearly see for all i like This Oil Trend Different Schools For Eve Was Quite Simple But Too Plus Withdraw Its Previous Video then subscribe to The Amazing Size Of Penis Subscribe Clear All Your Problems Of Mine In This Whole Edifice 12.00 Not Withdraw From Too Edifice 12.00 Not Withdraw From Too Edifice 12.00 Not Withdraw From Too Plus Avoid Smell of Situation Adhir Vo subscribe The Channel subscribe this of evidence is a that this eye is eye mode on two is one between this half inch plus two plus one upon in hair cutting maximum subscribe and share feedback from indian return subscribe 135 subscribe to 108 settings Compiled And Were Getting Expected Cervix Cancer Made This Code On The Fact That Accepts There Time Progresses Trading For Admissions Open And Space Complexities Of Software Creating Others Open So It Feels Like A Solution Video Channel thanks for watching
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
1,624
So hello everyone welcome back to my channel once again so today we are going to solve today's problem of the date code which is the largest substring between two equal characters lead code 1624 okay now what do we need in this A string A is given, okay, we have to return the length of the longest sub string, okay, between two equal characters, that is, the longest sub string between two characters, excluding the two characters, means we should not take those special characters. Is in the count and if no one exists then we will return minus. Now what is substring? It is contiguous sequence of characters within the string meaning one after the other means that sequence will not be broken. All inside the string is fine like a. If B comes after A, then it should be B only. Not that we will say by doing B, okay, then all that has been stinged. Let's see in our example, like here A is given, then it is okay, so in between this. There is nothing in I, okay, then there is nothing in the middle, now in this second case, there is ABC A, so one A, I see here, the second one is okay in the middle, B is in the middle. These two will be our answer. Tam all by I hope the question will be clear. Okay, now how will we do it okay, let's see that. So as we know the substring, then for the substring we are bound by two things. Okay one. One pass is left and the other one is right, okay, in this way it will be bound, okay, what will we do, whatever is our eye, we will make it right bound, okay, that means if we get the right part, then it means it will be bound from the eye to the other side. We will be doing it right and for that i we will be checking the left and how is that if our proposal is a string like this then s off left if our s off a comes equal to aa okay so if we see the test case then like that Something like this is happening, let's assume that our Y is the last index A and on the left we have A, let's assume that let's go to zero, so if this becomes equal to ours, then we can of course say that we have got our sub-group but this that we have got our sub-group but this that we have got our sub-group but this one Where can we have problem at the place where it is possible that there may be many indexes, the same index is the same, okay, look at an example, if our string is something like this, then what did we say, we will take it here, okay? Yes will remain ours, but here if we pay attention, there is one here also, there is also, and there are three, we are visible, then the question is, which one will we consider? Then there are three incisors, we have a tooth in all is present there and we had said that S of left should also be A, S of A, okay, then how will we select, so as it is said in the problem that we want the maximum length, okay, so we will select the maximum length. We will choose the lower bound, that is, zero is fine, so what will happen on our left, here we will choose the lowest bound, zero, so now what do we know that every I which is given to us will be given to us, what kind of interest we have kept, first index. Okay, where the s of a ok will be clear, what will be our last index, ok, whatever we get will be our i, so for that i, we will keep in mind the first ok currency, wherever it came for the first time. That will be our main answer, from there to there, okay, now to handle this thing, we will be using the map here to know where our first run comes, so we can keep it mapped, so now we can By adding I, we will add it to whatever string we have given and for each I, we will check whether the S of I is present in the first O currency of our map. If yes, then we got our answer. If not, then we will return it in minus. Okay, so I hope the approach is clear. Rest we can understand from the code how we are doing it. Okay, so let's see the code. Simply, we will make a map from where to where, so characters and integers are ok, first ok, we will make the rest one and answer, we will make a mine and do it like this, ok, now check on this, is our currency correct? Is it right? Does it contain the key, meaning the character is AI? If it does then what will we do? We will update the answer. Our answer is I. Now keep in mind that he has said only the middle one, meaning both of them will be excluded, so we will What will we do i minus first author? Now how do we extract it from the map? So by gating we can retrieve its value i minus and ok now in the else case if it is coming for the first time means if it was not present then first The bar and element will be coming, then we will put it directly inside the map, then the character will come and its position along with it will be fine, that was all our code, rest we will return to check and this is our work. Also, we got our batch in December, that's all, let's do a dry run on this code once and it will become a little more clear. Those who haven't got it, then let's take the same case which was our second one, ABC. If the first one is ok, then we will understand it like this, Suppose ABC, we are giving it like this, ok, what did we say, we had created an answer, we had created a map from Maave, ok, so we will keep the map like this, ok. Now what is happening here is that we are typing it inside the string, okay so this is our A, we are typing it, so the first character at I is starting from zero, so let's check here, is A? There is no P anywhere in our map, so we will not go to the if case, we will come directly inside the else, then put zero along with A, okay same, now what is the next character, we have B, neither is B yet. If it is not inside the map, then its I value with B means one has come, the same with C, two. Now what happens, we are the last, our I has come here and this is what we were doing, not our I which was right. He was most bound, now as he came here, he checked if he is present in our map, then yes man, he is present here, we can see him, so what should we do? Who was Max updating the answer with? Off which was our answer present for now and our i minus first au in the currency which we were getting, so what is the value of it associated with a, is it zero, right? Is it mine 0 ch it so this was our answer yes so this will be updated in our answer and if we look here then see this was our answer right so I hope this approach must have been clear I have also shown it by doing a dry run. So if anyone still has any issue, then either do the draw run yourself once or tell me in the comment section that I did not understand here, okay, so today's problem ends here, rest. See you in the next video till then bye take care of yourself ok and also happy new year in advance ok it is the last day of the year so from tomorrow onwards those who want to take new year 's resolution can take that we 's resolution can take that we 's resolution can take that we quote daily See the rest, you can continue as much as you can, it's okay, try it every day, okay, see you in the next video, and like, subscribe and share the channel, okay bye.
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
257
what's up everyone today we're gonna go over Lee code 257 now the input is going to be a binary tree and the output is going to be a list of strings and what we need to return is all the root to leaf paths for example one two and five is one of the strings and one and three is the other string so let's say for example we have binary trees right because they're asking the direct path from the root to leaf we know we can take a DFS approach if they were asking us something to do row by row or layer by layer that would be a BFS approach now we are gonna choose this one because the question is directly asking us to return the pets so let's look at how we can calculate this okay now I've drawn two binary trees and I'd like to point out a subtlety even though this problem is tagged as a leak code easy now let's say we were trying to do it in order traversal of this tree what might that look like so that's pretty straightforward and how can we generate this well all we do is just take a list of integers and we pass in our recursive tree so we passed that and each one of these notes is going to append itself when it's when it gets a chance so 2 5 1 &amp; 3 it's when it gets a chance so 2 5 1 &amp; 3 it's when it gets a chance so 2 5 1 &amp; 3 so what we have to note here is that each note is sharing the same object so every time a node gets control of the recursive stack it's going to append itself to the list but they're all sharing the same list in the problem without we're solving right now this is not the case we're not going to be passing an object like a list of strings or a set of integers or anything like that but we're going to be passing a string so that's just an empty string think of it like a empty or empty array list but this is what we're going to pass the 1 and then 1 is going to append itself to the empty string now what 1 is going to do is it's going to give each of its children a separate copy and each child is going to append itself to their own copy similarly to is going to give its copy like a brand new copy to five and five is going to append itself to that now you can clearly see the string that each node is generating when we're doing our recursive calls since the question asks that we collect all the strings that have from that Traverse down the root to leaf paths all we have to do is collect the three and the five now I'm going to show you a algorithm visualization so you can understand it a bit better cool now that you've seen the visualization let's briefly go over the code is pretty short and concise since it's recursive but let's just walk through it now we have a list of strings which is the result and this is our recursive DFS call and we're trying to return what we're populating so if the root is null we simply return and every time a node gets control of the recursive stack it's going to append its value to the path so in the beginning it was empty and then when one gets control of it's going to be one that's the value of a path and then it's going to recursively give a copy to its left and right children while appending the arrow because that's what the question wants to the path and if a node is left four nodes left and right child are null meaning it's a leaf node then it's going to add its own path that it's received to the result so the time complexity is going to be open where n is the number of nodes just because we're going to have to visit every single node since we recursively checking the left and right child and the spaced complexity I'm going to just say it's the output size because we're not really using you know extra spaces the question is asking for a list of string and we need to visit nodes so depending how you define out the space complexity like if you're visiting the node or the recursive stack I'm just going to say it's the output size oh that's how you solve LICO 257 if you liked the video please let me know and thanks for watching
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
115
hello friends so today in this video we're gonna discuss another problem from lead code the problem name is distant subsequence so let's start the problem goes like this that you have two strings s and t and you have to turn the number of distinct subsequences of s which equals to t so there's also one example which is given to you as you can see what is a subsequence is a new string formed by the original strings by deleting some of its characters without disturbing the remaining character order so as you can see if you take the first example that is r a b i t and you have to remove some characters from the original s string says that it can become the new string that is t now how many like number of ways are there as you can see uh which is given in the exact explanation of this problem that if you take the first 2b and i t then it is rabbit if you take the like first and the last b and the last to be so there are three types like three ways to make this rabbit equal to the string cool now how do you come up with the solution like you want to match two strings okay now you have to match out how many number of substrate like subsequences you can form so in this type of problem first go to the uh like also the constraint part as you can see it is 1000 it means that you can do this in o of n square time complexity or lesser than that but maximum you can do that no offense square cool so now the first thing which comes to mind is because there are two strings and the constraints also small why not use dp here and for using dpr after first define on the state for dp so because you have two strings i will take a two dimensional dp that is dp of ij and a dpf ij will store the number of subsequences okay such that i so i have taken a string till i so uh such that uh total number of characters taken in string s is till i and number of characters taken in string t is till j so i have characters so i have two strings so let us take the same example that is r a b i t that is the string s and i have a string that is r a b i t that is equal to the string t now you want the same string t to appear in s so you have to delete some characters so the main thing is that if i have taken some i string till i this is not equal to i have like i move till the ith index so if i until this ith index and if i am on this let's say jth index how many substrings i have formed till now that is the whole solution like this is the tp state so now how will you do about it let us like talk about that case you will draw a dp table so let's say that i have two cases like i have two scenarios if i am matching two strings so let us draw the same example if this is s and this is t and i have two pointer that is i and j i have two scenarios the first scenario is i and j are equal the characters and inj that is sfi and the select t of j if they are equal then what will happen i can either take both of them and like move forward or i do not take the ss s character because i want to find out the substring like sub sequence is s so in every step i have to move s okay but j will only move when i will find a match what i'm talking about here is that i have to find this hole in this so if i'm on this character and i'm matching the with this character if they are same then this is a way a possible way to make it a match so i can either take both r and move forward so one of the case can be if this is the okay function that is a db from like recursive function we are talking about we will go through the code we will make it more clear so if this is i and j so i will pass forward both i will move forward by one and the j will move forward by one and the next step can be because we are adding both of the possibilities the other step can be maybe it can happen that there is one more r ahead so let's say that the string s can also be like this r a b i t and i'm like comparing this r and this r but one of the case can also be that i will not take this r and this can be also r a b i t okay so it means that what there are two scenarios if they're matching i can either take that r or i cannot take it out so the other case can be if i'm not taking this like if i'm not taking this my i will move to the next point that is my i will move to the next character but this will not move why because i'm not matching them this is only move when i'm matching if i'm not matching i'm just keeping the next character then i will not take that character so i will move because it's the ith pointer so i will move but j will not move okay and this is totally equal to answer that is for the dp state dp of i comma j the other case can be if they are not equal if the ith cat and jth character not equal what will happen in that case if they're not equal obviously i just will i will just move my edge character to the next point and j will remain at the same point because g will only move when both the characters are same so it will just go to that point at i plus one j that's it so you will have to write on a recursive function and when it will stop it has two cases either my i will reach in the end or my j will reach at the end like this characteristic or this characteristic these pointers if my i reach at the end and j is not reaching at the end which means that i have exhausted all my characters in s and t is not formed in that position so i should return zero at that point but if my if i have still i have not exhausted all my characters of s or maybe at the end and t has exhausted out it means that i have found a possible way in which t can be found out in s and thus in that scenario i will increment my answer by one so these are the two tp states if my the point i'm moving here is j if j becomes equal to t dot length or t dot size then i will increment it by one but if my i becomes equal to s dot size then i should make it equal to zero and then in all the intermediate states this is the recursive formula we're gonna use and that's the whole logic for this problem let us move on to a question like coding party will make it more clear so let us move on to coding part yep so what you can see here i have defined here at dp state which is this cool now uh this is the calling function i will initialize all the states with minus one so that i will keep tracking which state has we have seen it and which state we haven't seen rule which is minus one this is the calling function zero comma zero is the initial indexes of s and t and they are also sending s and t you can also make them s and t global and then you can also do that but understanding s t cool because we have to edit over s t and i also send snt as an addresses so that i don't want to make a copy and again cool then i will find the length of s and t this is the first thing the two base condition is if my j also remember that put this condition first then this condition it will if you put the second condition this condition before the this condition then it will give the wrong answer because we have to first compare when the answer is coming not the zeroth point this is the secondary part the first point is if my jth pointer that is iterating over the j substring the second substring this is the string sorry t then if at any point of time my j becomes equal to m then i have like uh perfectly find out a particular substring in s that is equal to t so i will turn one or if my i comes to an end that is n then i will return zero cool if uh if both of these base conditions are not met these are the base conditions then i will first check that whether the condition i'm looking for the state i'm looking for is in the db table so if it's not equal to my minus 1 we will return the dp table value else if dbtable is also not filled i have to calculate the value for that position the calculate value position can be i have two scenarios if sfi equal to t of j then i have two options that take that character and move the jth character also or take that character and not move the jth character so pick it or not pick it else if it is not equal then like take this scenario and therefore returning out like take this answer which i have calculated uh for whatever state you have like whatever option you have and take that answer and store it in a different table before returning so this is like many of the students confuse that in the end i'm just assigning the value no not returning but see that i'm returning also it just means that i'm returning total in this written return on the return statement but returning before like before returning we are just assigning that particular value in the db state so you can also do that you can first assign it and then return it is also fine but generally it is a practice that we assign it and return the same line okay but you can also do that you can first set down dpf i j is equal to total and then you don't total but this is also fine and that's the logic for this problem as you can see that we have made a dp table that is like storing the values so n cross n that is n square dp or like suppose space complexity is required also we are iterating over that whole table and like doing these all those things so time complexity can also turns out to be of n square so that's the whole uh solution for this problem if you still haven't doubts you can mention down thank you for watching this video i'll see you next time keep coding and bye
Distinct Subsequences
distinct-subsequences
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`. The test cases are generated so that the answer fits on a 32-bit signed integer. **Example 1:** **Input:** s = "rabbbit ", t = "rabbit " **Output:** 3 **Explanation:** As shown below, there are 3 ways you can generate "rabbit " from s. `**rabb**b**it**` `**ra**b**bbit**` `**rab**b**bit**` **Example 2:** **Input:** s = "babgbag ", t = "bag " **Output:** 5 **Explanation:** As shown below, there are 5 ways you can generate "bag " from s. `**ba**b**g**bag` `**ba**bgba**g**` `**b**abgb**ag**` `ba**b**gb**ag**` `babg**bag**` **Constraints:** * `1 <= s.length, t.length <= 1000` * `s` and `t` consist of English letters.
null
String,Dynamic Programming
Hard
2115
424
all right so let's talk about the longest repeating character replacement so you're giving the student s and integer K so you want to choose any later of us uh in the Stream and then change it to any operator and then you can perform the operation K times so you want to find out the length of the longer substring so uh quickly explanation k equal to 2 you can change a to b or B to a right so let me say B to a so line of four right or B to a oh sorry or a to B still Lane of four right but how about this uh B to a then the four right or A to B 904 right all right so let's talk about the solution I mean the algorithm right so I still uh I need a slightly window to be honest so I will just keep moving my window and then every single time it match you know updating you know I'll shoot your left window right by one um so I'm going to say I need a counter array for my chart for my every single chart and then since like the later can be anything right it's not only a and b it should be a to z right so A to Z and I also need to know my operation K times right so for example I starting here J starting here so a b so now um you are definitely increment your J position right by one every single time and then you increment your eye position when the maximum frequency for the current maximum frequency plus the K operation which is what less than J minus I Plus 1. so maximum frequency plus K so what does this mean maximum frequency is actually a little Windows the windows you got so we should which is supposed to be like for something like this right but if plus K is if this is greater I mean sorry if this is less than the J minus I plus one this is going to be what you need additional K operation to replace a letter all right so this is too much talking so let me continue so right now this is gonna be okay right a equal to one B was supposed to be zero and I shift right by one and this is okay I still keep updating my maximum frequency which is going to be a equal to 2. sorry and then shift right by one okay and b equal to one oh sorry uh k equal to one B is actually with zero but I can using the operation to replace b2a right so I can say this is allowed be put one and I checked my current position so zero one two minus three two minus zero plus one if this is greater than maximum frequency two plus one so this is still a lot right uh Y is 3 greater than three this is now okay so I don't need to shift the left pointer so I will keep doing this shift my right find her this is what maximum frequency is three for a and I check the condition three minus zero plus one the maximum frequency is actually three plus one still okay right 4 greater than four this is not okay this is not a good operation right I mean this is not a true operation sorry so I will shift my J that one right by one so the maximum frequency for B is actually two and I checked the checklist if statement this is going to be my if statement uh zero one two three four minus zero plus one greater than one maximum frequency is three k equal to one which is five user than four right so I know this is not okay this is a true statement I need to shift my left pointer so I will shift my left by one so when I shift my left right I need to erase the current chart in Array accounting array right so I will update my a to be also eight by one and then now I can now I need to work I need to still shoot my right pointer it doesn't matter uh they it doesn't matter the current size the current sorry the current Windows is not the it's not the valid substring it doesn't matter because I know like maximum length the maximum window was full right so I still need to shift the window right by one so I will just keep shifting shift my red pointer by one so I'll update my B to what two three so a was two so it was two B was three right so J position is what J position zero one two three four five minus one plus one which is greater than the maximum frequency is three plus one and this is going to be five greater than four okay this is not okay so I need to shift my left pointer by a right by one so I will get this but before I shift I need to decrement my account for eight you go to one so this is still valid right still valid and then I would just continue doing this until J reached at the end right J Russell yeah and then it doesn't matter I stop at this position or not because I know the value Maximus window was full right so I would just basically return so I was pointed at this right so basically I will return the total length which is going to be on minus I position so I will get a length of what the length of the substring so this is a solution so let me code it so I will have in I equal to zero right maximum frequency equal to zero and I also want to initiate my n equal to extra length and when I want to return a 9 a minus I right and I need a counting array new in 26. and then I start my J pointer on zero position and enjoy less time install lens and then J plus so I'll keep updating my maximum frequency every single time uh I need I definitely need to increment my contract so it's only purpose count restart chart at AJ and I need to subscribe by the capital letter a right so if you don't like this so if you don't like the line eight you can do like this so I'll say copy paste and basically like this so you increment your account and then um incremental account and just pull a number of the frequency in the content array and then if this is Autobahn a J minus I plus 1 which is greater than the maximum frequency plus k then you will definitely what uh decrement your account it's actually at I plus minus a so uh what does this mean if you don't like this then you basically you change to list so you're decrement your current position the current position value which is going to be a list document your letter a and I increment your left pointer by one so uh this is roundabout right so submit and I pause so make sure you know the clean uh look like the clinical it's going to be at least so I will just push sorry so I will just put back the increment um uh increment counting array coding style back then decrement accounting counting already back and then increment right after list line compile so it's still going to be the same idea so I'm gonna run it I'm going to submit so let's talk about the timing space so this is going to be a space the base space so it's going to be 26 constant the time is going to be a time for Loop and then in the photo there's nothing else right so it's gonna be all the fun don't representing of the string s so I'm going to just use a debug mode okay about more I'm going to pause right over here and yeah basically yes I'm gonna pause right over here as well start debugging and then look at the left window and I'm going to just keep doing this until the end so I'm not gonna I'm not going to explain because I pretty much just explained in the beginning all right so this is a I mean I'm supposed to be I'm supposed to use case two be honest so start debugging a case one is supposed to be easy be honest so I'm gonna break right over here all right so you know the solution was supposed to be easy all right so if you have any questions leave a comment below and then subscribe if you want it and then I will see you later bye
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
1,847
hey what's up guys uh this is sean here so this is this time a little number 1847 closest room okay so you're given like uh un-rooms in the you're given like uh un-rooms in the you're given like uh un-rooms in the hotel right so and each room is represented by a 2d integer array where the first element is the room id and the second one is the size of the room and then you're also given like k queries right where the first query item element is a preferred room id and the second one is the minimum size this query is looking for okay and the answer of the query is it's a room id is a room such that you know uh the room of course has the has at least the minimum size right and the uh and among all those kind of available right the rooms that can satisfy this minimum size so we want to find an id right that has the uh basically the id is closest to the preferred room id right and if there is a tie in the app in the this absolute a difference we return the smaller one right this is normal um yep so oh and if we cannot find like such room the room that can satisfy this uh the minimum size we simply return minus one right so here are some examples here you know so we have three rooms here you know this room has id two one and three so the capacity or the room size is two to one they're all twos and we have these queries right so the first queries you know the prefer id3 and the minimum size is one which means all three rooms are satisfied right with the current one with this one and with three one with this three uh we won't find the closest one which is three right so i because the difference is zero that's why we have three and for the second one you know since the uh the size the minimum size is three and which and none of the rooms satisfy this three that's why we have minus one third one is three because the two you know for three for five right so the last one i the preferred roommate is five and three is the closest one that's why we have this one cool so and here are some like uh constraints so it's pretty standard uh 10 to the power of five uh right constraints i mean this one you know um obviously right we want to sort right because you know so because one of the reasons we want to store this is because you know the first you know we with for this kind of query problems you know uh we have seen several like uh answer k queries problems you know usually for this kind of answer quick q queries problems we always want to sort uh this k queries so that you know we don't have to uh you know so that we can basically process uh a condition right a con an element in one direction and we saw we don't have to go back to reprocess the some i mean some data right so in this case so what's going to be the sorting condition here it's the uh it's obviously it's this minimum size right so we what does this mean it means that you know no we have a bunch of rooms right and we have this minimum size and if we can sort the queries from the biggest to the smallest room size right and then so the reason we want to sort by the medium size is because you know when we pro if we sort from the biggest to the smallest you know by the time we are at a smaller size id uh smaller size you know we will have more like available rooms for us to search yeah because you know every time we have like the minimum size we're gonna find all the rooms right that satisfy the current minimum size because if we want to find the room id that's the first step we need to do right and if we don't sort it no basically we have to us for each of the query ids we have to somehow uh look uh searched all other rooms right but if we sort the course ids queries uh in the descending order for the minimum size so by the time we're at like smaller minimum the minimum size you know what those of those are those available rooms for the bigger minimum size they are definitely will also be available for the smaller minimum size right that's why we sort the queries from the biggest uh by the minimum size in the descent in descending order right so that you know basically at each of the minimum size we're going to find the rooms right that satisfy the current size so the naturally right so when we find the uh the rooms can satisfy the minimum size since this one is sorting right we since we if we don't want to reprocess the rooms multiple times we also need to sort the rooms by the size right so that you know every time once we add rooms in our list like we can call whatever we want we can call it like available uh rooms or candidates whichever you prefer and then we know okay that rooms will be available for all the room for all the remaining queries so that we don't have to re add we don't have to add that rooms multiple times which means that you know our available rooms or candidates list always becoming bigger and bigger right and in our like a candidate's list once we have the candidates list right we want to find uh basically a room id who satisfied the second condition because in our candidates list right you know candidates list you know all we're going to save is the desire ids basically the room ids that satisfy this minimum size right but in order to find it you know we want to somehow sort this candidates list right because you know in order to find these ids efficiently you know we want it we want this all those kind of ids to be sorted so that we can find the uh basically the id that has the small smallest uh a difference because you know if it's a sorted uh id here you know and then we can just use binary search to find like a place right somewhere here where the absolute difference between some number is minimum right because we have to find that but after that you know uh and after that we also need to consider maybe two candidates maybe the one on the left and then the one on the right to make sure we find that the mini the id that has the smallest right because you know if this one falls in the middle we want to check both sides right but that's going to be another uh thing we have we need to be considered so which means you know now let's go back to these candidates right we want to make sure this one is like it's sorted um so for that you know we have to use some of the a different special data structure in python at least you know because you know every time when we like add like a new uh rooms into this candidates list we want to keep them sorted so in python you know we have kind of a sorted list right we have this one that can give us like a log n uh time complexity to either do like so operations in this sort of the list is a login right we can use this one but this one we have to import sorted containers package now or you know we can use like what there's like a bisect you know there's like a bisect insert right this one we might we also we might also be able to want to use it but you know this one will also pass or test case but in reality you know this bisect in sword the worst case scenario the time complexity is o of n it's not log n but still if you use this one to maintain the orders you know to maintain the others in these candidates this one it can also pass i would i can only say that maybe the test case is not like strong enough but anyway so we're going to use the sorted list to maintain this one and then we're gonna basically do a binary search on that yeah so that's basically the idea here right um cool so let me try to start coding here okay so like i said uh we want to sort both the rooms and the queries right by the uh by the size in the descending order okay so first let's sort the rooms uh we want to do a sorting uh i'm going to lambda function right so it's going to be x dot we want to sort by the second element in the descending order so which means it's going to be a negative x1 that's how we can do the sortings and second step will be sort the queries but since we want we also want to populate the final answers you know we're going to also maintain the uh the original index uh when we are doing the sorting it's going to crease that's why i'm going to add this origin index into this queries before sorting and since we're going to sort by the cur the minimum size right uh let me see i'm going to put it into the beginning right so and the curry and then the zero and then the i right that's going to be the arduino index so for i we have them of the query right in the enumerate uh queries okay so basically we add this at the index engine index into the query and then we also like put this as minimum size into at the beginning so that we can sort later on then we just when we do the sort right and then we simply do a reverse uh equals to true i mean we can also use this lambda functions right to do it here you know we always use also use like a key you know let's do this uh x0 right this will also works you know actually we don't have we don't even have to swap this one but i anyway so and then we uh we start we initiate the answers you know everything starts with minus one right uh it's gonna be a length of the course okay and then we're gonna have a and it's gonna be the length of rooms right and then i'm gonna have like a j right j is gonna be the uh that's from zero basically this j uh keep pointing to the next rooms we want to check and the last one is the candidates right the candidates are which is going to be the sort of the list you know like i said uh in order for us to use the story delays we have to import like a package so from sorted containers right import sorted list so now we can see we can finally uh start checking the queries one by one right so for queries we have minimum right the minimum size and the second one is the preferred id right so since we i swap this sequence here and then the last one is the original index right in queries okay so first you know first we add rooms right to candidates whose minimum size is either equal or greater than discontinuous minimum right basically while j is smaller than n and then so j plus one right and then while well smaller than n and uh in the rooms right j of one right is either equal greater than m then we do a candidates right candidates dot add we only need the room's id right which means it's going to be the first element okay and what else so now we search right search the room id from candidates so first we check if the candidate is not empty right otherwise we simply skip that so we do search we do index right so the index is going to be a candidate dot bisect you know this is a bicycle lab actually bicycle knife is the equal to the bisect uh it's going to be a we search the preferred id right but here you know like i said we ideally we need to check both uh both side right you know let's say we have 1 2 6 10 right and then 12 right so this is the candidates and if the likes if the p is what p is like right so if p7 so which index we'll have like this one we'll have indexes pointing to this one right since we do like uh bisect left but for seven you know seven if we just use index for this one we'll have like ten but our the better answer is six right so which means that you know besides index you know we also want to check the index minus one that's going to be the two uh like uh candidates and we among we want to check but they're like some other like uh add case you know because you know when we do the search you know the index could be at the either it could be index 0 or it could be at the end of the of this list right because you know let's say if the p is you know let's say this is not two maybe two or two and four okay if the p is equal to one right so in this case you know uh the index will be zero right and the index minus one will be mine will be minus so in this case the index minus the other candidate is not valid same thing for like if the p is equal to 20 or is equal to 15. in this case index will be out of the boundaries right instead and then in this case index minus one is the only option we have uh where the index is the invalid case basically we have to handle that right this uh different special case i mean you can use your own way but i'm just going to call the way i do it so since we have two candidates we want to consider i initiate them to candidates one and two is a system uh max size right so the reason being is that you know later on we're going to use this one to do a different absolute difference with the p so if i initiate and then we're going to get uh choose the one who has a smaller absolute absolutely different right so if we initiative is the system max values you know the ones that has is not valid will definitely not have like a smaller absolute difference okay and so the candidates one okay so maybe so the candidate one is index and the candidates two is index minus one okay so there so for each of them there's a there's like an invalid scenario okay so for index one uh sorry for if we index uh we set the index when the index so we set the candidate one when the index is smaller than the length of the candidates right this means that you know this index is inside this candidates this is when we do the candidates one equals to the candidates.index right candidates.index right candidates.index right and then for the candidate one i'm sorry for candidate two we said that when the index is greater than zero right this is a otherwise you know the candidates the candidate two will be negative value this is when we set the candidate two equals to the candidate of index minus one okay and okay now we want to check the absolute difference for this kind of two candidates and another thing that you know we have to be consider is that if there's a tie if the difference is it's up it's the same then we want to use the smaller id and which one of these two is smaller the candidate two right because the candidate two is index minus one and this candidate is it's sorted right that's why we need to do something like this so basically if abs of the candidate two minus p is either equal or smaller right than the absolute of candidate one minus p so which and then i'm going to use the candidate two in this case otherwise candidate one right because here you know i'm using this kind of like a smaller equal sign here when uh when there's a tie and i use a smaller one otherwise i use the other one so here i return the answer right that so that's it cool so run the code oh there's a typo i think query is here all right accept it submit candidate 2 refers huh oh so many typos sorry about that all right cool so it passed right um yeah i mean oh the time complexity um so time complexity should be shouldn't be that hard to analyze right so let's say we have this is n and k right so the rooms is and so to sort the rooms we have well what we have unlogging right so we unlock n and then we have what we have k log k right okay log k sort the queries and then here uh we loop through the query right uh basically this is going to be the k right times what and we add these candidates so the candidate is kind of going to be the number length of n right and since this one is a log n so it's going to be a k log n yep oh and here is like another bisect right but here you know since the search you know it's also like a log n right so this one doesn't change yeah basically that's the uh the total time complexity a lot of log n or log k in this case right so that's pretty much it is right i mean so the key pro the key thing for this problem is that we have to somehow you know sort you know find a way to sort this both rooms and queries so that for each queries uh we only for each of the queries we only will only add uh the available rooms once into this candidates list right based on this minimum size right then after that uh once we have candidates you know uh we can simply just do a binary search and since we want to do a binary search we want this we need these candidates to be sorted that's why we chose to use the sorted list in python to achieve that and the right the last things that we have to consider this uh two can two candidates right uh the smaller one and the bigger one but those are kind of minor things right all right i guess i'll stop here and thank you for watching this video guys stay tuned see you guys soon bye
Closest Room
largest-subarray-length-k
There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed to be **unique**. You are also given `k` queries in a 2D array `queries` where `queries[j] = [preferredj, minSizej]`. The answer to the `jth` query is the room number `id` of a room such that: * The room has a size of **at least** `minSizej`, and * `abs(id - preferredj)` is **minimized**, where `abs(x)` is the absolute value of `x`. If there is a **tie** in the absolute difference, then use the room with the **smallest** such `id`. If there is **no such room**, the answer is `-1`. Return _an array_ `answer` _of length_ `k` _where_ `answer[j]` _contains the answer to the_ `jth` _query_. **Example 1:** **Input:** rooms = \[\[2,2\],\[1,2\],\[3,2\]\], queries = \[\[3,1\],\[3,3\],\[5,2\]\] **Output:** \[3,-1,3\] **Explanation:** The answers to the queries are as follows: Query = \[3,1\]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3. Query = \[3,3\]: There are no rooms with a size of at least 3, so the answer is -1. Query = \[5,2\]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3. **Example 2:** **Input:** rooms = \[\[1,4\],\[2,3\],\[3,5\],\[4,1\],\[5,2\]\], queries = \[\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[2,1,3\] **Explanation:** The answers to the queries are as follows: Query = \[2,3\]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2. Query = \[2,4\]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller. Query = \[2,5\]: Room number 3 is the only room with a size of at least 5. The answer is 3. **Constraints:** * `n == rooms.length` * `1 <= n <= 105` * `k == queries.length` * `1 <= k <= 104` * `1 <= roomIdi, preferredj <= 107` * `1 <= sizei, minSizej <= 107`
Search for the largest integer in the range [0, n - k] This integer is the first element in the subarray. You should take it with the k - 1 elements after it.
Array,Greedy
Easy
null
204
hi guys my name is khushbu and welcome to algorithms made easy in this video we will see the question count primes count the number of primes that are less than the non-negative number given to us than the non-negative number given to us than the non-negative number given to us which is n in the example one we are given is 10 and we can say that there are four prime numbers between number 1 to 10 which are 2 3 5 and 7. for example 2 we are given n equal to 0 and the answer would be 0 over here same for n equal to 1 wherein our answer would be 0 because in the number series when you start from 0 the first prime number would start from 2 so let's go and see how we can solve this problem suppose we are given n is 10 so we can see that 1 is a non-prime so we can see that 1 is a non-prime so we can see that 1 is a non-prime 2 is a prime number 3 is also a prime number 4 is a non-prime number because 4 can be 4 is a non-prime number because 4 can be 4 is a non-prime number because 4 can be divisible by 2 and 1. 5 is a prime number 6 can be divisible by 2 3 and 1 and so it's a non-prime 7 is a prime and so it's a non-prime 7 is a prime and so it's a non-prime 7 is a prime number 8 9 and 10 are non-primes so 8 9 and 10 are non-primes so 8 9 and 10 are non-primes so we can say that within number 1 to 10 we have four prime numbers in this video we will see one of the famous algorithms that is used to count the number of primes we have which is called sieve of eratosthenes now let's see how this algorithm works suppose we have got the number as 30. over here i have taken an array of 30. so this is going to be a one dimensional array but just because of lack of space i have divided into three rows the first row over here is 1 to 10 11 to 20 and then this is 21 to 30. now what does this array represents this would represent true for all the composite numbers and false for all the prime numbers so initially i have marked everything as false stating that all the numbers are prime and now we'll start iterating so as we know 1 is not a prime number it is a composite number so we'll mark true for the number 1 and we'll start with 2 because 2 is a prime number we'll be taking it as false and we'll mark all the numbers which are multiples of 2 as true so that gives us all these numbers marked as true because these are the multiples of 2 and so these are also divisible by 2 other than being divisible by 1 so these would become our composite numbers now we'll move to 3 now 3 is also a prime because it is still false and we do not have any number which could be multiplied with another number to give us 3 so that's why 3 is false right now and so now what we are going to do is we will be marking all the multiples of 3 as composite so let's see what are the multiples of 3 you get 6 9 12 15 18 and so on so we'll be marking this as true and now we move on to the other number which has the value as false since 4 is divisible by 2 and 1 we have true in 4 so we will be moving on to 5 and we'll mark all its multiples as true so this becomes true and then we move on to the next number which is a prime number or which does not have a true value associated in the cell which comes out to be 7 and now we'll mark all its multiples as true now if you see that all of its multiples that were there are already marked true so there was no change in the array for the prime number 7 moving to the next number which is 11 that is also a prime number we need to mark all its multiples as true and we can see that 22 was already true now we go to 13 and mark its multiple as true which would give us 26 which was already true again and this loop was having no effect on our array next we move on to 17 now do we have the multiple of 17 in this particular range no because 17 multiplied by 2 would give you 34 and that goes out of the range so we need not worry about the numbers after this 17 and all the numbers that are still false are already a prime number and so we can just iterate over all the numbers now and check whatever values are false are the prime number indexes and so over here for this example we can find that there are nine prime numbers now what are the derivations or what are the properties that we saw while iterating for this n equal to 30 let's check we saw that for every number that we were iterating for that is every prime number for which we were marking the composites the first composite that was found false and we had to turn it to true was the number i into i so over here you can see for 2 the first number is 4 for 3 the first number that was marked false and we needed to mark it true was 9 for 5 the first number that we needed to mark was 25 and for 7 11 13 we did not have any numbers that we would have marked so over here we can say that the first index that was needed to be changed to true would be starting from i into i and the second thing that we are going to note over here is that the only change in the array happened till this 5 which is equivalent to root of n and so we can say that the last digit for which the cell values could have changed in the array is square root of n because if you go after this 5 that is if you go for 7 the first value that could have changed would have been into i that is 49 and 49 is falling out of the range for n equal to 30 and so there wouldn't be any value after this 5 that would affect the array that we are having and so these are the two properties that we can take care of and remember while solving this particular question so let's go ahead and code this particular approach out that is we will be taking the primes and marking all its composites as true and finally we'll check for the array and whatever is false is the prime number and so we can count the prime numbers that we are having the first and the foremost thing that we can do is if n is less than equal to 2 we can just return 0 because in that case we are just checking for 0 and 1 that is less than n and we already know that 0 and 1 are not primes for the rest we need to create a boolean array and this array would be of length n and now we'll take a for loop and our for loop will start from i equal to 2 and would go up to square root of n so let's take the limit till which we are going to go and that limit would be the root of n and since this is a double we need to convert it into an integer and over here will go only up to limit and we'll do i plus so that's our outer for loop wherein we are going to check whether the value that is there at that particular index is false or true and if it is false then and only then we are going to find the composites for that number so we check whether the value is false and if it is false we are going to mark all the composites of that particular number to true and the other thing that we saw is that the first index to be flipped to true is i into i so will start from j equal to i into i j is less than n and j plus equals to i because we need to mark the multiples as true so this would give us the next multiple in the next iteration so what we are going to do is composites of j is marked as true so this would give us the array of composites wherein true represent composite and false represents primes so since we have the array filled we just need to iterate over that array and we can start from i equal to 2 because that is our first prime i less than n and i plus and if the value is false we can do a count plus and that count will represent my prime so let's take count equal to 0 and finally just return the count and this will go till the square root rather than less than the square root so that's one of the mistakes that we made let's correct that and run the code and it's giving a perfect result let's try it for a random bigger number and it's giving a perfect result let's submit this and it got submitted the time complexity for this particular approach is root n for the outer loop multiplied by the time complexity for the inner for loop now the inner for loop has a time complexity of log of n if you want to go and check it out the link for the proof is given in the solution part over here and you can check out the proof how it is coming out to be that the space complexity is of n because we have used a boolean array of length n so that's it for this video guys i hope you like the video and i'll see you in another one so till then keep learning keep coding
Count Primes
count-primes
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`. **Example 1:** **Input:** n = 10 **Output:** 4 **Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7. **Example 2:** **Input:** n = 0 **Output:** 0 **Example 3:** **Input:** n = 1 **Output:** 0 **Constraints:** * `0 <= n <= 5 * 106`
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors: 2 × 6 = 12 3 × 4 = 12 4 × 3 = 12 6 × 2 = 12 As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n. Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach? public int countPrimes(int n) { int count = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) count++; } return count; } private boolean isPrime(int num) { if (num <= 1) return false; // Loop's ending condition is i * i <= num instead of i <= sqrt(num) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i <= num; i++) { if (num % i == 0) return false; } return true; } The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple. Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0. We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime. The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia. public int countPrimes(int n) { boolean[] isPrime = new boolean[n]; for (int i = 2; i < n; i++) { isPrime[i] = true; } // Loop's ending condition is i * i < n instead of i < sqrt(n) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i < n; i++) { if (!isPrime[i]) continue; for (int j = i * i; j < n; j += i) { isPrime[j] = false; } } int count = 0; for (int i = 2; i < n; i++) { if (isPrime[i]) count++; } return count; }
Array,Math,Enumeration,Number Theory
Medium
263,264,279
921
welcome back everyone we're gonna be solving Lee code 921 minimum add to make parentheses valid so in this problem they give us a parentheses string and we need to return the minimum additions we need to make in order to make a parentheses string valid so let's take a look at example one gives us the string of an opening bracket a closing bracket and then another closing bracket now clearly this string is not valid because the only valid parenthesis string that we have is this opening bracket and closing bracket right whenever we have an opening and closing bracket that match that parenthesis is valid so we have one closing bracket that doesn't have a match so the minimum additions we would have to make to this string is one right we'd have to add an opening bracket either at the front or just after this first closing bracket in order to make this string valid so how can we solve this well we can use a stack so let's initialize this stack equal to an empty array and what we're going to do is we are going to Loop through every character in our given string so let's take a look at example one again we'll start our for Loop we'll grab this first character if that character is an opening parenthesis or you know we don't have any items on our stack we're just going to add that character so we'll add that opening bracket onto our stack now we come to the second iteration we see that we have a closing bracket so what we want to do is check if we have characters on our stack and we have run into a closing parenthesis what we want to do is pop that last opening parenthesis off of the stack right that means we found a match and we don't care about it and after we run through this entire Loop if we have any elements or parentheses strings on our stack right we can just return the length of our stack and that'll give us the number of minimum additions we need to make in order to make this parenthesis string valid so essentially what we're doing is looping through the string looking for valid parentheses already if they exist removing them and then just returning the number of invalid parentheses that we have right and that'll give us the number of additions we need to make the string valid so we'll say four character in string what are we going to do we're going to check to make sure we have elements on our stack so we'll say if the length of our stack is not equal to zero we're going to do something but first let's handle the case where our stack is empty if our stack is empty all we want to do is just add that character onto our stack so we'll say stack dot append that character okay now we can handle the case where we have elements on our stack so if we have elements on our stack and the current character we are currently at is a closing bracket and the very last item on our stack is an opening bracket it means we found a match so we can pop that last item off our stack that's what we want to look for so we'll say if the current character we are at is equal to a closing bracket and the last item on our stack is equal to an opening bracket we found a match we just want to pop that item off of our stack and continue on with our algorithm right otherwise all right if this condition never gets executed we just want to add that uh character onto our stack so stack dot append that character and then at the end what we can do is just return the length of our stack so let's run this perfect we pass both test cases so we'll submit perfect it does run so time and space complexity time complexity we did this in one pass so it's going to be o of n We're looping through our string and touching every character at least one time space complexity is going to be bound to the length of our stack so space complexity will be stack dot length all right that'll do it for Lee code 921
Minimum Add to Make Parentheses Valid
spiral-matrix-iii
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at any position of the string. * For example, if `s = "())) "`, you can insert an opening parenthesis to be `"(**(**))) "` or a closing parenthesis to be `"())**)**) "`. Return _the minimum number of moves required to make_ `s` _valid_. **Example 1:** **Input:** s = "()) " **Output:** 1 **Example 2:** **Input:** s = "((( " **Output:** 3 **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'('` or `')'`.
null
Array,Matrix,Simulation
Medium
54,59
72
hello friends today less of their added distance problem this is a classic curtain make programming problem let's first see the statement given two words or the one in word to find the minimum number of operations required to convert what the one you were to you have a following three operations permitted on a word insert a character delete a character replace a character let's first see the example one input is the world one is host where two is rose and now we output 3 because we first replace H with R and then we remove the middle R and then we remove e so how do you think about this problem the problem seems abstract if you first a seat but you can see invalid if we have to convert like we needed to convert or e-reader to like hi the total number we e-reader to like hi the total number we e-reader to like hi the total number we need to convert the world want you were to is like based on if we converter we read to H hi this is one possible commercial we convert to ie a too high which means we just needed to add one operation right because we inserted D in the end that this is one possibility another 8 that we the total number of converted Rida to H because we just add a one character in the end of H so there will be the tour number of convert reader to edge the last one and also we can use replace so it can be I EA converted to edge and there will be their total number 2 plus 1 because we just convert like a replace this did you the I so as you can see we can get to the total number of convert what want to world to pass on their three like the three operations plus one so in this case we can use dynamic programming to solve this question because it had overlapping subproblems okay so let's solve it we will first take out the lens over the word one and then we get to the lens of the word - we then we get to the lens of the word - we then we get to the lens of the word - we use another to use another 2d array DP and there it means that there it elector distance or converter there number of the characters so there's a reason we +1 the characters so there's a reason we +1 the characters so there's a reason we +1 because if when the world one is 0 if we need a two converter would want word to the number of the elector distance should be the length of the word - should be the length of the word - should be the length of the word - because we just insert your characters the same idea if the word - is lengths the same idea if the word - is lengths the same idea if the word - is lengths of 0 the elector distance convert 1 want word - is the length of the world 1 so word - is the length of the world 1 so word - is the length of the world 1 so that is the like the base case order initialization so let's do it so when there I could use your allies I call them and I plus are we are first to fail older value in certain in the DVR rate shooter integer max value because we want to get to the minimum number of operations so initialize with the integer max value but we need the to change the DPI zero to I that means that will word one have the length of I and the word to have the length of 0 the Elector distance is I because we just insert the characters so the same idea when there J equal to 0 J let's go there and J plus the deep heap 0 J means ego 2 J that means the world will have length of 0 and the word to have a lens of J so the tonal for other operations is J and then let's start from the very beginning if I go to 0 I less than an I plus and the 4 into J equal to 0 J less than and J plus we will get to the current atchoo character the first 8th word one char at high in the city will be word to char at J so if C 1 equal to C 2 then their total number of the operation we see the edict distance is the same with the previous one because we didn't do any operation but if not the same we know that we have three operations can choose so we just choose the minimum one like is their DP I plus 1 J and their mass Tom minimum D P I J plus 1 there will be D P I J and their plus 1 so what does that mean DP I plus 1 J there will be there 8 editor distance to convert like converter this one there is the same right by the J lesson Wow we just inserted one character at the end of world to get this high so there will be one insert operation so we plus one so the same DP IJ plus 1 that means we insert one character at the end of the world wall so we also add one and the DVI J that means we do the replace operation we also add one so we just pick the minimum to arawa so finally we'll just return em and there will be the Edit distance to convert what 1 2 or 2 okay thank you for watching see you next time
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
1,982
hey everybody this is larry this is me going with q4 of the weekly contest 255 find a way given subset sums so you may notice that i actually didn't stop this during the contest i actually saw this about 15 minutes after the contest and you can actually watch this live aft after my explanation um it's very long you could fast forward for it if you like but hopefully you can see my thought process there maybe i actually got very close um but i was missing one insight that i think i got later on but it was too late and i was a little you know i stopped it after the contest i am proud and happy that i solved it after the contest because only like 50 people got it or less than 50 people stopped this one during the contest so maybe just a little bit afterwards i said the right idea and this one actually i'm gonna go over kind of two solutions uh if you will one is my solution that i solved um live as you can see but i have a hacky way of re fixing a bug where i'm gonna go over uh using code review another solution where it makes even more sense but the logic is gonna be the same it's just that there's one step in which one observation in which i couldn't figure out um until the very end but i didn't put everything together because i just ran out of time um so maybe i could have gotten it that way anyway so this was a very hard problem so you know give me some support by hitting the like button hit the subscribe button if you haven't already uh join the discord as well if you want to talk about this problem or other problems during the contest and if you enjoyed these contests then you know come ask problems as well uh anyway so this one is find a way given subset sums so i did this in a bit of a hacky kind of way um as i mentioned uh so the thing that i did was just trying to figure out things out right um the first thing that i did and it actually wasn't necessary is to figure out the number of zeros so the number of zeros is this thing um and what is this thing right is that basically we look at all the frequency together then the max number um you know let's take you know this input and if you after you sort it or i guess you don't have to sort it you put in the frequency table the max number is going to appear x times and that x time is actually going to be a power of 2 for every 0 in the original input and that's basically the idea you can kind of prove to yourself this is right but yeah but that's kind of the idea and then after that i end up skipping every uh x number for x as the number of zeros because like i said that many duplicates right so now let's go to um and it's not i mean it doesn't it may be a duplicate but there may be also more numbers in the middle right so it's not the max frequency but it's the max thing so for example let's take a look at this thing um yeah so in this case they're two nines so that means that we know that there's gonna be one zero um even though they're four fours um and the reason why we know that there's gonna be one zero is because one of the zero it could appear or not appear and in that case it doubles every input right so that's my logic you actually don't need this but that's the way that i kind of figure it out um so then now let's say we now reduce this to um okay that's actually really quickly uh yeah i actually had a lot of test cases um because i got it wrong a lot even afterwards but for the purpose of this one we can print out for now uh let's see so i just i wanted to give us better visualization so i can so for this one let's print out sums and my computer is kind of slow right now so yeah uh what is what do we get and this one is four okay so this is the sorted thing right and the thing that i noticed was that um if you take the biggest two numbers or the smallest two numbers um and i think this is the part where i messed up uh because i took because i was trying to figure out whether there's signs and stuff like that but actually it should be symmetric um and i think that's the part where i messed up when i was doing it during the live contest but you can see that there is either a one in here or a negative one in here we don't know the signs for this one but and actually i think now that um yeah let me rewrite this code um so that's basically the idea right so now you know that there's going to be a one or oh sorry oops a one or a negative one in there why do i think that because um because of one observation right the biggest number or the biggest positive number contains all the positive um all the positive numbers right and the biggest negative number or the smallest negative number contains the sum of all the negative numbers and then so that means that the second biggest number is the only two possibilities one is the only two possibilities right one is that um the second biggest number is the sum of every number uh minus one of the positive numbers or the sum of all the positive numbers plus a negative number right so basically that is the idea um and then boom how do i explain this because this code is actually not what i want it to be now uh let's say delta z so now let's actually live write this a little bit more even though you can watch me solve this live donor contest and after the contest actually but yeah so this is the delta um we actually want to append delta and then now the two possibilities right like we said it's either positive or negative um so then now the two ways to kind of create a new array that's the way that i would think about it because here let's say we were at this stage right sorry this is a little bit hard to follow this is a really hard problem so this is gonna be hard to follow let's say we're at this stage and so there are only two possibilities one is that the answer is a negative one that's actually yeah don't look at this code quite for now because this is probably wrong um yeah so the only two possibilities is that this is a negative one if this is a negative one then what does that mean that means that um we want to go from smallest to the biggest and because if this is negative one then subtracting from the smallest number will give us zero and we know that this is a pair and this is a pair right so then in this case we want to take 0 4 5 9. if possible is negative one if possible is positive one then we then the answer is going to be um we go the other direction right we go eight four three negative one why do we go into the other direction um because we know that one number is negative one that uh one number is one that means that this uh the biggest number is no longer possible right so then you have this number um yeah and of course i'm just reversing the way to here and of these two things one of them has to be true right um does that be because yeah um yeah so basically if this the biggest number is a negative number we do this thing if the number is a positive number we do this thing right um yeah and the reason why we choose this one is because there's a zero because we know that zero is in here because um because zero because uh an empty subset sum is needed um because zero represents the sum of zero elements right so you know that this has to be in it and therefore this is not true so basically here um okay that's actually not append this so from that logic we can go okay for x in sums so now we take either if you look at how this is laid out we either take the na positive in the outside the even number indexes or the odd number indexes so we can try something like oops if index so if this is numbers then we just do evens is you go to um was it x else odds append x right so even is equal to mt r is equal to mt and as we said if zero is in um if this is in the odds position then it is so if 0 is an odds that means that this is here then possible is the negative version so n start append negative possible else and here we also want to update the next array because now we can think about this recursively because now we have this number and we have one few numbers so what is this thing well so now we got rid of the negative one so then now we go okay well now we just take here and four either four or negative four is in the answer uh of course this is gonna be four because there's no you know but that's basically the idea so um yeah uh yeah so basically this we just update sums is equal to uh odds and sums is equal to events so i think that's basically it i did a lot more other stuff oh wait no this is not right uh sorry friends i kind of messed up here um because i made this mistake during the contest as well is that i skipped every other one but you don't it's not actually under every other one right because you're trying to match x with x plus possible so this is actually not quite right because this is actually it's not every index so yeah so we actually have to change this a little bit sorry about that uh so here we go if f of x is greater than zero um then we do uh this mine is possible and i think this should be good f of x we subtract one and f of x minus possible we subtract one as well so basically what this is doing is just matching uh let's see f is equal to collection dot download of sums right and then now and i actually did something similar here uh yeah and then that's basically the answer to be honest i have this other thing um and the so i'll give a little background about it but i think this should be good let's actually run it real quick oops so live explanation this is our range what really i guess sums could be zero wait what do you where how let's see so you do get to get a second chance to live debug but that's basically the idea that i have hmm can i mess this up um oh yeah whoops i use the wrong one does that matter maybe i think it should just at least not like this hmm so yeah so sorry about that it's a little bit sloppy um the reason why i did this is because as i'm extruding the explanation i noticed these um these like one i noticed a better way of explaining and two to better visualization which now i finally see why i wasn't able to solve it through the contest i was able to see um the real way of doing it um and except for now i have an implementation issue which is a little bit awkward uh why is this empty though oh whoops i didn't take out the enumerate okay that is just silly yeah so this is mostly good except for the signs are opposite um so yeah well actually except for this one maybe i'm wrong here but huh so if this is odds then texas motors okay i think this is good let's run it real quick all right i still have a lot of point i have still a debug statement okay i think this is good let's say this is good um this is negative 11 should be in this sum what is this input i have so many inputs i didn't even know which one to debug now um okay so you get to watch a little bit of a live debug that's kind of cool right maybe not i don't know sorry friends so negative 13 is in here but negative 13 is not in this one so i am actually wrong on this a little bit let's see where am i where did i go wrong did i mess up this it's just that okay i just messed up the science one more time okay i was right the first time okay so yeah i was a little bit sloppy but basically we're going from the smallest to the you know we're going from smallest to the larger number so events means that um i guess it's no longer evens but this is the evens is the next number wow so actually i messed up on the vocabulary because i kind of did them in the wrong order um so yeah so maybe this should be that and then here this should be the case more maybe huh okay i mean this is now right except for everything is uh exactly opposite okay except for some other cases for some reason okay so yeah so that's basically the idea um sorry if this explanation is a little bit slow it includes some live coding because like i said my original coding was a little bit of a hack and you can kind of if you fast forward near the end you'll see how i came up with it um because i did a lot of hacky things to try to um try to get it to work and i did get it to work actually at the very end um but that said you know so there are multiple ways of doing it but while i was kind of doing this explanation you saw that insight where i'm like oh actually it doesn't have to because i thought that it had to be one of the two but actually it could be either of the two and here the insight is noting that the zero is in one of them so then you have one of these things and that makes it so that i don't have to do anything um in the other case so what happened was that i actually got the signs really wrong um and this is just to kind of give you um an example of don't give up if you keep on grinding you can get it even if the your ideal your solution isn't ideal so one thing that i noticed with my original solution was that and let me see if i could kind of pull it up real quick yeah i'll pull up that solution um real quick um and this is just for illustration um oh wait i don't think this is the one that i no this is not the one that i was wanted sorry give me a second friends so this is actually the solution was mostly right but i had some issues with the signs as you see i get a wrong answer on this one if there's signs um and the idea here is that i don't know this is just very yucky um but somehow it worked enough that i don't know why this works enough to be honest this is just a lot of if statements of me going with cases but actually i was wrong in one of the assumptions but it basically gave me the right numbers but not always the right signs so what i did instead let me actually go to this no so what i did instead okay sorry friends uh what yeah so i had a couple of issues but yeah so what i did instead was so i had even a lot more if statements but so what i didn't said was because when i couldn't figure out the signs or rather i had the signs or i had the numbers but i couldn't figure out the signs for some reason but all the numbers were correct i couldn't i don't know why uh maybe someone who knows better math can look at this code and be like oh yeah but so what i did instead uh one inside that one hack i did right after the contest or near well not right after the contest but like ten minutes after contest was okay if i got all the signs why don't i just brute force it uh and that's basically what you saw at the end of the code i basically first okay let's brew force all the possible signs um and what would that look like well as i said all this the sum of the negatives would have to be the smallest number in the original sum and the sum of all the positive numbers would have to be the biggest sum in the original sum so i basically did a brute force on that which is 2 to the n but 2 to the n is fast enough because that's the size of the input and n is equal to 15 so that's only 65 000 anyway um so yeah so this is 2 to the n times n but it was fast enough so my lesson here is just don't give up and keep trying uh even if it's good enough right and an ac which is accepted anytime your solution gets accepted it's fine right so anyway um okay that's set let's go with this complexity um yeah so ignore i guess i didn't actually need now i no longer need all this stuff i probably don't even need this anymore to be honest but ignoring no zeros for now because that's even easier to operate um this loop we add one number to the loop every time so this is going to be o of n and for each n we do two to the n uh work because sums contain two to the n elements so this is going to be o of two to the n each loop so then that means that the total complexity is n times 2 to the n in terms of space this is also going to be 2 to the n because initially sums is equal to um 2 to the n and then it's going to and then the next elevation is going to be 2 to the n divided by 2 and then 2 to the n divided by 2 and so forth um of course if you know what that summation is it's just two to the n plus one so yeah and actually in that case this is actually uh tighter bound is o of two to the m plus one which is equal to o of 2 to the n because this is actually o of you know 2 to the n plus well not roughly 2 to the n minus 1 plus dot 2 to the 0 which of course is just 2 to the n plus 1 which is what we have here right so this is actually o of 2 to the n where n is the where 2 to the n is actually the is actually linear right because the size of the input is 2 to the n so this is a linear time algorithm uh space and time um so yeah uh i met so that's all i have really um i'm really proud that i solved this after the contest without any help uh even though i did it in a very hacky way and then i learned the cleaner way after reading some code reviews which you can see me actually doing it live but i think the key observation was this one actually but even without needing it i apparently could have gotten the answer by brute forcing but i didn't so and he's not doing a contest but i did it afterwards so they're more hacky ways of doing things sometimes but you know as they say an ac is an ac um so that's all i have with this one let me know what you think hit the like button hit the subscribe button join me uh join me on discord and you could watch me solve it live during the contest next let's fasten up in most languages say what oh subset sums n is 15. always at least one command hmm okay oh because it can be negative i was going to say the max would be in it but it might not be the case because of negative numbers can we so the max positive number we don't even know how many i'm gonna do this but okay so the max positive number is going to be the sum of the positive numbers and max negative numbers gonna be the sum of the max negative numbers but is that good enough for me to know anything hmm selected yet and every number has to be in the list as well for one number so can i figure that out wow four minutes and they haven't finished q4 yet so that's a little bit tricky well the smallest absolute value now that's not true i was going to say that has to be on the list but i guess that's not true since it was five now it's actually i guess so oh it has to be in there this it has to be in there because this no that's not true because you can have zero negative three or you can just have two numbers negative three and four and this total to one and you would have zero one two three four and maybe there's another possible answer for this i don't know if i know this one all right someone got it so turn to the floor can i use this 10 to 4 somehow this is in my face so hmm 2-15 is about 65 000. 2-15 is about 65 000. 2-15 is about 65 000. 32 000 is that hmm so the max is going to be the sum of the positive numbers and even is the sum of all the negative numbers so we have to figure out a way to work all that together and only tend to do trying to play with some small numbers to figure it out but that is tough well let's see okay so people are starting to get it but i don't even have an idea well it's only 15 numbers so i have to try to think a little bit easier maybe can i choose another thing is that it's so hard to wait examples because even for small things there's so many combination already so people already got it i really don't even have any idea but i just want to see why this is a unique example or whatever my this that's only 40 to the fourth time some stuff but okay fine is that way too slow i guess 40 to the fourth is a little bit slow and now i don't know okay so there's a lot of possible solutions well okay that's actually because it could be the same do they have to be distinct nope there's only one example hmm this is unique to this particular thing then how do we go about it and i don't expect this to give me more answers but okay so it's not okay so looking at the two maxes that means that one of the numbers have to be on the thing okay huh looking at the max end of the second max and we can figure how many odd and even numbers there are and zeros okay i feel like i'm getting some ideas but it's still going to be very hard uh okay so the zeros are actually the number of symmetry because i think if you sort this you just have everything times two so actually that's that makes it a little bit easier maybe yeah so that's just everything times two so that means that so i'll try something real quick well this you so this has three zeros and we have one how many tubes are there one two three eight so then this is the number zero should just be two to the power of whatever um because here is four okay that makes sense okay so negative one frequency of that and then so just a frequency of that how do you do log2 lock base two or whatever um okay so it's just minus one oh i just have another five one here anyway okay and now what do we want to do now that we got rid of all these zeroes this is doable maybe in the hour that i have uh i want to divide her away but and the question is how do you do it so i think i'm able to get one number based off that but can i um oh i think you can get the number of positive and negative numbers as well that's not true maybe not maybe i am not able to get it but you can figure out the skills later uh so hmm okay so then now we got rid of zeros now what do we do this one clearly have one negative number that doesn't have to be true let me think so and i mean in this case there's a negative number and even then what do you do after you get that one negative number oh you subtract it from and you can really match these up okay i buy that and quickly match the other side up as well okay actually i think i mean that's reasonable okay i think i have an idea then oh it's still a mess tradition increase one number at a time how many negatives and how many positives and there's always one zero remaining anyway and here this is on three numbers left hmm what if the duplicates i think that's the issue that i don't know yet still i just need a scratch pad of let's say we have one so when this before oops so if we have multiple ones okay so it still shows up here one at a time is that true hmm so 15 eternities 51 positive numbers okay well let's give it a try then hmm this may be a source of issue later but okay otherwise they have different signs so this means that the negative negatives have it oh in this case this is a negative thing so actually no you get the positive number and in this case you get a negative number i don't know this is right i mean it probably isn't but let's see let's hope at least it terminates it might not oh yeah it doesn't because i have this thing it doesn't terminate oops else in the same sign so if that's that they're both negative then what happened if y'all only have on or if you have only positive numbers left i guess it's just then in that case the contribution is gonna be is that true yeah maybe now this is a positive number in the other direction hmm oh okay that's fair in that case got it right for this one but not this one i don't need this and i don't need well okay eat it with that one time but hmm let's see so it thinks negative one is the answer so you have this thing the things negative one is the answer so then now it takes out the negative one so zero four five nine and we have two numbers left and we actually want four and five here we get rid of the four okay well here we have both on the same side oh for some reason i didn't do this thing okay so now i got this right but is it actually right i mean we can actually play around with some inputs here also oh whoops this is the actual input and this is six or something that's not great unless this is the same huh that's not the same though so that is weird okay so me yikes yeah this is definitely wrong because this six and a nine sums to 13 which doesn't really make sense so the first number that we got in this thing okay so at least we save ourselves five minutes of penalty but we still have to get it right so we have this thing we think negative one isn't the answer negative one two and then three and then four and thirteen left is that right this is five and six so i'm something is weird here okay so my skipping is wrong is what's wrong maybe it was five and six one five and six should have this doesn't even make sense because it's not sensible is this as wrong is this right well the negative 2 is already wrong let's have a negative three instead of this thing is it negative two oh this one thinks this is a negative two but this is the different sign and actually this could be a positive okay i think i'm just weird here this is right but this negative two i'm not super sure about negative two because these have different signs and i think that's where that messed up and that should have been a negative here this should be a negative two that's fair dimension you oh i skipped the head for some reason i needed the frequency table that's why i need the frequency table okay that makes sense i think i'm that's what i was thinking earlier but then i think i got confused with because i did this as a trick for zeroes but yeah that's not quite the right way to do it okay because you only matched negative two with zero instead um and getting rid of the negative two so then zero remains okay let's see some new sums ah try to be too clever i guess um for x in sums if f of x is greater than zero then we take x and then we document and also we decrement x plus possible hmm did i print anything okay so in one step i oh that's because i still have these things okay get rid of it i went from this to this that's fine and some should be sorted okay now it should already be sorted because of this thing okay well that's a little bit unfortunate this didn't even get smaller so you subtract this right so now you get to here that's not useful i think i have the right idea but now but i have to figure out how to do it quite correctly why are they the same now i mess up the possible number that's going to get negative 1 x plus this oh it's minus this okay so it's not subtracting correctly okay now this is correct yay friends let's see let's try another one um how many numbers are there should print that as well nine okay this is definitely very wrong because they're all negative actually even in this one this is all negative so i'm still wrong the reason is signs i think i got this one wrong sums of they both are then the number fix this one but actually this is wrong so i'm glad i actually caught this a little bit so my numbers are right but my signs are wrong so if negatives have it then next number is positive that makes sense if the positive answer then the next number is negative should be right why is this wrong what did i have before yeah okay so the first number is well it could be the first version of this but this is just clearly just wall i have 20 minutes to solve this so come on i don't know i've just got positive idea and that may just be lucky but you have positive numbers left so first we take the negative one this is not great so close yet so far i got the numbers right but my signs are weird okay so we do the negative one because okay that means that the two should be positive so they're different signs oh i see so here yes where if we only have one negative number is that right also this is d two ping one because this should d2 negative no oh that's why how do i get how does this even write um is this right negative three matches negative two so this should not be right oh my okay so the first negative one it matches this one with this one and then puts in the negative three okay so this is good oh i feel like i'm so close earlier how does that even work with the sides let's just say i trust this is it possible that this is uh an alternate answer nope because there should be a seven in the input and there should be no this is clearly not right because the sum of all the positive numbers don't match up okay why how what is this right though well why does this give me the right number is that just luck did i have the signs for because we subtract there's something really weird about this okay so at least this is consistent but this is just weird i don't think this should be the thing how does this go the right number numbers but with the incorrect sign that doesn't make sense like this i'm okay with but this is giving me the wrong answer so maybe i was just really wrong so negative three minus three over two then negative two matches negative one into one negative one which is six wait what oh yeah no this is right zero four this matches so oh yeah no that's right maybe so then you have this thing which is still a negative one and you have this thing now negative two well this just puts the wrong stuff oh hmm okay if it is the smallest maybe okay this is still wrong wait is it well maybe i just oh no this is now this is still wrong well maybe this is right it's just two different things maybe i don't know uh not only at 15 minutes uh this actually looks similar so let's see if they're actually together oh so they are true okay i mean i have 14 minutes i might as well spend the time on this i'd have a negative 20 on here can i mess up why is there a negative i hate everything about this todd do did i copy peaceful hmm well clearly these two things should not have to write at the same thing so awesome wow this is very awkward let's get rid of this for now but all right about 12 minutes to figure out this mystery this is exactly the same but hmm huh maybe i just copy and paste well oh this is i don't know huh hmm is this the answer you know it's just this press a couple of normal numbers let's actually also put in the example cases first cause that'll be embarrassing if this is wrong for that okay let's just give it a submit i don't know anymore i only have 10 minutes left anyway so if it's wrong answer then maybe we'll get something from it as long as it's not hidden okay that's sad but um hmm okay let's put it here sorry don't lose it but at this thing i put in nine because the negatives have it or the negative things is a positive okay that's fear yeah right that mess up to you so the negatives have it maybe i just didn't test your space um i think i changed it messing around with this at some point but wait what um the negative habit so this is to uh this is gonna be annoying to debug so basically the reason is because i have zero here oh yeah i have a zero here and this was type working to the wrong way so no yeah so this is the negative's habit so this is a positive number this is right but then i go here because it thinks there's a negative 9 which is fine let's see again i have eight minutes this is cutting it close okay so i have this which gives me positive 675 okay so that's fine as long as my 605 is positive no that's not true because i think that if uh so now this cannot be negative nine my after only okay so okay it finds a way to do a negative nine because well this is just wrong that's why because this is not negative nine they're both zeros i think this was inconsistent anyway no this should be right yikes so okay so we have this is not true sum sub one is greater than zero sum of negative two is greater than zero okay else no this the original sin is here negative nine actually uh it thinks this is negative nine why because the first elevation okay so it takes this and this so this is a positive number okay i think i just don't handle two numbers correctly very well i run up time but because then here i skip to 605 i think i see why but um uh this is too tight the hell what why would it do top of them so if the first one's nine uh i feel like i'm close but this isn't that close they're both negative i don't have time to test more ah okay well went out of time oh my with the signs and the rules well this is just really wrong now but i feel like i was close but i think i just implemented it to poorly uh 57 i guess that's okay i really should have gotten this one i was very close as you can see i have all the numbers in a lot of places but i think i just didn't handle the zero cases very well um what happens if there is a zero i mean the zeros are always going to be yeah i don't know hmm i think my idea is right i'm clearly having some science issue and i'm just hacking it around but let's slow it down and try to see if i could figure it out from first principles uh if this is negative then we go from small to largest okay that seems reasonable if it's positive then we go from biggest to smallest yeah maybe that's reasonable as well but i don't know why this is wall now tell me why i had it right before for this particular case but maybe this stuff is small yeah why is it even wrong for this one so it gets the first number is negative one it well this is clearly wrong so i have it possible typo here i thought i fixed this though but i think i just messed up on the signs uh because i guess they're four combinations but don't be sad if this is right i mean it won't be that sad just slightly sad but maybe not super sad uh okay so i'm still wrong here so i guess that's something yes i'm still warm but hmm oh yeah this is just a way just spit why is that i think this is just negative on both sides yeah okay maybe that's true though actually i get all the signs wrong but oh is that it i just have to reverse it and i fix i added the signs for some reason but okay oh so i did get the signs a little bit awkward but that's all um what do you try to think about how to handle this serial issue i mean so this is still wrong but i'm very close um there's just more cases but maybe there's a cleaner way of handling these cases because here i think that okay there's a positive number but this there should be a negative number because this is zero and i think maybe i am missing one inside so maybe i'm just wrong by a lot to be honest my idea is right but uh yeah okay maybe i just need one more case if this is the case then possible is equal to hmm i've gone to the point where i'm going a little bit nuts i think i actually added everything here so let's just do this here and then remove all these extra lines so okay definitely still have some issues but i think the funny thing is that if i just did like 20 long answer submits during the contest i would have gotten this i think maybe i should have done it that way because instead i did this thing okay so wait hm so negative 145 is that right now i think this should be positive 145 that's why huh okay so i was actually wrong on some of my logic in that here the 145 delta is the same as here and here so i think i just got the signs maybe wrong or like i don't think there's a consistent way of doing 145 because they should be positive but okay so maybe i don't know how to do this but uh let's see let's do some quick code reveal real quick see if i oh i think one that's one thing i could have done is that the only 15 numbers so we could maybe prove first because i always get the numbers right but not the signs so maybe we could proof force this yeah maybe we could prefer let me try something really funky real quick let's see okay so let's uh i modified this so many times so uh let's go post some for original cells so the smallest number uh and i think that's what i should have done now that i think about it maybe if okay so now we have answers type of pen those are answers for my adventure and if uh ten positive is equal to zero negative zero so okay oops am i doing positive to the absolute value of x all right whoops negative y and positive is equal to o sums of zero and negative is equal to negative one return oh well then this is the answer but we have to figure out how to uh do it okay for y and range of n y well that didn't go quite well okay so we did have some sort of an answer before that how that would happen here maybe we return thing here that's why that's weird oh i mixed up this okay well okay this one because we have to we have this wrong numbers here right no this is the right number so why is this not doing this one because this is wrong good so can i mess something up let's answer the biggest negative is minus 283 oh why is this over sums up negative one oh i didn't sort it okay dummy i thought i did because i didn't the other thing but okay oh this is okay i think this is actually right more white oh no um actually i don't know if this is right let's see i don't know what i'm printing what am i printing now that these two things are correct or the same is this equal to this i think i just copy and paste the same ones though but let's look at the expected answer ah so they do have the same true value even though they look very different for some reason signs in the weird price but i guess sometimes that happens okay then let's try printing this out let's try running this took 17 minutes after the contest and this may still be well uh i don't think that's the right intended way but uh but let's just see kind of how they did it um okay so they did it in a smarter way this is the way that i was trying to do but i couldn't figure it out let me see this is the way that i did it um yeah this is basically the way that i did it this is smarter okay yeah i mean i'm happy that i got it eventually a little bit late obviously but yeah a lot of case analysis but i didn't even need all these cases i just kind of because i had it much earlier right i think i even could have just removed this one i know it would have been okay because i just maybe well because now some of this other stuff is weird but it's just that i had more cases because i couldn't figure out how to get it to work but it turns out all i did was ah i have to remember to focus um yeah i mean i'm happy about this because i think only like 50 people got in it 46 i could have maybe gotten it but um yeah i mean kmjp did it the correct way maybe i don't know how this logic works let's see if i can learn from this before i go on um i'm still happy that i did it my way and then couldn't figure it out um maybe i have to take put that into the video explanation okay let's see so put everything into a multi set so basically just a sorted set looks at the first two numbers and the delta is the difference between the first two numbers while there is number in m s what is a oh this is basically what i was doing i don't know what this means though well i mean i know what the code is saying but what oh this is just doing rich um this is basically the same as what i was doing um with we so i did this reverse thing that's really awkward and also apparently i didn't even need well i need to reverse but he did it without the crazy hack that i was doing so oh i see because basically if s has zero we want to take the one with the zero otherwise oh huh that's really clever wow i did not oh wow i mean this is why they're the best in the world and i'm not let's see let's take a look at a couple more codes this was kind of the way that i was doing it oh that's smart looking at the using the sum to do it that is smart i've that's another good way of doing it um okay so i think i have seen enough no but um yeah hey uh yeah thanks for watching hit the like button here to subscribe and join me in discord hope y'all have a good rest of the week uh stay good stay healthy uh and to good mental health i'll see you later bye
Find Array Given Subset Sums
remove-duplicates-from-an-unsorted-linked-list
You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order). Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **multiple** answers exist, return **any** of them_. An array `sub` is a **subset** of an array `arr` if `sub` can be obtained from `arr` by deleting some (possibly zero or all) elements of `arr`. The sum of the elements in `sub` is one possible **subset sum** of `arr`. The sum of an empty array is considered to be `0`. **Note:** Test cases are generated such that there will **always** be at least one correct answer. **Example 1:** **Input:** n = 3, sums = \[-3,-2,-1,0,0,1,2,3\] **Output:** \[1,2,-3\] **Explanation:** \[1,2,-3\] is able to achieve the given subset sums: - \[\]: sum is 0 - \[1\]: sum is 1 - \[2\]: sum is 2 - \[1,2\]: sum is 3 - \[-3\]: sum is -3 - \[1,-3\]: sum is -2 - \[2,-3\]: sum is -1 - \[1,2,-3\]: sum is 0 Note that any permutation of \[1,2,-3\] and also any permutation of \[-1,-2,3\] will also be accepted. **Example 2:** **Input:** n = 2, sums = \[0,0,0,0\] **Output:** \[0,0\] **Explanation:** The only correct answer is \[0,0\]. **Example 3:** **Input:** n = 4, sums = \[0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8\] **Output:** \[0,-1,4,5\] **Explanation:** \[0,-1,4,5\] is able to achieve the given subset sums. **Constraints:** * `1 <= n <= 15` * `sums.length == 2n` * `-104 <= sums[i] <= 104`
Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number.
Hash Table,Linked List
Medium
82,83
103
all right let's get started it's been a while since i've done elite code question to be honest i've been away for a week on a family vacation plus a developer conference so that's been sort of where i've been so i apologize for not uploading anything within the week in any case let's get back into it and get into our first question which is binary tree zigzag level order traversal given the root of a binary tree return the zigzag order traversal of the node's values i.e from left to right then right values i.e from left to right then right values i.e from left to right then right to left for the first level and alternate between okay i think in this case we can alternate or sorry we can still use a linked list uh in the java implementation i believe this is a doubly linked list with a head and a tail pointer which is why we can do this the idea is that when we are on an even level go right to left when we are on an odd level go left to right actually i think this is backwards so this should be left to right and this should be right to left so layer zero will be this three then layer one then layer two here so we go left to right though there's only one then right to left on the first layer then right to left on the or left to right on the second layer this will be just dependent on so basically we will pop and push elements from different ends of the doubly linked list we could also use a deck here a double ended queue which would also work i'm not entirely sure though if the double ended queue allows for insertion and removal from both ends in constant time we could actually very quickly check that so if we use a deck um let's see because this is an interface a linked list is an implementation of a deck so i think it's fair enough we could just use the linked list there is an array deck but for sure the array deck if it's using an array implementation it will not have insertion and removal at both ends in constant time but it does provide us with the ability to index into it but in this case we don't need that so i think this is a fairly straightforward implementation of the solution and this will just run in o n time uh where n is the number of nodes in the tree because we only need to really traverse through them once and then let's see when we decide to go for the space constraint is interesting um i have let's see if we have a let's say that we had a no or a tree of height long base 2 of n is this o of n squared space because n squared is the maximum width of the tree assuming that we have a perfect binary tree where all the where it is both full so it has all the nodes all both chosen and complete i believe it's n squared i could be wrong though i'll have to double check this at the end in any case i think this is a decent enough solution and with that let's get started with the code so we'll say um our deck is going to be a links list of tree notes add and this is going to be our ad first and we'll add our root of course if we say if our root is null then we can just return an empty list which is of type list in and we can also create our return list here which will be a mutable list of list in and in this case maybe we want to actually instead do something different and rather than having a deck then we could use this return list as our deck itself but a linked list does not implement the list type in kotlin and if i remember correctly this mutable list implementation is using an arraylist implementation let's check out the source oh this is an interface and this implements a list and this has an index if it's indexed inside then it probably is an arraylist and so this will won't be very particularly fast so i think in that case we are going to keep the deck though it is very much possible to use the return list on its own and just iterate forwards and backwards within a specific index um we are going to do while deck is not empty not sure if this is not empty actually works here in any case for let's see index in 0 to dec dot size minus 1. so we will iterate over well actually let's do a var depth is zero if depth mod two is equal to zero then we'll do right to left otherwise we'll do four reverse index in deck size -1 down to zero iterates in normal order iterates in reverse order and then we will say we want to create a new list here so val we'll call it layer list this will be a mutable list of it and for each index we will say if so this is normal order so we will do left to right so first we will add the item that we are currently in into our list right let me think about this yep so when we actually iterate over the element we want that's when we want to actually add it onto our list so what we will do is that we would do layer list dot add our current uh index and we this will take in a value and then let's see we will say if index.left is not null index.left is not null index.left is not null then we want to do deck dot add last index.left if index.write is not null if index.write is not null if index.write is not null then dec dot add last index.right index.right index.right so this will add the it'll go left to right and add the values left to right in terms of the notes and this will just go through and remove those items after uh we will say here that we want to remove the elements uh once we are done with them within the deck so we can do deck dot remove first i think it's removed first yeah similarly here we want to do layer list dot add index.val index.val index.val and now we will do left to right so if dot right is not null then dec dot add last index dot right and similarly we want to do the same thing but for the left here and the entire idea is that we will be iterating through this left to right oh interesting let me think about this some more if we were iterating through this right to left already we are iterating through this left to right already hmm and i'm not actually sure if the linked list is iterable it is iterable okay awesome um yeah so if we're already iterating over this layer in reverse order and then we add the right one then the left one i think actually we don't care about this let's see i don't think we actually care about this in the sense that we still want to do this left to right for the next layer right and in that case maybe we want to reverse this one no because it's already reversed based on our reverse index right so in the case that we want to do that then we actually let's see if we do if we add the right one first then the left one that's actually correct well no we want to add the left one no sorry because we're adding it right to left let's see then we don't really want to add it to the hmm this is a good question because now that i'm thinking about it when we add it to the last part we don't necessarily want to do that uh maybe we want to add first then which is what we actually want yes and we want to add the right one first and we want to add it first right because then we can have the order that we want we actually want and then we want to do deck remove last i think is what we want right then at the end of this we want to add our final we want to add our layer list once we've added all the elements and then at the end of all that we want to return our return list so the idea is this we go through each layer left to right or right to left and we add it in an in the way that it makes sense for the next layer uh into our list itself and as well as into our deck for left to right it's the same as before we still go through and we add it to our last in left to right order as that is how the level order traversal goes if we are going from a standard left to right we also add elements as we traverse through them as we add the children and we will remove them from the deck on the flip side for a reverse level order traversal we will do pretty much the opposite we will traverse the list in reverse order we will still add the element as we encounter them but we'll start by adding the right element then the left element and rather than adding them to the end of the list we will add them to the first part of the list to the head of the list and finally we will remove the last element i'm not sure if kotlin will allow us to do this because this is um although this is a for loop i believe that this is implemented in maybe a little bit of a strange manner so we might have to do something a little bit different here if we want to actually implement this in this way in any case after we traverse through the entire layer add its children to the deck and add all of the current layers items into a list we will add that listing to our list of lists and then at the end after we've traversed through everything we will return that list let's go ahead and run it and let's see if we run into any compiler issues and let's also see where we're at so it looks like we ran into an issue with the mutable list this should be immutable list of actually uh layer list add let's see hmm we will do head is equal to dec dot poll first and then we don't have to worry about this right because head is just an index and we are really operating this index as more of a counter than anything else so let's add our actual parameters and actually get our values from the head and the tail of our list and let's go ahead and see if there are any other issues let's see looks like our first and third layers are correct our last layer however is not let's see why um we could still do this index in zero to deck size minus one and we could probably merge these together a little bit more because our deck is mostly a counter we don't really care about whether it's going back in normal order or reverse order since the counter since the rather the index is just a counter in normal left to right traversal or for loop is fine what is not right here i guess is this um let's see if we add the left element first then we add the right element here then our q should be like that should have 9 and 10 and then our tail should be 20 first before 9 i'm not sure why ah we're not iterating depth is equal to depth plus one mod two and that should give us the result that we want because we're actually iterating depth um yeah let's go ahead and toss in a couple of other cases so we just forgot to actually increment our depth you could also just increment depth by one but adding mod 2 makes it so it's constrained between 0 and 1 which is really what we want we could also use a boolean value for this instead which would effectively do the same thing and it might be a little bit faster because it's just a strict boolean value and we can actually do that so we could do var left to right is equal to true and if left to right is equal to true and here we can do left to right is equal to not left to right and this should be functionally the same thing there you go let's go ahead and toss in a submit again we could probably compress this a little bit more actually so let's go ahead and do that before we submit so let's do four what this will be replaced by is this so for index in zero to deck size minus one if left to right is true otherwise ahead and this will essentially be moved up here and this will also be moved up here and since the four loop is mostly a counter it doesn't really matter that it's like that and this should run effectively the same thing it's just a little bit more concise because we're not running uh we don't repeat that for loop there like i said this return list is or this deck is a little bit unnecessary because we could be using the layer from before and hmm let me think about this right now is there a way that we could do that instead within the confines of effectively we would be doing left to right or we'd be doing we'd be reading the reverse of each one um and adding that okay but how do we know when to stop knowing when to stop would require i think a counter that or a boolean that effectively says whether or not we've added any children elements the problem is that in that case we would be we would add an additional layer to iterate over so what i mean by that is that let's say that we go so for each layer within our return list starting with the root read the layer in left or in reverse order no matter what and add the elements accordingly or according to the uh left to right boolean so the idea is that we read the list in reverse order or the next layer down in reverse order every time because we are reversing it every layer and we will have to add the elements accordingly right the problem here is that until we reach the last layer and add no other nodes from the next layer we don't know when to stop right and not knowing when to stop means that we need to add an additional we add more calls to the left or we add more calls to um well we just add one layer versus here i mean are we doing that call anyways to a certain extent yes within this uh situation because we still check whether or not the left and the right are null and we uh and then we add nodes based on that so let me think of this as actually like that much worse hmm i don't think it's actually that bad so that's what i'm going to actually do i'm going to sort of take this chunk right here and see that probably works and let's move it up here so working solution one in o of n time o of n squared space again not sure about this o of n squared space but i assume that's somewhere in that ballpark this mutable list will start with a list that contains an integer i just realized that we don't have access to the nodes we only have access to the integers hmm well then could we we could probably reduce it so if we started off with the tree node which included the root and let's turn this into a tree node list a map from tree node to integer for each element within the list so this will rely on transforming each value from one to another i don't think it's associate i think it's just map like lowercase m map maybe it's i don't think it's flat map single list of elements being on each element of okay no it's not i think it's just map and we'll probably need a inside map as well uh it'll be a little bit weird um but in any case let's go ahead and do that then so we can say return list um well we actually have to do this in reverse order right um and we need a var index we'll call this depth and we'll say while return or depth is less than return list dot size we can say depth plus and this time we can just do like if the depth mod 2 is equal to 0 and not increment it mod 2 because we need the depth in order to sort of hit our endpoint of our traversal so we'll say let's see for reverse index from return list dot get and we'll save our list is equal to return list at get depth down to zero so traverse all layers in reverse order well do we want to do reverse order for all of them that's a good question um let's see certainly we'll need a new layer list and let's see actually i think what we want to do is a very similar thing to what we did before where let's see where we add each element or where we use the for loop as a mostly as a counter and in that case what we could do is that we could do list up for each node we can say if depth mod 2 is 0 otherwise if depth mod 2 is equal to 0 then we want to do right to left hmm if we want to do that right let's let me think about this some more if we did this right to left on the first layer left to right then we wanted to do right to left there well then we want to do for each element at from the end to the beginning on even one so iterate over the layer right to left in for the next layer then iterate over the layer left to right for the next layer and this will be in this case if we did 20 and 9 then we kind of want to do reverse order as well this is reverse order because we want to start with the last element and add them right to left and here because the elements are already reversed we want to add them in reverse order right to left as well okay so in that case we can do this for index in list dot size down to zero this should be list size minus one sorry for jumping around with the logic and everything we want to say if well valve current node is equal to our list get at index then if index dot right is not null then we want to do new layer list add index.right index.right index.right and similarly for index.left and the idea is that if we do if we are starting here we are starting from the last element see that adds items on the right to left i wonder if you allow for an ad operation at a specified index oops did not mean to close out that tab let's see and it's add at index and i believe we want to add these at the head of the and we want to go left to right order no right to left yeah then in that case do we want to add these at the end in the same order i think we want to go left first then right so this is effectively what we did before and i kind of want to flip this right because let's say if list is not empty or if sorry if new layer list is not empty then we want to add it to our return list and increase our depth so we start off but with our root then we go through each element from in reverse order since depth starts at zero we will start with the left candidate and add nine then we go with our right candidate which is 20. and we add that into our list which is not quite what we want to add right then left right so we want to add right so that's the 20 for our next layer then we add 9 to our list right then in the next one we have 20 and 9. our depth is now 1. so now we go in reverse order so now we start with 9 first and we go to the next iteration where we add our right element to our head first well 9 has nothing so we go to 20. at 20 we will add our 7 first to the head of the list then we add our 15 to the head of the list because the 7 is on the right and our 15 is on the left we add 15 to the list or the 15 comma 7 to our list and then we continue our depth at this point our depth is equal to our return list size and at that point we return at the bottom so i think this is what we want and now we need to do a map function and this will be a internal list which is a list of tree nodes and we just want to return the item value so this returns a list of integers and then subsequently this returns a list of lists of integers and let's go ahead and run this and let's see where we end up let's see type mismatch uh we know that this is a mutable list of list tree node oh this should be a list of and this index again we should be using current node not index so this is a more kotlin e answer i feel but i don't think it's necessarily anything quicker at the very least this returns a run time same as above solution but runs in o of one space because we're reusing the list that we're using to return although you can argue that this is um realistically a bit slower because we need to run the map function to transform each node into its integer form at the end which will require another pass through n nodes so it seems like it works for this case let's go ahead and submit and let's see if there are any issues or where we're at looks like we ran into an issue here with this tree let's take a look at what it looks like okay that's what it looks like and we want it to return one three two four five and we're running into one three two five four interesting let's see we add one into our node or into our list then uh depth is at zero so we go this route we add the right node in which is three then we add the left node which is two so we push in three two then we go in reverse order again so now we go to two we start with two will add in four however when three comes around because it that's the next element in the reverse order it will add five in its place and it will add that five at the head i see okay so if we're doing that in reverse order do we need to do this at all let's see what happens if we add in our values in the standard order if we added our right side or our left side in this case we'll just add our four then in the next case we'll add our five and that's perfectly fine so do we even need this let me just double check with this if we go through 9 first then 20 we will add our right value first so our 7 then we will add our 15. assuming that we go this route so this will go if we wanted to do that would be 3 29 and since we go in reverse order 9 doesn't add anything but 20 we will add our right value first so 7 and then 15. maybe the play here is not to add it to her head but instead just add it to the end but add it in the other order let's see if that works for this one well since this only has one child it won't affect it that much let's add another child for you so let's add a 7 there so what does this look like so we have 1 then two three so one is nothing special so then three two then let's see what happens at three two well we start with two and two will first add its left child then it's right child so it'll add four then seven and then three which is next we'll then add five which is precisely what we want right okay let's just double check and remove this and return this back to its original state and let's also run the example test cases just ran a blank test case uh let's use example test cases and let's add in our the one that we failed on so yeah going back and forth in reverse zigzag order can be a little bit confusing uh if you don't really keep track of it in any case looks like it passed it's a little bit slow on the slow side again this is more of a like trading space for time whereas this initially was more of a trading time or trading space for additional for a little bit better of time but in any case both of these solutions work it just really depends on whether or not you value the space consumption more or the time consumption more because this one can get it done in one pass and this requires two mainly because of just mapping it and there's no way really around it because it requires you to return a list of integers rather than a list of tree nodes but in any case i hope you learned something and i'll see you for the next problem
Binary Tree Zigzag Level Order Traversal
binary-tree-zigzag-level-order-traversal
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[20,9\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100`
null
Tree,Breadth-First Search,Binary Tree
Medium
102
189
That aapke Ajay ko hua hai Hello hello everyone welcome to new video this video or any tourists and the question for its question more no problem said that if anything can happen then ghee then subscribe us. Now we will be given this to subscribe, what do we do if we first will come here and that Shruti and 56 if the increase of K is that Raghavache give and share then we have rotated as many as we can here if we Ghaghra. If we subscribe in front of rotate, set any number of times, then if we see in front of us in the oil, what will we do, we will turn our face from this side, to fix it, first of all we will see the village and then we will see ours. So first of all let's see what we can do in brute force approach road office approach. What should we do if you have an example of 123 456, after mixing how many, this is 66 of ours and if we have this last one in front of ours and where else? If we have gone, then what have we observed here, what do we have to do, after whatever elements of research, we have to bring them forward from the last ribbon and we have to set the time for the rest of the juice, we have to do the rest of the elements. If you see, why can we take interesting observation from here, in this we have to bring all these elements in front and set them right, so if we see the logic for this, what will we do, first of all we will make a deep, okay, let's which one? What will we do? First of all, we will create an answer named 'Answer' and what we will do in the answer is that we will named 'Answer' and what we will do in the answer is that we will copy the last elements. First of all, our answer key is 1601, whatever is the side of the mother, we will give zero, after that what will we do in these elements. Whatever is the initial, if we put the elements from 1 to 1 here, then our answer will be 575 1234 in many places, this will be our answer, so how will we apply it, if we look at it, then what do we have to do here first of all There is an answer if we have to make this tennis, what size will we make it, we will make it in the size which will be in our name, what should we do now, where did our hatred for the dead body come from and where did it last - meaning - 11 - meaning - 11 - meaning - 11 coats and pants - of In this case, what is - 30 coats and pants - of In this case, what is - 30 coats and pants - of In this case, what is - 30 - 110? Then do we see copying from the beginning, - 110? Then do we see copying from the beginning, - 110? Then do we see copying from the beginning, copying from zero 12345 i.e. forces, then we have to copy from the beginning till the copying from zero 12345 i.e. forces, then we have to copy from the beginning till the copying from zero 12345 i.e. forces, then we have to copy from the beginning till the last, from where we have to copy, if we have to do it in the beginning index of the answer, then what do we do? We will run our face here, from where to where, as long as we have our channel, we will run it and give it and inside this, what will we do which is our answer's - - answer's - - answer's - - we do and rectangle index Why a moment because our initial - K will be friend minus our initial - K will be friend minus our initial - K will be friend minus plus one but meaning five six seven our I will go OK our I will go from where to where will it go for this our I will go for 4 5 6 minutes so where will our I go 456 K Our answer for how far will it go and - and is how much is and - that is ours is go and - and is how much is and - that is ours is go and - and is how much is and - that is ours is left in the bracket this is our initials that if it will open then this is ours is this is how much is ours for plus is four - and is for plus is four - and is for plus is four - and is how much is ours is seventh This is our Three Four - 7 - Reel, what is our place, our Three Four - 7 - Reel, what is our place, our Three Four - 7 - Reel, what is our place, 7.30 - 01 2012, this will 7.30 - 01 2012, this will 7.30 - 01 2012, this will work for us, except that in the subscription for this, we will get this quiet, so like follow is finished, which part should we get? This is the guru part here which we had to copy from behind, I will get it. Now as soon as we finish this, we will copy everything from behind, but then we will have to do the element, so we will run one of our calls, this is from Jogi. If we fold it then it will be plus and inside this we will make our - K. - K. - K. We will open it and turn off the village answer because what we will do i.e. Scientific Index Nifty Element. Who should we call this? Answer 80, we will do a moment, whatever our answer is West I - Key. So the answer will be A I - K V because - Key. So the answer will be A I - K V because - Key. So the answer will be A I - K V because if we answer name - - - name - - - name - - - - will end, ours will be found and what will we do after that there is another one which is ours. There is ours which is ours. There is no need to end this village because the function is found. And our answer is, it will be updated and this is our simple solution, if we do a dry run for this, what will happen, first of all, our answer will become one, which is seven size amp's, first of all, this is our episode 271 to 0578 of ours. Our answer is okay this - - - - - - - - - - - - - - - - - - - - which is our name so 12345 here and after that as if people will be ours here it will end like wow what will we do we will run our seconds loop here that our faces will come Request two key i.e. 3 will run till how long will come Request two key i.e. 3 will run till how long will come Request two key i.e. 3 will run till how long will three less bank run till seven no issues now what do we have to do inside this answer to be removed answer battery taken number 123 where which value will come name set i - where which value will come name set i - where which value will come name set i - k means three layer how much is the guest - Rs k means three layer how much is the guest - Rs k means three layer how much is the guest - Rs means name 600 here further by name or one after that what will happen that it has been updated that this time one is the answer adv1 i.e. this time one is the answer adv1 i.e. this time one is the answer adv1 i.e. in this location is there a rectangle number tier for - in this location is there a rectangle number tier for - in this location is there a rectangle number tier for - that is one answer at one is equal to two During this, sir rate plus one will be done, see this of coriander, here we have husband here and as we finish our mill, so let's go to the liter and fold it, before that if we see the time complexity for this, what will it be? Here our flop going on is 0202 which is maximum so our soak off n will be activated on time. If we talk about space complexity and mix player is making every time what is the size of excise then our space contract It will be done, see if it will be done, so let's go to the return and look at our code for this, so you are done with your liter, first of all, what do we have to do, first of all, we have to make another one of this type, we will keep the answer to this. What will we do, we will make this, so inside this, we, our from where to where - from where to where - from where to where - meaning and update, now inside this, we have the answer to tie, remove the answer to, we will equalize, remove the answer to what. To we came to this - - came to call to minor came to this - - came to call to minor came to this - - came to call to minor - to will mix to this we will cut this - to will mix to this we will cut this - to will mix to this we will cut this now our name will be like it will end up to appoint this our ka this for and will update again inside this we will add There are other things like this will end, follow our complete raw, we will get the answer, after that what we have to do is just copy the answer here, where we have to click on the value, from the name to the answer, in this we will run electronic from equal to zero. And if we copy the limit, then plus and what will we do in this, it is equal to answer, now we have to click here that it says our solution is required, we submit, we see the result, we run that our sample discus has passed, let's go. Let 's submit from and see the result. 's submit from and see the result. 's submit from and see the result. And here we have some mistake in this position. Let's -1.5 over there in this Let's -1.5 over there in this Let's -1.5 over there in this position. So let's go here. What happened to us is that if we click and subscribe, if our In any condition, we have to divide by this, if we take because our is more than once, then it means what happens along with it, then we take it after Hussain, if our with n and if our inch plus one time. If it is being rotated then what will we do, we will separate them because after the entrance result, if there is a tumor and we will rotate it once more, if we submit it and see if it should be passed sometime, there are 6 of them and right now it has been passed. Which is faster than if I go further, then this is our simple approach. Now we go and look, now we will see 5 to 6 subscribers appointed in the village, so one now we have to click on this, then we will click on this appointed here and we will see this. Will take and even war we from here even young now we will divide it by clicking this pumice 1234 500 which is our answer click once if it has to be clicked twice then what will we do now if it has to be clicked then We are going to do it here, we subscribe here and this is ours, after clicking on 12345, subscribe us, deputized, subscribe, village, ours, appointed in subscribing, we have to click on this, what we have to do after that we have to click on zero two, minus one. How much is the minus one to click from this porn to that war click and if we see then any we in this and after that if we click before appointed that if our here we have what is the size of this if we click on this If you subscribe to Ultimate, then before clicking, we will divide what is ours, we will take this, the answer we get from this will be good, so now let's see its meaning, so what we have to do for coding, first of all we have to appoint a function for ourselves. Let's create a function, so first of all we create this giver function inside it, first of all, let's create the whole first, so subscribe village first use appointed starting index so S Chauhan and appointed now what do we do inside this. Till the time our oil starts from home, what will we do? Appointed a team in-charge, we will from home, what will we do? Appointed a team in-charge, we will from home, what will we do? Appointed a team in-charge, we will note down the vitamins, we will note down the number, set the start, whatever is ok, after that the name will be on scientist, what will we do with it, the number is 601 and we will put it on the set, we will put salt, we will subscribe. Subscribe to our channel and complete this function by 123 456 and subscribe to our channel, its name is ours here, ours is here, our value is here, what is our name set, what is this - value is here, our value is here, what is our name set, what is this - value is here, our value is here, what is our name set, what is this - World here. But if there is one of this case, then our education will go here, after that, attend by name, what is our end, from this, here we put the time, attend, first person one will open here, similarly to replace were and 60 After that this subscribe this and of course subscribe run back and after that our here subscribe and which this will work in our what to do now what we saw if we have to flip then from where to where we had to flip this we have I had seen that we had to click first on 020-V, which did our click first on 020-V, which did our click first on 020-V, which did our complete reverse, after that we had to click second. We will do the function by voting in the village on Thursday. Inside this, we will click once and will take the most First we will take this subscribe my channel subscribe village and our channel ABS 21 A as we finish then we will get our required Hey so if we look for this case first let us write it properly from zero - 1090 se and minus one from zero - 1090 se and minus one from zero - 1090 se and minus one problem 110 se k minus one and next will be our from 0 to - Now what we will do is here we will 0 to - Now what we will do is here we will 0 to - Now what we will do is here we will see what is its time complexity till the time active time. Subscribe to this channel if we want to know its time complexity. If it is taken out then it will remain soaked, which is our vegetable. If all of us have not subscribed, then we make him above us that the first thing to do is to fight the war, first of all we will come out of the union and here we have seen the village and then We put this inside this, ours, which is ours, which subscribe to our channel, as long as our start is there, the wire start, which is our loop, from whom, from these, what do we have to do here, we will we here, we will put ours in subscribe, leaning towards this side. We will mix it and after that we will use our subscribe function to appoint it. Now here we know from where to fry, so here we first of all do what we have to do. Here we have to click first where to flip from where to where, the first click is from zero to 1000 to 1ghz and that is done. We will use subscribe. These presidents will be appointed to meet us. Submit this The answer is correct, here, somewhere, here, flip, cannot be applied, to give it's ok, I had subscribed, which is here, we will have to give it first, every time, only on Ravana, here, in our village, now we subscribe to this. Should be accused that a here is our issue here is our are indicative dam if we see our do 2010 - So first of all - So first of all - So first of all what we will do here is we will do a divide in this our complete rotation is done so we will take this model now Scares both are two and this is our successfully incorporated that poster banner patient and subscribe let's copy it control subscribe that war function appointed photo copy dance that my our C plus mission we here But what we did is we copied the code here we changed the length function to size, apart from that, this is our same SMS here, we did not put our function declaration here, that tips ML, here we got C plus. Please note that when our automatically reference copy send is not done in WhatsApp Plus, then if we want to send here, then we will have to subscribe here. Here we have done this our absolutely fish and any one has been appointed in this. One moment this is our The sample is accepted, let's submit it for this and let's see and this is our successful this time which is faster than five subscription 27.6 27.6 27.6 subscribe solution understood. Also if there is any diet then you can comment in the comment section below. Apart from this, you can join our company here, you can ask us and do interactive track. Thank you for watching
Rotate Array
rotate-array
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative. **Example 1:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 3 **Output:** \[5,6,7,1,2,3,4\] **Explanation:** rotate 1 steps to the right: \[7,1,2,3,4,5,6\] rotate 2 steps to the right: \[6,7,1,2,3,4,5\] rotate 3 steps to the right: \[5,6,7,1,2,3,4\] **Example 2:** **Input:** nums = \[-1,-100,3,99\], k = 2 **Output:** \[3,99,-1,-100\] **Explanation:** rotate 1 steps to the right: \[99,-1,-100,3\] rotate 2 steps to the right: \[3,99,-1,-100\] **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1` * `0 <= k <= 105` **Follow up:** * Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem. * Could you do it in-place with `O(1)` extra space?
The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.
Array,Math,Two Pointers
Medium
61,186
414
Today we are going to talk about the problem of the third maximum number on the list, so this problem has 3 solutions, subscribe here, so I am going to do this, so see here, share and subscribe and You will have to subscribe maximum number here see it here delegate here now subscribe this number two so you will get mental answer check pimple number two let's see now we have two elements maximum on this not possible subscribe here Subscribe to the channel, if it is a list entry then you will not get the school, if you do not get it, then do not forget to subscribe those two elements, subscribe, my chicken became free 12302, do not understand it like this, here number two three one two three third maximum here means skin. Subscribe to Tan may be here meaning 238 operation is there is one second somewhere so you can perform your introduction then you can subscribe and can do it in this and can do it in end login. You can wear it in pan also, okay, that means now let me tell you and you approach will go to Google office because here we see the time by seeing the custom and have to decide the time, after this if you select something here then this. How to do it, that's why questions come, which route is the first one? If the first one picks up 321, then it is a simple approach. If the nearest element is 321, then it is okay, but first one, you have to take 123, that is okay. Now, which will be the third largest in this? It will be including the third largest which will be coming third from the back, meaning one, two, three, if this is the case, then one irrefutable comes that if I do it like this, then I will dry up and then we will meet. If we blur the position of A, then - meet. If we blur the position of A, then - meet. If we blur the position of A, then - 3 meaning this vitamin can melt maximum electronics it can be okay good and what can happen if you have this little angry he has defended himself subscribe that you will learn here and that's what makes it so important in this video butt We will learn in this class but if we take easy approach, then you will be able to see here that I did not get it, I got it, Meghnad, first of all, I do not want that girl 2323 subscribe, I want distant third number, I want subscribe maximum possible, it is simple, ok, then If you remove it from the damp, then one of mine is removed, like I did in this case, you would have reduced it seemed ok, then look here, take out the mix of yours twice, once and remove it from the name, okay, so what is there in this? If you look here, where is the max, where is the to-do list? Well, look here, where is the max, where is the to-do list? Well, look here, where is the max, where is the to-do list? Well, finally, save as much as my daughter can, take it out, whatever will be mixed, how will it be, if there is a third maximum number in it, then it will be very high, and another thing. I had done this here, I had subscribed to remove it, so this is a text, Namaskar Store, this is 231 lying in the list, okay, we have taken it, join it, after folding it is 123 that we had kept in half, a little bit. Will do simply, zero work for you, welcome to, food is also ok, now there is air condition, but simple means quick appointment, liquid hatred, otherwise, subscribe, if you subscribe to, father was written in District Commandant Express, Namaskar - V to jo Namaskar - V to jo Namaskar - V to jo for the campaigns. Look at the approach, okay, this approach will take time, it will take time, channel log in, it seems that it may take time for someone else before you, try to subscribe, I have it here, okay, so you guys are here. It is taking time, reducing it to something else is appointed which is complete, subscribe here, it was complete, with the eyes of the final trick, you will have to ask what is Cup Twenty, what is a method, there is a note on the side, how many children can he have, what did I do? It happens that such a note which has two children means this means if you want to set a pin here then subscribe on this side here I have appointed here subscribe want subscribe Choudhary and Nitin element is okay so sister 's speciality. It happens that these people are here, 's speciality. It happens that these people are here, 's speciality. It happens that these people are here, I have appointed them here, okay, so here, now I have appointed them here, I look here I will pay attention to the minimum, here the accused will run away, above me, meaning my work is done and this is what happens, you will get the understanding. Now we read these, I had to set this pin, so see here, come down here like this, now it will be compared to zero one, it will come down with a strong request, it will go to zero, something like this, things are happening here, you will see again. If there will be a minimum of metro on the Se Chowk route, then one thing that I want for you here is that whenever we use it on our own, it was taking time to login is done separately, click the subscribe button on subscribe through. If it comes here, then it's okay here, okay, now should I tell you, or if you want to set it off, then we will rot here, okay, compare the minister, yes brother, it's right, there is no doubt about you, okay now. If I say that I want to subscribe then it will take me a few minutes to type, here you will see the celery photo here up and down also, so here we have a small one and people are making maximum, that means why would they go to the island. Will be asked or will come down the line Chapter-3 If we can do very simple come down the line Chapter-3 If we can do very simple come down the line Chapter-3 If we can do very simple things, then it is better to complete this whole work with our mind, then if somehow we appoint ourselves properly that we remove that today we have removed the pipe. It has been deleted, okay, so this note is gone, now the question is whether it will come in its place, what mistake do people make, they think that it is 381, so take the OK up here and press it from here, it happens like this. Nothing happens except that you are here and subscribe here, appointed here and subscribe quit, I will get the volume maximum, what did I get the maximum, I got the maximum for, okay now I will delete this here. So the one which is not the last in the last, look, here is Chuttu, it is lying in the last, we will pick it up, where after that, subscribe to each other here, then I said that I am different from here and here soon, right here. Subscribe to this and it will ask like a to-do list. Study-teaching portion is now a Study-teaching portion is now a Study-teaching portion is now a school, so why don't I cook my own food at the given time limit. What should I do after making the food so that I can pop it two-three times? If I do popcorn three times, pop it two-three times? If I do popcorn three times, pop it two-three times? If I do popcorn three times, then recite it for the first time, the phone will not work, then recite it for the second time, sugar candy will come out, once you get it from Hazrat Ibrahim, what will come out of the wallet, if the third maximum number is there, then it does something like this. If you want to make this gown, then you can subscribe. Okay, so here I am, why is it only in imported form of ghee? It is available only for investment of choice. You can use it separately. Okay, after this, what are the functions inside it? So, there are some functions which will be useful for you. Today's second one is Pushkar in Pak team, turn it off in the interest of Pushkar. If you push in a good form, then here you have to do what is the name, which is useful for you, which element is spread which will give you something inside it. You have to do the right thing, what happens in pop, you set up here, you pass the name that just do a comment for this hips, it only makes it popular, which on this note, the commission returns Bigg Boss back, so basically these two If you subscribe to success tips on Shatrughan who is using , then the entry system has been appointed or someone is needed because Kumar has come here, then he has come here to come, so it is okay here, something like this should also be made, Amiri Mini is appointed, I click on this. By subscribing by subscribing in such a way that it is ready to make something special, so if you guys want to make it then I can make this our ghagra, so if there is something, this tube inside is for that and we will not make it, you can make the melted element negative - - not make it, you can make the melted element negative - - not make it, you can make the melted element negative - - Verb - Verb - Verb - Okay, now if you mix it here, then by making it negative through the number, what is the result of mixing them? Let's first go to Malaysia or okay, then - Okay, so the minimum or okay, then - Okay, so the minimum or okay, then - Okay, so the minimum is above the minimum, it is okay, then I have discussed our topic here. So this means that the cover, now let's try to make ours here, I need a third number to make it, we need this thing above here, now to make it, appointed Subscribe A vacation, I will change it, so I can get the original number. Will go to the original maximum, so I am thinking something like this here, okay, I will set an alarm for this and make a video, I will stick it, then I will show you the complete things here, how the infection happens, how is the relation, there will be something in this, so right now, first of all, you will watch it on middle Sunday. What is happening here, I have been given a list of numbers, okay, after this I have made my own list like this, you make a play list, you are simple, I have melted that all the numbers of my own, those who hate us, all those that are closed, But keep it one by one Subscribe Item Maximum Subscribers - Then Minimum Maximum Subscribers - Then Minimum Maximum Subscribers - Then Minimum Maximum Elementary On Friday, he will have a Sai son. Okay, so you guys, if it gets made here, then subscribe - - - - - - - - - - - - - Come sometime. Who can do this in a simple way, now if you switch me off then my phone will get throat cancer, where will there be justice - switch it off my phone will get throat cancer, where will there be justice - switch it off my phone will get throat cancer, where will there be justice - switch it off in you only - had made - 9 - woman's in you only - had made - 9 - woman's in you only - had made - 9 - woman's minimum is above, if it is at the minimum then I will become this now What do I need to do, I want it in my channel according to me - appointed is at the top, I have here - - - - If it is on top, then I have come to here. Okay, tell me, is it not so? If it is not so, then change it Orange. What will happen if we do this, here I have discussed this issue, there will be a problem, this Johnny district's, this will come in its place, this will be used here in the school - will become - used here in the school - will become - used here in the school - will become - 2 Now here on the ground itself, okay tell me what to do I also want to remove the second maximum, but what will happen if I remove it at that time? I said pop, delete one element from here, delete the other one - came out, okay, delete the other one - came out, okay, delete the other one - came out, okay, whenever I clicked, at what time, there is only one note. Bacha - Verb - One President, this is one note. Bacha - Verb - One President, this is one note. Bacha - Verb - One President, this is what will happen to me, so this below, if you liked this channel of ours, subscribe, then this of ours, I, this, here, this is the meaning, I have now, mute the volume, accused, this will be maximum set maximum sum third, take it out, want to subscribe. So here I have posted here, okay go, so I login here and unlock is very big in Indore, so I thought it is better to make it solid, you will make it soon, it will be easier, because the video made about it. If I give it, I will upload it in a few days. If I do it before all the pictures, then it will be coming on the I button. If you have commented, then it's okay Ajay.
Third Maximum Number
third-maximum-number
Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_. **Example 1:** **Input:** nums = \[3,2,1\] **Output:** 1 **Explanation:** The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1. **Example 2:** **Input:** nums = \[1,2\] **Output:** 2 **Explanation:** The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead. **Example 3:** **Input:** nums = \[2,2,3,1\] **Output:** 1 **Explanation:** The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1. **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Can you find an `O(n)` solution?
null
Array,Sorting
Easy
215
838
hey everybody this is larry this is me going with july 21st the code daily challenge hit the like button hit subscribe and join me in discord i hope y'all are having a great week uh it's wednesday let's do today's farm push dominoes i usually saw this live so if it's a little bit slow fast forward to whatever you need to do um the reason why is so that you know you could see someone making an attempt at the solution and the thought process go uh that goes with it right anyway okay let's see and dominoes upright push to left to the right okay i feel like i've seen a similar problem with the cows or something like that could be wrong the first oh maybe not okay maybe this but when a vertical has dominoes okay so that's this is what i'm looking for you know i read it backwards which is that you know if one has three thing pushing to the left and two things pushing to the right you know which way does it go um so i think this one is pretty okay this is about a simulation and just being careful about stuff um so for these problems one thing or just problems in general maybe uh one thing that i would think about is just thinking about backwards and here i think the intuition is to look at each domino and then push it say and then kind of see where it goes um i think the other way of thinking about is okay given every domino what forces is being done to this domino right for example here i go okay um how many is the domino pushing from the left and is there abdominal pushing from the right um and i think that's maybe a good idea enough to go um yeah that's still good look of n so n is 10 to the fifth so we cannot do anything n squared so we have to do something well of n right um let's see how do i cleaned up my thinking and i think the idea is so um yeah this example okay so let's say we have this one right so then we have to take a look at the so here in this case i was going to say something about the courses but it's not even the closest right actually no it may be the closest because if there's a close one to the left then one second later then it's closest to the right or if this one from the left and it's you know for example this one oops the one next to it will have certain forces to the left so then now in that case it becomes a co um you look to the left to see to get the first right and then you look to the right to see the first left um and then that distance and you take the minimization or some uh to get to see who gets first and then there's some rules about you know like obviously if you're uh if you're here you're not gonna look at the right because then that means that there's no force impending on it and then and of course if you do it for every block it's going to be n square so then the question is how do you reverse thinking about that and then think about um and building them as you go from left to right or and then right to left for the other one right so for example here you just go from left to right you hit the right so that now you can follow this as one two three and then you hit the left so that now it resets back to zero uh and it just backs to zero and so forth so i think that should be good enough so let's type that out um yeah so right distance maybe white d prediction that's just the right distance 0 2 let's just say infinity times n and it's equal to the length of the dominoes infinity is either some big number it doesn't really matter right that's what i always play um your management way also hope everyone enjoyed the cameo from yesterday's prom uh probably not gonna get one today uh sleeping right now but yeah uh okay and then we also want the left distance for you know symmetry reasons but just in general so then now we cascade what we said right so right is gonna um almost i guess another way to think about it is the time that this block would um impact a certain block because here it would be at zero seconds well you're already putting a force on it here next to it you have um let me actually put this here so i could have easier highlighting yeah here that would have impacted second one this would be at this second two second or third second and so forth right so that's basically the idea so yeah now we go from index from range from left to right and then here um current is equal to z um no apparently it's equal to infinity and then yeah if dominoes of index is equal to right then we get to reset right and then otherwise else right distance is equal of index is equal to current uh i guess technically you could go over infinity but uh because we started infinity but we can maybe find adjust that later and now we want to do it for the left side but these are things that you know you have to think about though sometimes i think about and then forget but because otherwise you may have weird cases but these are things just to take note and actually i did this incorrectly sorry friends uh this should be backwards because you're going from right to left uh with the same symmetry reasons but i think i just mentally copy and paste so um so here is just and then now yeah and then now answer let's go to uh let's just call it that wait for index then insert that a pen let's say if right distance of index is let's see if this is closer then we want to do a right else if just put the other direction we want to do a left and then else of the d code then you just appended period i think that should be good let's give it a spin and we know that this is linear time because we just do three for loops right um of course they're really helpful if you get the right answer definitely distant distances where am i gonna get one oh oops okay oh uh i messed up with respect to oh i think well one thing is that uh yeah we want to do this and that's fine that's easy but i actually made a mistake with respect to what i said um i think i actually pointed this out as i was going but then i forgot which is that for example here this period there's no force in impacting it but because i have an l um here it thinks that this is five distance away or something like that given it should be infinity so we should we have to uh do something we have to add in another if statement um yeah and then i have to do the enter opposite and then i think that should be good just have to be careful make sure you get all the cases i was a little bit sloppy uh and i think i'm maybe even additionally sloppy oh no actually this is where we said earlier um this is where we said earlier uh the infinity things so i guess we took a note about it but then we didn't do anything about it but the reason is because now some numbers are infinity and some numbers are infinity plus one or something right so that's basically it um okay so i think this is a easy fix but you just have to kind of do it uh yeah sloppy this code is getting okay i think one way that you can clean this up is just um put these in the one function so you could try yourself and dry meaning do not repeat yourself um so you can kind of do that really quickly and then you know maybe you just go one direction for dominoes and then just reverse the direction and then do it again there are a couple ways to do it but yeah but now you know it looks okay do i have any other case i don't think so to be honest but i mean i think these are like weird-ish cases but otherwise weird-ish cases but otherwise weird-ish cases but otherwise i think we're gucci i'm just looking at the i mean yeah i was looking to see if there's a zero case but i don't even think that matters let's give it a submit hopefully if it looks okay yep uh yeah and as you can see even though this code could use a little cleanup to be frank at the way at least what we said and put this in a function and then we use code in a clean way um yeah you can easily see that this is linear time here so we use linear time and linear space and which is unless you want to make some argument about some in place stuff yeah it's going to be lower bound because that's the size of the output um you can also do some output sensitive analysis if you like but that's where my journey ends uh let me know what you think hit the like button to subscribe and join me on discord uh yeah i will see y'all later have a great day and yeah stay good stay cool it's a good mental health bye
Push Dominoes
design-linked-list
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string `dominoes` representing the initial state where: * `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left, * `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and * `dominoes[i] = '.'`, if the `ith` domino has not been pushed. Return _a string representing the final state_. **Example 1:** **Input:** dominoes = "RR.L " **Output:** "RR.L " **Explanation:** The first domino expends no additional force on the second domino. **Example 2:** **Input:** dominoes = ".L.R...LR..L.. " **Output:** "LL.RR.LLRRLL.. " **Constraints:** * `n == dominoes.length` * `1 <= n <= 105` * `dominoes[i]` is either `'L'`, `'R'`, or `'.'`.
null
Linked List,Design
Medium
1337
792
That these guys welcome to take good bye Nivedita and in this video we are going to solve 23rd July list challenge so before starting this video I request you guys if you like my video then like share and subscribe if any feedback now You should give everything, you can give Android, ok, let's start the video, hit, what is the problem, today's problem is Malad number of matching, all the sequence is seen in it, acting is given, already given string is given, okay, what do we have to do, address After voting, you have to see whether it is the most requested of the given string or not, then how many subscribers are there in total and fine is given in the account. OK, it is of subsidy, it is a string which is from your original skin. It is okay if the order of character is in it will be there in free mode on, but it is not necessary that the Cultivates character is present. Okay, so see here, what have you seen in ABCD, now what is its subscription because it is a very See what is in the sequence, in this sting too, there is an order for such a thing, even after that it is not necessary, you are present here on Control Fierce Cat representative, so it is not necessary but order from us is given to me for AC here. The order is the same, here in the motor, what will happen to us, this sting will be the sequel of this sting, so what we have to do is to check all the stings given in this year, what is the meaning of this? Is it white cement or not? If so, what will we do in the account? Let's keep incrementing and we will sign the total account. Okay, so the first thing we are going to watch is the drama, we are going to watch Pores vote for it. Okay, so we will watch it in brute force. That is the field, that is the problem. If you understand then you will agree that it is okay, so what has been given here, I have given a sting, this sting is yours and this option has been given, there are many sticks in it, what do we have to do and check, is this its sequel? Is this most of the cancers? Is this a subscription to this? Is this all a scan? If so, what will we do? We will take one more card and keep on incrementing it. So we will reach the simple thing, what is going to happen here, so this is daily. First of all, let me tell you that in this process, we and Total Kumar had done only tattoo hit in this process. I am telling a lot in this so that you can understand it as good for support. Okay, so it is given here that we come because we have a request. If we look up here, it is given here and what will we do about the posting, a BBC lead, one by one, it is matching, then it is finished, so look here, use here, we do, plus. Plus let's do what will happen if our who has covered its meaning will have met when we do what will happen from this Answer Kumar Jain Kapoor today is a holiday if you don't cover your then what after covering It will happen that your word will be more, its size will have to be fixed. I am also looking at the second example, what will happen here is that if you do G plus then it will go and whether the size is life or not, is this your sequel to this, what will we do? We will increment the account, what will we do with the account, we will take zero to seven, okay below that one will be one, zero will become one, then let's see for the second one, BB's remains here, what to do here, we will force it and then we will start from Aa Ho. This match is not done, match will I increment but then what will I do, then I don't like, comment that we will Aishwarya IV increment and whatever increment will happen, what place will yours be in, then what will it do, is this match happening or not? Is it happening then let's move ahead Himanshu or is it not happening? So whatever he does, he will move ahead Himanshu Bhai, it is not happening, that is, your life is still one, but your size is Pattu, that is, Tonk, Yo Honey, is this not your suspense? So account additive will be our one. Okay, it is not. Now we will see for Idli directly for A Okay, this is why you will look at I which you will chart, is it matching, are we matching, will we increment this, what will happen to our life. Whether I will match the increment or not, if Seema Chala is matching or not, then the ad will remain like this and if you click on the icon, then you will get the idea that it is matching today, then we will do maths on this also, if we increment further then do so. Okay, let's make it two, then it will move ahead, it is matching, it will also move ahead, it will come here and it will become three, then we will see, whatever is our reason, its size has been fixed, whatever is the cattle, it should be captured. What is this, what is its sequence, subscribe now, what will we do by incrementing it to two SIMs, we will apply this in this also, this is why otherwise you will do more, whatever you chart, you will get angry, you will be able to match. Are we moving forward today and tomorrow night on Amber in One, you also have this here on Dainik Bhaskar, what is this, take forward the payment on this disease, then marching like Madhav's match, we will move forward with this also and this too, we are moving forward If we want to match on the di, we will move ahead. If we match, both our work will move ahead. Will yours be freed from 0.2 and we will see that freed from 0.2 and we will see that freed from 0.2 and we will see that its size has also been captured as per the fixed increment. We Will we do this Jaganathan, so this is our approach, this is a beautiful approach, okay this is us and you will garden this, right, you are not going to pass it clearly, I am just showing a little that we took continuation here and here But and toe advers take this Kunwar then we will go that I will set so that stir what I village people's liya is done a lot size and Jaipur VS student The description inside is fine and what is yours like this which I am last year is fine, both of them were drawn in the match, we will press after the match, we will come back and we will plus it, okay if it is equal to the size of our account, we will plus it, last important. We will do this, it will be a common cause but all the yes will not pass in it, so next day we are going to see optimize the solution, okay some of the solution, do it, so here we will definitely see what we are going to do with the second example, which is the second app launch. What are we going to do in this, what are we going to do in this, we will see for ourselves in the second example, Sonu Nigam has done 200, what are we going to do here, we are going to use it on the actors, we are going to use it on binary search, we will not create a reminder search function from us. Appoint, we will use it, okay, as positive is provided in the press, okay, and we are going to use it here, so what we will do here, we will take one person, now what will a vector do for you, what is it actually going to do this, your saree tractor. Coming to this is going to store your index, okay what will happen in it, understand this in a way, we have learned so much and its value is okay, it will be decided here, which will be here, it will be from zero to you want to three, that is from five to What will happen to you? Here it will be 25th. Okay, what will happen to me in the office? All of yours can be worth all of me and not multiple o multiple, so for 121 we will use zero, for also we will use mohan, learn to use two and DK. For three, it will work like this, A to Z will work, okay, so it may be too many, one sting, too many no1s, okay, as seen in this example, but what is G if it is two times, then its index will be different on Friday. No, no, what we will do is possible in this way, see, let me explain to you what we are going to do here, what we are going to do is we are going to check a text, like here you have an example, okay, you have it here. Okay, after that you would have felt strange that you would have checked whether this is your subscribe, so we see the speed, what is in the subscribe, what is its index and what will be its index, the index of G should always be behind. If you are interested in the street then only you can subscribe to it because of the border, we have to keep the SIM. Right, if you have access here, assume that it is not yours, let's assume that we remove it here. Yes, we remove it for the back. Have to do, is this your sequel to this, what is the piece, see here, it is present here, it is happy, both are there, but after mixing it with border and drinking it, the apogee has to be seen whether this is this sting, is there G in it, is it not after P, you will not get it, but This is what you will live here, if I will live here, then you will be drinking after many drinks. Now look, I am busy. Yes, I got it because it should be a joint extra editor, so we are going to use it from here, what will we do here? Last we will see the index of this character and will finalize the next one that if we will fund the index of the lead character, will Arun fund it? On getting fine, we will see whether Urmila will be given to you first, Mila, if found, then what is his character according to the index, what is this cigarette, only then our What could it be, it could be in the pan, it could not be otherwise, so see this type of thing, if you come here and there is no jail, then check intake for P, next Jacqueline texture, this cigarette of coffee is there, if you don't get it here. But it is found here first, it is okay, so do you agree, do n't subscribe to it, but here one more is given at the back, which is after P, so we can consider here, so here we have we and jo. Who are going to use it, what will it do from A to Z that if it is here or here then it is possible that now it is possible that there is some extra inch, let's assume that the aspect index is why the young man should make his name famous by starting with 1 inch here. Will take, after that, this relationship that has happened, it will store it here, night, what will happen to you here, in a security for, you are going to get the index about the particular tractor, if it happens here in the sting, then here. But because of the approach route, we have taken many stars here and the ones that will cover your back and the cut thing that is on the track, you can say in a way that please check where it is for that. We are using that character and it can be multiple, so where is its position, here we are ok to make that call, so what is going to be our approach, see what we will do here, you and I believe that everything is ok here. Then after doing my show, it will be quite long, I can see something here for A, here for C, here for D, in the file, it is okay for these and for this, yours will be six, clean, G, H, where till P, do it. This is going to be quite long, so just accept it, there is no need to tell that much, if you have understood, then look here Deepika, what will you do first, whatever position is here, then here you can also go to Jio Store. Everyone seems to be okay with this matter is S, here we have induction for the owner add, and what will we do here, what is its position, so here we will do one, then one is here. If there is a special two here, then we will force it here, then we will accept the inch one, it is good that our someone else doing MS Word match position is 20123, here we will make the gender store of 3 ok happy and then this one is for Let's assume for me, for one g, let's assume that your fold is going to be a bit, right, zero one two three four, then what we will do for p is that your fiber for p is five a fiber for p and then Your more ad song again 6 will start their monthly this will be 6 after that what is yours this is a top-20 over here then here is intake or is a top-20 over here then here is intake or is a top-20 over here then here is intake or pictures or it is human somewhere else ok now this work It will be your 8 A Look at Life Apps for FD Account Prakritiyan Let's cover the position now, Naagin is ok, this is your dominant, ok now what will we do, how will the approach be, in this we have done the index of Alum Saare in 60 years. Thank you to everyone for the number of backs in this sting in the year, where is the position, we will start from here, okay, so first job chart will be done, here we will wipe it thoroughly, we will see what is the index of inches, what is the acid, what is this injection, how better. What is the index of picture like Twitter is there more indexes behind is greater what is one line tax like fear can you text acid if all the returns will go on getting the sequel of pregnancy is tight so here what we will do it means Here this trick is this award fracture, you know the position of this character, then you will fine the portion of this match, here again one position you know, check any A pointed of bread, what is this acid, nice composition, yes, so all this is like scalar. We will do physical check, we will click, see, we will all click, one by one, our efforts are indexed, we will keep making less money, okay, now what will we do, we will take the enjoyment here, now we will take it, let's start from here and see one before this. If he is a cricketer then what will we do, for this we will put the index of his effort - I OK - I index of his effort - I OK - I index of his effort - I OK - I took it here then you will check for one cup, what is your position, update it here, you will get one position of Pattu, first of all ok. Hey, you will get this, you will do it here with two, see how you did it, mother, why don't we take two here, because we are not the best bond, then Vansh Twitter, which one will you get? For one, you will get two, not seven. Will get that airport want justice a great karke hoga tu hoga - justice a great karke hoga tu hoga - justice a great karke hoga tu hoga - Messages Twitter If I return, then this award will be used by others, then use the point between or turn on and use two, here you will get it, then you got it, then you What will you do, will you move forward, will you do any side of today's match, there is a portion of glass, if you get a stone, then you will get it for free here, when I call him, but the bond is there, what are you going to get, this is three, okay, so you got it. Nothing, then we will move ahead. If we check for this, then what will it come? 438 Apart from God, it will be pa for rate that the song will be played again. Happy's portion is on 5rs, so it will be 4.5, okay portion is on 5rs, so it will be 4.5, okay portion is on 5rs, so it will be 4.5, okay then Jacqueline check. If you do, then what was the prime of floor five, six became six, then one point here you will get 101 of six, you got it, then what is you sir, this is one of the portion of which is the powder of seven, that is, what is this? If there is a subsequent, then what will we do, Rafi said all this sequence of including the match, like the one who checks for all of us, OK, then let's see the code of the school, understand the vote, again there is nothing approaching your chest, but what have we done here? The account has been taken in word size, do we not accept these? Total marks in word size are our account, gas subsidy is so much, why should we use a name, will we never vote, who are we not doing plus, okay here we have taken the batter index Bluetooth. What size is it by taking lemon juice and the points will be up to five okay then what will we do 11 Chapter First here we will support the index - one by one when it came to we will support the index - one by one when it came to we will support the index - one by one when it came to that point then it after people stay here start today then what will happen here will start Okay, so what is after this, we will go through a canter of one word, so what will we do? Gas Index - Let's assume here, okay, Gas Index - Let's assume here, okay, Gas Index - Let's assume here, okay, this is your address of awards, you will take out one word of one word, then you will see the word cricketer, so here. We have used record people, W World was about this cricketer, what will we do, so tractor index will sign reminder here, okay next point letter take or what will we do in it, we have funded the index of the chapter folded here. What will we do in this, we will check which is the last intact side, Dongri equal is fine and if you get the bond, we will first check whether this cater index has not gone till these, has it gone till the last, what is the domain that it is the percentage share in it, you and in it It is not the President. Okay, it is not the President. Laddu means that which is yours, which is the particular word, that batter was not mixed in it. Actually, okay, so what will we do? At that time, we have assumed that I have it. What should you do? Scandal. - - A new word is not its subject, Scandal. - - A new word is not its subject, Scandal. - - A new word is not its subject, okay, there is no proof of the one who has an Instagram account - - We will do it further, Instagram account - - We will do it further, Instagram account - - We will do it further, no need to check, next is the character, he is not quick in technique, let's put one here, okay otherwise. If we got the last of it which would not have gone even within an inch of it, you are the dominant dream, we have got it, now they have got it, what will we do, will we update the gas index of the previous one which is ours, just weigh it and cut the total account of the tractor. The account will be transferred to the one which is found last. Ok, let's turn the mode. Compilation is done and submit. Ok.
Number of Matching Subsequences
binary-search
Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\] **Output:** 3 **Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ". **Example 2:** **Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\] **Output:** 2 **Constraints:** * `1 <= s.length <= 5 * 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 50` * `s` and `words[i]` consist of only lowercase English letters.
null
Array,Binary Search
Easy
786
423
hey what's up guys uh this is juan here again so uh let's take a look at today's daily challenge problem number 423 reconstruct our original djs from english i mean this one it's a very interesting problem you know not like any other problems only code so basically you're given like an empty string containing an out-of-order english out-of-order english out-of-order english representation of digits from zero to nine so only from zero to nine and you need to output the digits in the sending order so which means that you know the input only contains the lower english letters and the input is guaranteeing to be valid and then can be transformed into its original digits so that means you know the abc it cannot be transformed into any uh any english letters english word right and the input length is less than five fifty thousand so what does this one mean it means that you know uh we have we could have like different uh digits but now it's being uh represented by it's in the english letters so for example we have 0 1 2 which means that we're going to have like a 0 right and then we have 1 and then we have 2. but the other objects of this kind of uh all the uh the letters are wrong basically these are the all other three other letters but they are in the different random orders and our task is to basically to reorganize them so that we can print we can know how many what are the numbers right and it could be one so one digit could be uh have multiple uh appearances because the length is 50 000 right so this one you know all it requires is it's like some observations you know then why is that because you know with this kind of uh random other numbers which we shouldn't we let's say for example if we pick o here right so we don't know how many we have because all belongs to different uh digits english words so which means we by looking at oh we don't know how many uh how many zero or one or two is there right but if we look at zero right but there are like some english sliders that can only have one have a unique numbers so what does it mean that you know let's say we have let's output everything together uh from the start to from zero to two to nine so zero that's zero right and then we have one right we have two we have three right then we have four then five all right six seven eight and nine basically this is the out of 10 digits the english words right so if we look take a look so this one what does it mean it means that you know this one it's only has so z only appears in zero right i know what are the others right so uh the other one is two here right basically 2 w only appeared in 2 so which means that you know if we know how many z appears in this in input here we know we will know that not that it can we can tell how many zeros there right similarly for two here and what else uh the next one is four right actually so four means like it's u right u only appears in this four the next one is six means is x right x only appears in six and the last one is eight is g right so if we can basically uh get so we can the first round we can simply get the how many zero two four six and eight by counting how many unique letters we have here right and then for the remainings we basically will use the this previously calculated results to calculate these three here to calculate all these uh remaining here and we have to follow a sequence right so the first one is three here so let's see for calculating three how can we calculate three here uh we so three has t h r e right and basically we have to calculate a three based on this uh just the first round results right so basically if we look at closely actually we can use h here because h only appears in eight and three since we have already calculated eight here so we can simply do a h minus eight right so i'm using the eighth to uh to represent the previously calculated results basically h means that the count of h right so that's three the next one is five so how about five so five we have i v e and e appears into so many places and f right since we just calculated uh we already calculated f here right now we have f minus four because i have only appears in this half here in this four here and the first seven so for seven let's see seven is it's v right we have v here okay v only appears in seven and five here so we have v minus five right and then the last one is nine oh sorry not the last one this one is nine so nine we have uh and we can't because n also appears in one here actually for nine we can either use e or i either one is fine so if we use i here you know we can have like i minus what so i appears in five right five and then six right and then eight that's how we calculate nine here and the last one is one so for one uh we can use actually for one we can use any of the letters because you know we have already calculated all the other uh letters we can simply pick any of them so for this one let's pick o here so we have o minus what minus uh zero right and then minor is two and the minor is what the last one is four okay yeah so that's going to be our strategy so let's translate this one into the code so first one we're gonna have like count equals the counter dot s right then i'm going to have like the uh basically the uh the answers to store the uh inter medium result right so like i said the first round is answered zero equals to the count of z right the answer two equals to count of w answer like four gonna be the count of u right and then answer six because the count of x the answer last one is eight that's the first round we can see oh we can simply use the unique ladder to calculate the appearances right in the g and the second round is three right basically three equals to the count of h right minus answer eight right and then the answer of five uh actually so counts five f minor sensor four closer seven right it's like a tedious repeating like copy and paste here v minus answer five the answer nine goes to count of i right minus answer five minus answers six minus down to eight right the last one is one basically the uh kind of o right minus answer zero right answer two then answer four right so that's going to be the answer and then uh once we have the count for each of the digits we simply need to output the output and um so we have output right i mean we can simply do this right so we have because starting from empty for i in range of 10 right starting from the smallest because it asks us to output in the ascending order right so basically output plus this one right so we have um so the ladder for this one is going to be the string version of i right and then how many appearances is going to be the value of this one going to be the answer of i right and then we simply return the output in the end run the code accept it yeah there you go right so that's it right i mean it's a very different problem you know you just need to be able to systematically uh deduce the count uh for each of the english for each of the digits actually i'm bit i'm kind of surprised this really works actually you know it's just like maybe it's just like coincidence that you know we can just like there like enough like unique numbers unique letters we can get several numbers the count of several digits and then based on those digits we can deduce get the remaining count for the odd for the remaining digits it's very fascinating actually and yeah i think there's nothing else i want to talk about right so i mean for time-space complexity mean for time-space complexity mean for time-space complexity uh it's pretty obviously it's all of n right since we do a count here yeah that's it right and then here's like oh often cool yeah i think i have to stop here and thank you for watching this video guys and stay tuned see you guys soon bye
Reconstruct Original Digits from English
reconstruct-original-digits-from-english
Given a string `s` containing an out-of-order English representation of digits `0-9`, return _the digits in **ascending** order_. **Example 1:** **Input:** s = "owoztneoer" **Output:** "012" **Example 2:** **Input:** s = "fviefuro" **Output:** "45" **Constraints:** * `1 <= s.length <= 105` * `s[i]` is one of the characters `[ "e ", "g ", "f ", "i ", "h ", "o ", "n ", "s ", "r ", "u ", "t ", "w ", "v ", "x ", "z "]`. * `s` is **guaranteed** to be valid.
null
Hash Table,Math,String
Medium
null
48
hey and welcome today we will solve rotate image interval question which mostly asked by Amazon as lesson other companies like so we will explore two interesting solutions for this problem so without further Ado let's Dive In first example as you can see top Edge moves to the right Edge move to the bottom Edge bottom to the left and finally left to the top that is what this question means by rotating 19 degrees clockwise second example again rotating 19 degrees clockwise would be like that but note that when we have more than one layer we need to take care of all possible layers in that data set like in this case we need to rotate the inner layer as well so if we do it one more time it will be like that let's jump into the solutions so there are actually two solutions for this problem first one is a bit mathematics related and easy but second one I would like to call it engineering oriented we will explore both for Mass solution what we need to do is a simple we need to transpose The Matrix first rows becomes columns and columns becomes rows and then reverse every row inside of that Matrix those two steps will give us the answer as you can see it in here and the code for that is going to be super simple like this for more in-depth simple like this for more in-depth simple like this for more in-depth solution the idea is that we can rotate Matrix in groups of four for each cells in the edge of Matrix for that if we break this solution down we need to consider three things first we need to perform swapping cells in each layers of our metrics that means we need to find the depths of it second is how many operations we need to do per each layer and lastly we need to find which cell will replace which for finding the depths of our Matrix since it is n by n Matrix and all sides are equal we can cut one of its edges by two and that will be your depth we will use Master floor because of odd cases since the very center cell of Matrix in odd cases doesn't need to be rotated in order to find the operations count in each layer we need to swap cells values as long as we've done with the edge cells but we don't want to swap the last cell in the edge right because it just solved with the first cell so the number of operations per each depth will become n minus 1 where n is the length of our Matrix and negative 1 because we will ignore or the last cell but that is not the end of the story as a last thing how we are going to know that which cell should replace which we need to know target cells index before getting replaced for Corners it's pretty much obvious we know that Corners might be replaced with other counterparts the tricky ones will be the cells and the edges we will have I and J indices from or traversal but we are going to need a third variable in order to keep track of the distance between base cells the cell that value comes from and the target cell the cell to replace its value and we will call it offset this offset will be again the edges lengths minus one everything is kind of simple so far four or three by three Matrix but let's just spice it up a bit what if we have four by four or even five by five one below our solution work well no everything we did so far was based on the layer we were in I mean the operations count and offset variable was for that layer and obviously we might consider them when we have bigger matrices so let's take the big elephant in the room and explain if we go the one layer or edges in The Matrix will be reduced by two cells so we might subtract that two cell from operations count in each layer that we go dip and for the offset as well we might subtract the depth index as we go deep into our Matrix because we need to do our operations in their respective layer and don't want that performing operations from deeper layers mess up already swap numbers in outer layers okay all of those three important factors will come together in order to make the swapping cells to happen but how if we have the depth we know that how many times we need to do all work in this case three times if we know the operations count we know how many swaps we need to do in each depth and if we know the offset amount between cells we would adjust the inj indices with or offset in order to know which cell will replace which one quick thing before jumping into the code for doing the actual swap if we start doing it clockwise we need to do three things first find the base cell and the target cell second store Target sales value in the temp variable and lastly replace target cells with the base sales value this will happen for each operation in each depth of our Matrix but the point here is as soon as we done with our first iteration we need to keep the next operation's Target sales value in a temp variable right I mean the 9 here but at the same time we cannot override the temp variable which we have from previous iteration because if we do so we will lose the previous temp value before even using it so we need a new temp variable after updating our Target cell but this cycle will go through all operations in the given depths right actually there's a way to get around this if we perform this operation in counterclockwise we will only say first sales value in a temp variable and replace it with the previous cells over and over until the last one at the end we will have an empty cell right here that we can use our temp variable for it now let's jump into the code to show you this process first thing we need to do is getting the length of our site or so-called edge of length of our site or so-called edge of length of our site or so-called edge of our Matrix then it's time for our depths as we discussed earlier it will be our Matrix length divided by two but wrap the Master Floor for odd cases then it's time for our iterations based on each level of depths we are inside of this for Loop we need two things first or operations count second the offset operations count will be length of our Edge subtracted by last item we also need to consider the depth remember that each level we go deeper we get rid of two cells now or offset again it is the length of H minus 1 and also subtracted by The Depths now we need to take care of each operation right for that we will do another for Loop inside of this first we will get a backup of our first sales value then we will swap values in counterclockwise and also please note that how we are leveraging the offset variable in order to adjust the coordinates of target cells in each operation so at the end we don't need to return anything now if I run this test cases are passing and if I submit we are in a good shape here now let's jump back to the slides for time and space complexity analysis for time complexity we will have o of C where C is the count of all cells in our Matrix and that is because every cell has been read and swapped only once for space complexity it will be all upon because we really don't do anything special with memory so that was it for this video I will put erase playlist in the description for you to check it out thanks for watching and please leave a like comment and subscribe to the channel and finally hope you enjoyed this video and stay tuned for the next one
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
454
uh hey everyone nitish's side so let's start with the question so the question is four sum two so you have given four integer array number num two num three and m four oh all are of length and it and you have to return the input basically i j k l uh it will be the sum of that pointer is equal to zero so let's see the question what's it's asking so we have this num1 num2 num three and num four and we have to sum the array of each element which gives us sum of as 0 so basically we need to do is num i plus num j plus num k plus num l equal to zero okay so if i give you an example it's basically 1 plus minus 2 plus minus 1 plus 2 it will be 0 similarly one more example will be 2 plus minus 1 plus 0 it will be also okay so you i hope you got the question so let's see the approach what we can do so if i go with the base approach that i was thinking so what we can do we will basically loop all over the element so basically first loop will be over num1 then your second loop will be on num2 similarly we have num 3 and we have num 4 okay and we'll check if their sum is equal to 0 then we increase well let me take a counter variable then we increase the counter by one and we just return the counter okay so if you can see the constraint of the question it is 200 basically so if i mention it here it is 200 okay now how can we optimize basically if we use the ca this approach so this will cause us basically for loops so for one it is 200 for four it will be basically 200 into 202 so as you can see this is quite large so we can't take this up okay so as our previous approach is taking so much time so we will need to optimize that so how can we optimize it we can use some sort of a hash okay so what we will do we will take uh any array and store it in a hash okay so what i will do i will take the num4 and store it in a hash okay so this will be like this so i will take the first element and i will push it in a hash similarly i will take the second element and i will push it hash and increase it value by one okay if it is not present the by default value is zero and after that i will increment it by one step so what i will do i will go to so let me take a count variable i will loop over first element similarly i will loop over second element and similarly i will loop over third element and i will basically calculate the sum from here okay a plus b plus c now my question condition is a plus b plus c plus d is equal to zero okay if i know that the result i just need to do is basically d is equal to minus a plus b plus c okay so if a plus b plus c negative is present in my map that means i got the sum as 0 so what i will do the sum into equal to minus 1 and i will check if basically not if i will just do it like count plus equal to map dot get this sum okay so if i got uh as value 1 so i will store it and i just return the count okay now what's the problem with this approach also basically i'm taking again three loops so the previous one is having order of n to the power four but for this we have order of n cube we optimize it but the question constraint is not so small so we need to optimize this more further so what we can do is basically we will go with the same approach so instead of one array what we will do basically we will take two array in a hash map okay so what i will do i will take it like this so basically hash will be like this i will first push the sum of these two element in the hash and after that we will do so how can i push it so i will do minus 1 plus 0 equal to minus 1 plus 0 is minus 1 so i will put it minus one and with the value of one again i will do minus one plus two which is equal to one so i will push it in the hash map so one again i will do two plus 0 which is equal to 2 and i will push it and i will have a value of 1 similarly i will push 2 plus 2 which is equal to 4 so 4 and a value of 1 okay so this my hash is created now i will only loop over this two element okay so i will do four a in num1 similarly for b in num 2 and i will calculate the sum first a plus b now as i already told you like a plus b plus c plus d equal to 0 this is the question condition so we have already c plus d in our map so c plus d is already present so what we need is negative of a plus b in the second array is it there or not so what we will do sum into equal to minus 1 and we just do one thing let me take a count variable count equal to 0 and we will check we just do plus equal to map dot get basically this sum is it present or not if it is present then it will increase my counter and i just return the account okay let's try and this so in num1a we have let's go with a equal to 1 and b equal to minus 2 so this will be equal to 1 plus minus 2 which is equal to minus 1 so minus 1 we have already in our map so this will increase our counter so our counter will increase by 1 so counter is now one similarly now b will update to minus one but we will do one minus one now the sum is zero so this is not so sum is equal to zero this is not present in our maps or complements one only then our a will update to two and our b will be point two minus two and we do two minus two is zero so similarly zero is also not present in our map so we'll increase the pointer of minus 2 by minus 1 and we will do 2 minus 1 which is equal to 1 and we see 1 is present in our map so we increase the counter by one okay now what's the time complexity for this so time complexity for this is we just iterate over two loops so for this equal to order of n square and plus order of n square for uh storing it to the hash map or a hash map and the space will be we just basically store it into the hash map so it will be also of order of n square okay so let's write the code for this so let me take a counter variable okay what we will do we will take a map also we just need an integer over integer array and we iterate over first let me just let c equal to num three and for end d equal to nums four i'm just using ending slope you can use any loop and we calculate the sum from them c plus d and what we will do basically map dot put this up and we need to check whether this is already present or not so how we'll do we will check map dot get and there is one function get or default also let's say this sum is not present in the map so it will give a default value to that sum equal to zero if it's not present then give zero if it is present then give that value less one and similarly so this will create our map then we need to check the sum how can we check that so we will just do 4 in a over first array then we do entry over second area and we need to calculate some equal to a plus b and i will tell you we need to negative this sum so equal to -1 and we negative this sum so equal to -1 and we negative this sum so equal to -1 and we check we increase account by map dot get or default basically let's say this song is also not written in the map the medium full value and we do sum okay by this we can try default value or the summary in the hash map and we return the count so let's run the code and see hope it will run so let's submit so it is dominated and as you can see it the dynamic text i got when i use the for loop uh basically the problems that's why it is giving the time limit exits so i hope that's good so i hope you like that video
4Sum II
4sum-ii
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that: * `0 <= i, j, k, l < n` * `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0` **Example 1:** **Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\] **Output:** 2 **Explanation:** The two tuples are: 1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0 **Example 2:** **Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\] **Output:** 1 **Constraints:** * `n == nums1.length` * `n == nums2.length` * `n == nums3.length` * `n == nums4.length` * `1 <= n <= 200` * `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
null
Array,Hash Table
Medium
18
1,706
hello friends so today in this video we actually gonna discuss the problem from lead code problem name where will the ball fall so it's a medium lamp problem i will first let you understand the problem statement it actually states that you are having a like a 2d grid okay and each grid has some sort of panel okay as you can see the panel can be like this it can be uh going from the top like top left to the right bottom or like a top like right to the left so it can be like this now at each position like each column you will throw a ball now if there is a way the ball will go and slide down to some particular column but maybe it cannot go maybe it can like uh like get stuck at some position so you just have to tell that whether each ball like reaches to the particular column if it reaches down what is the particular column it will reach if it cannot reach down like you just have to print out minus one so as you can see for this as you can see the first ball uh will go to the first column as you can see column one else no one reaches down so the answer is minus one for all the following now uh the first thing uh you can simply observe is uh so let's do that if there is a some particular position let's assume that the ball is at this position now any ball which comes to this position will eventually leads down to this column so it means that if you store out for every position what is the uh for every position what is the column it can reach so any ball if it reaches that position will reach to that so it means that you can use some sort of dp you can store for every position what is the final column it will reach or it will not reach any position so it can be minus one so as you can see the number is also 100 uh like column and like rows so you can also make a memoration table for that so now how you can approach this problem now as you can see if for any like we just talk about some general case if first say like as you can see for this block if the block is having a diagonal like this and the next block that's just adjacent to this is also a diagonal like this then the ball if it is dropped in this position then it will go to this diagonal block so if this is like r comma c this is like a row x comma y block and the xor y block is having this type of diagonal and the next adjacent uh diagonal is also like this then if a ball is dropped here it will reach here i hope you get the point and uh the reverse is also possible so if some diagonal position is like this and the another is like this so the ball will go in this position so from this x comma y it will go to this column uh which is the row is changed so x is increased and the y is minus one and in this x is increase and y is plus one so you just like you can uh take every ball and then try to drop it up along the path like what is the path it will reach and also try to store out for every uh position if another ball land down to this position what is the uh like the path it will reach okay so that's the simple problem i will show you so it's just required dfs uh some sort of dfs because the recursive function to start the ball from one position and what is the path it will take and maybe some another ball will take that path and then what is the like final solution for that sorry for the code part now uh as you can see in this problem because the constraints are very small you can do this for every ball like uh you can just take out for every ball individually find out into which column it will take no need to use a dp table because the constraints are small but uh to increase the speed you can use dp because as you can see you can observe that for if you know the position that for this block if the ball lands at this position uh what is the partial column because it will always lead down to the same answer so you can also use that so what we'll do we'll first find out the grid positions uh n comma n we just make it global so that we can find because we have to make that we have to also make a is valid function because in most of the great problems we have to check that uh because if we are on some position we have to check that uh like if for some addition positions we have to check that whether we can go to that we have to check that it should be inbound so we have to always make a like is valid function so uh then we make a dp table so as you can see generally we initialize db table with minus one but because in this minus one can also be answered which means that if a ball is at this position it will not reach any position so minus one for all the positions like if any ball come to this position the answer is obviously minus one so we have to also stop minus from that so that's why we make a dp table uh because the tps uh we have initialization variable we resize with minus two or you can store it with any negative number apart from minus one okay i just use minus two whatever you can use and then this is the answer vector to start all the answers then for every wall we call this okay function okay so this okay function will return out the position or the column at which that particular ball will land now what we'll send in this okay function will send the grid because we have to iterate over the grid we'll we will send out the row the particular row on which we are and currently we are on the zeroth row and the i means that or at which column we are okay and then we just return this answer that's a vector now this is the invalid function we just return our object that whether this x comma y if we send that if in like invalid or like if it is valid so how we can check that x should be in one which is like it should be greater than equal to zero and it should be less than n obviously and for y it is greater than zero and less than m so this is the like if all the conditions hit true and then that coordinate is valid and then we'll just return out that yes that's valid then how this okay function will work we just find out the base condition is when we just go out of bond which means that the ball fall and just go out of bond so it will happen that when r is equal to n uh then like because we just start from first or second one third row when my number of like rows exceed them like this box which is like equal to n then we just write around at which column we are because column is storing that else at whenever uh grid point we are which is r comma c what we will check that if we are some intermediate row if we are let's assume that if you want to check that for this particular row if it is valid or not we will check that whether this particular uh this particular what we can say this particular grid point is valid or not if it is valid then we will go and check that okay if this particular get like good position is valid then we will check that okay if this is having one so this type of diagonal is represented by one and the another type of diagonal is represented by minus one so if this is minus one and the next column position which is like this addition cell which is like if this is r comma c this is r c plus one so we just have to check that whether that exists or not if that exists and that is also one we just have to check that all of the conditions are true then we just check that okay now both of them are in this format so the ball will go to i plus one c plus one r plus it means that to the next diagonal like this position so we will check that whether we have found out the answer for that how we can check that if the dp table of that particular coordinate is minus 2 then we haven't found out because we have initialized with minus 2 but if it is not minus 2 it means that we have found the answer for that and we can use that so we can just return out that else if we haven't found out we will store that answer and we'll call that recursive function again for this quadrant okay then we'll do the same thing for minus one positions like if this position is minus one and uh if this is minus 1 and the left side of that is also minus 1 and it is in like it is valid then we will check that if it is found out then ok then and it does not find out that we will just return it minus one okay and then for any of this case if it doesn't hit the answer might as well okay so that's the code for this problem i hope you understand the logic and the code if you still have any doubts you can mention it on as a next one until then keep coding and bye
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
1,558
uh hey everybody this is larry this is q3 of the recent nikko contest if you stayed to the end you're watching me solve it live during the contest um hit the like button hit the subscribe button draw me a discord and let's get started uh minimum number of function calls to make target array so we get this function which is actually like i don't know why they wrote it like this um because they could just literally just give you the definition of two functions which is one uh you have basically two functions you can do one is to increment by one and then the second one is by doubling right um so this one took me a little bit of time just to think uh i spent about four minutes but most of that was just thinking because the code ends up being really quick uh yeah so how do i solve this so let's think about this one number at a time uh and i actually to be honest i sorted this during the contest it's not necessary um for me i just figured maybe there's a way to reason about it but actually it wasn't necessary so i wouldn't worry about it and again you can see that it doesn't matter um in terms of uh whether it gets accepted or not but let's say you have a number like five right so the binary representation is 101 right or seven which is one and then say i don't know uh 11 which is my map is not as good so something like that maybe uh well the question is how many operations to do this one right well minimally uh you need to press one plus one at the way at least you know that you have to use the first operation twice because the two ones right and then you can just double them and like you know playing around with binary numbers the easy the obvious quote way of doing it and you know you should prove to yourself at home it's just to construct you know you start at one you double it to 10 and then you add uh and then you double again to 100 and then um you add one to 101 right similarly you go one um you know double it and then go to 11 double it and then one run one right and so forth so you can kind of see the pattern how you want to do it individually but in this case uh of this problem i'm not going to draw this out uh because i'm lazy okay i guess i am maybe i'm not that lazy but yeah so you get the pattern here right um for each individual number but that's not enough for this problem right the problem is that you have to uh for operation one the second operation uh you have to multiply all numbers by two so you draw the shifts together right so that means that for me the way to figure that out is that actually well the ones they're adding ones you cannot do it together but the doubling you could always do it together so basically your doubling is going to be affected by um by the number of times the most number of times you double so basically that's my strategy uh of solving this problem is that you know i have a count for a number of this is for the number of ones that we have to add and there's no way around it so you just counting them all up and doubling we just keep track of the max of the doublings um by taking it half the number of times you count by half which is the reverse way of it for example you know that for five and seven we have to double it twice so then that means that you know that's all you have to do that means that's two but if you add 11 to the list you know that you have to double at least three times so that's how you would um uh and then that's how you kind of count the max double in that case and then use them all together right because if now let's say you're constructing them together um well first of all you know you would you know pat a zero i guess uh so in the first set of moves you would just add one for the 11 and then you double to 10 and then now on the second digit basically we're doing it digit at a time so let's convert this to zero so then now the second digit you have one um and here you do ten and don't add a digit and then so forth so that's how you kind of do it digit by digit and just counting them with digits in binary uh minus one because i guess one digit you know you don't have to double it uh so that's kind of my solution for q3 i actually think this farm is cute and i had to you know think about really think about what to do in this farm so i was cute uh anyway hit the like button hit the subscribe button drop me on discord and let me know what you think about this problem did you like it how did you solve it was another way and i will see y'all next one bye okay so hmm two so slow testing today so hey everybody uh yeah thanks for watching the video this is probably after you watched uh the live portion of the salving during the contest uh hit the like button hit the subscribe button join me on discord and i will see y'all next contest bye
Minimum Numbers of Function Calls to Make Target Array
course-schedule-iv
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls to make_ `nums` _from_ `arr`. The test cases are generated so that the answer fits in a **32-bit** signed integer. **Example 1:** **Input:** nums = \[1,5\] **Output:** 5 **Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation). Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations). Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations). Total of operations: 1 + 2 + 2 = 5. **Example 2:** **Input:** nums = \[2,2\] **Output:** 3 **Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations). Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation). Total of operations: 2 + 1 = 3. **Example 3:** **Input:** nums = \[4,2,5\] **Output:** 6 **Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums). **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109`
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
null
1,639
Hello friends a very happy good morning good afternoon good evening come to the problem of the day series and today we are going to solve problem number 1639 the number of ways to form a Target string given is dictionary from the lead code it has been categorized a hard problem and to be honest it is a really scary problem it took me more than 10 minutes to understand what the problem is and what I have to solve so let's try to understand the problem first so we had been given a list of the strings of the same length so we have given the string and which is of the same length so here we'll go the examples together so we have a c a b and c a so we have the same length of the string and we have been given a Target so Target is right now say you have been given a b a now what we have to do is that we have to build this Target string using this word using the words given here now the target has to be built from left to right okay so this whole thing to uh ith character and jth character let me simplify this thing is that once you have taken a character to make a string right so suppose that I have taken this character to form a character in The Target I cannot go back so that means that I cannot go I cannot pick any of the characters before this column even I cannot pick the characters in the same column I have to move forward though so just as that once you have pick a character you have to move to the right towards this side okay you cannot move back you cannot use the same column so for example in the same problem we had a c here so I am going to make form here a B a I cannot pick this one so the next one I can take this was one way second one is I can grow a b a which is the second one so for example like we can take this character so we can take a B and A so that is the third one and we can also take a b a which is the fourth one so now how we are going to solve this problem is so one way is uh simple that suppose I have a Target right so we had a target of here a p a and let's say that I have to make this index Target index and then I am going to Traverse in this array and see if my character is matching with your target index or not and if it is matching that means that I have found one possible way of building a Target index at this at Target at this index so now I am going to work on this for the next index and now my column is going to be start from this position right so this is how we are going to search let's start some coding so if my Target is null empty return 0 okay otherwise now what I'm going to do is we said that we want to match the Target and for a particular index so let's slide down uh helper function that matches the increased Target index so let's call it Target index and we also talked about the index at which we have to work on right so we will be starting from say starting zero index and at any given time we want to we are looking at the index of a column so that means that I should be having a function integer let's call Quality Index so when my target index is actually reaching to the end of my Target string so for example I started with here which is a zero right and then you have one and then you have two so that means that once you've reached at 2 or actually 3 which is Target length that means that you have actually built a Target means that you have found at least one way to build Target so that means that if your Target index is equal to Target dot length return one okay now in a similar way that the index at which we are working column at which we are working on once you reach towards the end right that means that you have taken the character from all the possible columns but still target has not been built uh means that now you cannot build the U that means that you cannot find a way to build Target so in this case if column index is equal to uh the column size which is actually integer length of the word right length is equal to words 0 dot length because all the words have the same length and zero and then let's declare it is a result is equal to zero and then for each string word inverse so let's say that I have to let's find out which character we have to match so the character that we have to match is character Target care is equal to Target of Target Index right this is the character that we have to match so now if no we have to search from suppose that I am looking at this particular column right so my for Loop is going to look for all the columns starting from this particular column till the end of column so for integer I is equal to column index and I is less than word length plus I and if word of I is not equal to Target character then nothing I have to be done continue otherwise that means that I have found out I am able to match the one character right so now let's move forward for the next match so now integer count is equal to uh we'll call the same function recursively number is words Target now my core next column is going to be I Plus 1. right and now Target index will be Target and that's plus one and this is the number of ways so result plus equal to count and we will say return result okay and from here we are going to call the function return number of ways words Target column index is 0 and Target indexes 0. a very Brute Force recursive way of solving the problem let's say if it passes okay so this is working fine for basic cases and I'm sure that we will hit the tle for this I expected okay so if you had been watching this until now I hope that you have liked this video please like it and I will really appreciate if you subscribe it so that you will be notified whenever I publish a new video so you don't have to go and search an elite code all right so let's continue with the next approach so after the Brute Force recursive so if I take a look at the column index and Target index it means that we might be solving the same problem for a given column index and a Target index so how about if we cache this value that we have calculated for this particular combination so one way of solving is like we can create a memorization error integer and let's say that you have words of 0 dot length so that is basically length of the word and comma Target Dot length right so this machine basically map is to your column size and this is your target length and then we will initialize this value with minus 1 f plus G right and then I am going to pass this memo into this function right now let's pass it as other places too all right so now let's update the result in the memo and return it from memo so that means that Target Index this so from here now if memo of column index comma Target index is not equal to -1 that means that we have actually -1 that means that we have actually -1 that means that we have actually calculated this value earlier so we'll just return memo right now at the end once I have calculated the result we will save this value result and yes and we'll return this value so one thing to note is that uh it has been mentioned right so we have to return the number of ways from Target verse modulo so let's do that so here what we are going to do is we'll see result is equal to result percentage 10 to the power 9 right so it is this one and we've convert it to long so that it can hold that value and then I have to convert this to an integer so earlier we saw till 40 cases so hopefully we pass it or we should be it should be improved so let's first run it we missed something let's submit still taking longer so okay so we reached closer earlier like my test question test case 41 now we reached further so 17 oddly this should be again uh good enough to solve uh now we have to do some optimization here so one optimization that actually we can do is since we have to count the number of ways right so that means that if I have the same character the have been is appearing multiple times right so instead of evaluating uh instead of evaluating for every Loop but actually we can do is we can just multiply it with a character count that how many times that character has been calculated so this will get rid of this for Loop and hopefully it will be having a better time complexity so let's see how we'll do that so ah we are going to create a first frequency map so similarly so you will have integer array frequency is equal to new integer and what we're going to say the number of rows is going to be what is the length of uh each word in words array so it will be words of zero dot length and we have 26 alphabets in this character okay and then for integer I is equal to 0 I is to be less than uh words dot length plus I and then for integer J is equal to 0 and J is less than words of 0 dot length side and then we get the character right so character will be your words of I and J right which is the character and if I subtracted the ASCII value from a I will get the integer that represents this value so let's say integer current pause is equal to this and then we will update the frequency row is going to be your J comma current pause Plus right so this becomes your frequency and I am going to pass this inside the function frequency inside this recursive function upgrade the integer frequency and okay so we got these things here now let's go ahead and solve this fix this Loop okay so let's we just remove this whole let's not remove it will Okay so at this character index that I am targeting right target of Target index so integer current pause is equal to Target of Target index minus a right now I am going to call this function recursive function for the next column right so in this case it will be your uh column index plus 1 and but for the same character and we'll cross the frequency here and say you get the long result and let's function return the long okay now we got this value for the next column now we are going to use the frequency mapping so we are going to call the same function again but now we are going to work on the next column and next Target index Plus 1. and then we will multiply it with the frequency of the current column index and current pause right and make sure that we convert it to Long otherwise we would be having in trouble it took a lot of time for me to figure out where actually I am screwing my code all right so till here and then result is equal to this and we will return that value okay so we have some trouble here uh I and then J okay this is plus J run and then submit the solution okay uh so this is the recursive with the top down approach I believe that we can write down a similar solution from the bottom up approach yeah and that's the solution for today's thanks for watching and if you have liked this video please like it and subscribe it will help me for the YouTube algorithm thank you
Number of Ways to Form a Target String Given a Dictionary
friendly-movies-streamed-last-month
You are given a list of strings of the **same length** `words` and a string `target`. Your task is to form `target` using the given `words` under the following rules: * `target` should be formed from left to right. * To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`. * Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string. * Repeat the process until you form the string `target`. **Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met. Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba " **Output:** 6 **Explanation:** There are 6 ways to form target. "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ") **Example 2:** **Input:** words = \[ "abba ", "baab "\], target = "bab " **Output:** 4 **Explanation:** There are 4 ways to form target. "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ") "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ") "bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ") "bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ") **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * All strings in `words` have the same length. * `1 <= target.length <= 1000` * `words[i]` and `target` contain only lowercase English letters.
null
Database
Easy
null
430
hey guys welcome back to another video and today we're going to be solving the lead code question flatten a multi-level lead code question flatten a multi-level lead code question flatten a multi-level doubly linked list okay so we're given a doubly linked list which has a pointer to the next node and to the previous node but it could also have children pointers so these children pointers could be pointing to other doubly linked lists so our task is to take this multi-level doubly linked list take this multi-level doubly linked list take this multi-level doubly linked list and then we need to flatten them so let's see how we can do that okay so this is the linked list that we're given for example and let's see how we can flatten out this multi-level linked list flatten out this multi-level linked list flatten out this multi-level linked list so what will you do is we're gonna implement a stack in order to do this and we're gonna iterate through our linked list so first we're gonna go to the first to the head and we're gonna look to see if it has any children notes so it doesn't so we're gonna leave it neither does the next node but once you get to three we have a children node a child node so what we're gonna do over here is we're gonna take this part and put it inside of our stack simultaneously we're gonna point the next node for three two seven and seventh previous node is gonna point to three so let's see how this actually looks like alright so after that what we'll do is we're gonna go to the next node seven so seven also doesn't have any children notes but once we reach to eight we have a child node again so we're gonna perform the same thing so we're gonna make the pointer the next pointer for eight it's gonna become ten and the previous pointer for ten is gonna become eight and what we're going to do is we're gonna take everything to the right of eight so nine and null we're gonna take that and put that inside of our stack so let's move that again and see how our linked list is gonna change as it is right now we have a flat linked list but we don't have all the elements in it so we're just gonna keep going so we all the accounted for eight ten also doesn't have any children nodes neither does eleven and obviously null doesn't so after we reach the end of our linked list so far what we're gonna do since we did not account for all of our elements in the linked list yet what we're gonna do is once we reach this end we're gonna start popping out the elements inside of a stack so first we're gonna pop out whatever is in the last index so we're gonna pop this out and we're gonna add it to our linked list so since I don't have space I'm just gonna continue adding it from here so nine and then no and similarly after we pop this out then we're gonna pop this element so for five and then no so again what we what's gonna happen is we're gonna keep going through all of the nodes so this doesn't have children nodes and none of them have children nodes and once we reach the end and our stack is empty so in that case we'll be done making our multi-level linked list done making our multi-level linked list done making our multi-level linked list into a single leveled one okay so first we're gonna initialize our stack as an empty list and we're gonna also store our head value inside of a temporary variable so I'm just gonna call ours temporary variable start and that's gonna hold the value of the head okay so now that we have this we're going to go in while loops so while head exists and so while the value of head is not equal to none and what we're going to do is each time we iterate through our while loop we're gonna change the value of head to the net to the next node so head equals to a head duck next now we also need to add a few things before that so first we got a check if that node has any children nodes so we can do that by doing if head dot child so if a child node exists we're gonna go inside of this loop and we're also gonna check if there are any elements after so if head dot next exists so if head dot next and in that case what we're gonna do is we're gonna add that to our stack so stack dot append head dot next and one more thing we have to do we're gonna change head dot next value to that of the child so had our child and head dot next value a previous value since it's a doubly linked list we also need to take care of the previous pointer is gonna just be the head and finally currently head dot child has a value but in this case since we're flattening it out we're gonna change that to none okay and now one more thing we need to check for is when you check if we are at the ending of our linked list so to do that if now we need to check if we're at the ending of our linked list so to do that what we're gonna do is if head dot next is equal to none so that means we're add so we're at the ending and if the length of stack is not equal to zero so what that means in that case is we reach the ending and now we need to add the elements inside of our stack and add it back on to our linked list so to do that what we're going to do is we're ahead dot next it's gonna have the value of the last element inside of our stack so we're just gonna do stack dot pop which pops out the last element so and then we're also gonna change the previous so head dot next previous value is gonna have the value of head okay and so that should be it and why once we're done with this we're gonna go outside of our while loop and we're gonna return that temporary variable we stored in the beginning okay so return I call it start so return start okay so now let's submit this all right so our code got accepted and finally do let me know if you have a better solution to solve this question and don't forget to Like and subscribe for more content like this and I also post of projects and stuff like that so if you're interested don't forget to subscribe thank you
Flatten a Multilevel Doubly Linked List
flatten-a-multilevel-doubly-linked-list
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below. Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list. Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`. **Example 1:** **Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\] **Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\] **Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: **Example 2:** **Input:** head = \[1,2,null,3\] **Output:** \[1,3,2\] **Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: **Example 3:** **Input:** head = \[\] **Output:** \[\] **Explanation:** There could be empty list in the input. **Constraints:** * The number of Nodes will not exceed `1000`. * `1 <= Node.val <= 105` **How the multilevel linked list is represented in test cases:** We use the multilevel linked list from **Example 1** above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: \[1,2,3,4,5,6,null\] \[7,8,9,10,null\] \[11,12,null\] To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: \[1, 2, 3, 4, 5, 6, null\] | \[null, null, 7, 8, 9, 10, null\] | \[ null, 11, 12, null\] Merging the serialization of each level and removing trailing nulls we obtain: \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
null
null
Medium
null
61
welcome to october's leeco challenge today's problem is rotate list given the link to list rotate the list to the right by k places where k is a non-negative if k places where k is a non-negative if k places where k is a non-negative if we're given the list one two three four five and a k of two we're going to shift it two times so that four is now the head and three is the tail you can see how it's done explanation similarly if we're given a list zero one two and a k of four we're gonna shift it four times now it's gonna be almost like we only shifted it actually one time because it gets shifted three times looks exactly like it did before and then it gets shifted once so now two is the head and one is the tail so given the explanation we might be tempted to write an algorithm to restructure this linked list each time by getting the tail shifting it to the head and making it point to the head and doing that k number of times but don't be fooled by this explanation really there's no reason to do this k times all we need to do is figure out at which point in this linked list do we need to restructure our linked list so that it whatever we're pointing at is now going to be the head and everything else needs to be shifted to the um to its right so basically say we're given like this list here uh what we want to do is we are going to go through this linked list and figure out how many n there are all right and the reason for that is once we know what the length of this linked list is it becomes very easy to figure out how many times like which linked which node is going to now be the head so say that we have five and we're given like k of seven or something like that we know that we need to shift everything to the right three times so that three is not going to be the head right so how do we do that um well if we were pointing at three right now and we want to say hey we want this to be the head all we need to do is take that previous node make it point to a null and make this new node be the head right and that would be it but the one problem here is that what about the five here like we need this five to still point all the way back circularly to the one so we'd have to go down all the way to here and then point that to the very head but how about this in the very first pass we are going to make this a circular linked list we'll make five at the very end point to the head and that's going to be circular now it's fine because we still have the head um initialized somewhere and after that then we can go through our linked list and find which node we need to restructure say that's three here take this previous node make it point to a null and make this three now the new head so at the second pass or first pass we should say count n and we should also make circular and the second pass we are going to make the previous node point to null and the new node bv head okay so that's going to be our approach so the very first thing we want to do is well if not head return head i should also say if uh or not head dot next because either way if there is nothing there or if there's only one node there's nothing to be shifted so we just return it back now we need to do our first pass and count n and also make this circular right so how can we do that all right well let's first make a current pointer i'll make that point to a head and we'll also initialize n and make that equal to one because i'm going to assume that this is like a regular array and make this zero indexed so n needs to start at one so while curve.next so while curve.next so while curve.next we are going to increase our n by one i will make cur equal to curve.next i will make cur equal to curve.next i will make cur equal to curve.next and this is going to keep pointing our pointer to the next node until there's nothing left that should give us the proper n and what we'll also need to do is say hey our current pointer is now pointing at the last node make that next equal to head so now it's going to be circular okay great so we've done that now we need to figure out which node do we need to point to restructure this make the previous node point to null and make the new node head so how do we get that number okay well i'm going to call that m and that's basically just going to be a modular function right we have to get n subtracted by the k modular m because this is the k can be greater than n we need to figure out how many times can we go circularly and just figure out how many times we shift in that last i guess cycle and we need to get the um the list index number and that's just going to be n minus whatever number we come up here right and now we have m so that's going to be the number we need to point at kind of like the list index of the new head right okay so now we could do finally our restructuring okay so what do we need to initialize a index number and make it i equals zero and we'll also put our head curve to head so while let's say i is less than m what we need to do well first we need to make sure that we um store our previous notes somewhere right so we'll say previous will equal the current and curve will now up to be updated to the current.next current.next current.next and we'll also increase our i and once we're here now we're at the new node that's going to be the head we're going to make previous dot next equal to none so that's not that's going to be the tail now and the new head is going to be equal to ker finally we just return our new head all right so let's see if this works and it looks like it's working let's submit that and there we go accepted so this could definitely be well as far as optimization goes it's an o of n time complexity and it's basically constant space so we can't really optimize any further than this we can certainly make this code look a little prettier and cleaner there's probably better ways to do it but the real key here is to figure out that we don't need to do this whole rotating and or k times because we're going to be doing a lot of unnecessary work then we just need to figure out what is going to be the last state of this k at the very end and then just say make this new node to the head and make the last one into the tail all right so that's it thanks for watching my channel and remember do not trust me i know nothing
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
304
hi guys hope you're doing great arteries question has ranged some very 2d immutable this is an extension to a AZ problem alright some query immutable which I have covered in another video to understand this question and its solution better it's recommend that you watch that one first alright so given a 2d matrix find some of the elements inside the rectangle defined by its upper left corner Row 1 column 1 and lower right corner Row 2 column 2 so we'll be given two indices right and those will be the diagonal points of the rectangle and the rectangle formed by these two points right we need to return the sum of all the elements that lie inside that rectangle right so the above rectangle with the red border is defined by a row 1 column 1 which is 2 comma 1 and 4 comma 3 and we have to return the sum of all these elements which is 8 so we'll be given this kind of a two-dimensional be given this kind of a two-dimensional be given this kind of a two-dimensional array or a matrix and there will be calls to some region which is a method which will provide the values of Row 1 column 1 Row 2 column 2 right and it should return the function should return the sum of all the elements inside that rectangle okay so I hope the question is clear there is also some nodes which says that the matrix does not change there are many calls to some region function and you may assume that Rho 1 is less than equal to Rho 2 and column 1 is less than equal to quality so as we had discussed in the previous video around range some query immutable this definitely is a clear example of backtracking hooding interview questions and the reason is that so we could definitely go ahead with every Sun region and traverse the metrics from rogen column going to row two column two and keep just adding them to a sum value and that could be the right answer but it would need us Oh of M into n time complexity each time some region is called right so if you proposed this solution you're definitely going to be asked to improvise it and the only way to improvise it is to build a structure which we can use an Earthman one complexity time complexity and derive a result with a very simple mat rather than going through the matrix every time some region is called right and for that we'll have to solve many subproblems right to derive the final model which will help us achieve that and that is what we use dynamic programming for so that's why I think this is a classic example in a very good way to learn dynamic programming better and it helps us develop an approach that is applied to a large variety of dynamic programming problems so the approach that we'll be taking here is we definitely creating a DP array right or a matrix which will be having one extra row and one extra column as compared to the number of columns and rows in matrix okay that's because for DP of 1 comma 1 we want to store the sum of elements in this particular region ok so we basically so imagine one extra row and extra column here so the last element will store the sum of all the elements in the array so what I mean to say is VP of M plus 1 n plus 1 where MN and our are the rows and columns in matrix right so this extra element and the extra row and column that will be adding so the last element of D P matrix would store the sum of all the elements in the matrix so if you just move upwards the matrix goes on shrinking right and we store the respective values okay so DP stores the sum of the rectangle that is being formed from that there to the start okay and to derive such a rectangle the sum of elements in such a rectangle all you have to do is that pick the value of DP of Row two plus one column two plus one and then from that subtract all the redundant parts right which are not a part of this because we have Row one column one and we have got fruit to quality so to understand this better let's use this slide yeah so this is our matrix right now we have to find this right this is what we need to find so what we need to do is that if we take the sum of all the elements in the yellow rectangle right and from it we subtract all the sum of all the elements in the blue rectangle right and then from that we also subscribed sum of all elements in the purple rectangle right so that leaves us with this right our answer the only thing here is that we subtracted this small rectangle with three and five as the elements twice because that was a part of the purple and blue rectangles boot and that is why we will add that part after subtracting it from the yellow rectangle so that we get the correct answer okay so this is what we will be doing and let's get started with the solution so this is a very easy implementation you just need to understand the underlying concept right and then it's really easy okay so we'll just declare this outside because we want to use it in both of the functions and then initialize it inside here but before that let's just do some basic checks that if matrix dot length equals to zero or we don't have our matrix of zero dot and equals to zero so in that case we just want to return because there's nothing that we can do here right so we just return ok so the number of rows in matrix that is matrix dot close matrix dot length and the number of columns is matrix of zero length right let me just close this out so um right so DP would be initialized as are the same we need one row extra and we need one column extra right and that's what we've done right now let's fill this out so we'll just do a simple matrix traversal so rows and then J equals to 0 J less than columns right and J plus okay so now as I was saying that the last element in TP right so basically DP of rows plus one coins plus one will store the sum of all the elements in the matrix right so that concept what we do is so we won't be use our pre-calculated results for be use our pre-calculated results for be use our pre-calculated results for the elements surrounding the element that we are considering right now okay so if I'm considering for example 0 I want to reuse the solution I had where I have built for three for two and four six so if I add the result for three with the result of two right I will basically be adding the result for six twice and so I'll subtract the result for six once okay so given by that what I and then I'll of course be adding the value of the matrix of I comma J so first of all let's start with that so I add this plus TP okay so now I and J plus one so it basically we are trying to cover like four zero here we are trying to cover three and two okay and similarly I plus 1 and J and then since we have included this value twice so we just say DP of I and J should be subtracted once right to get the right answer okay so this is how we just build this up and now when a some region function gets called all we have to do is just return so we'll be using our DP and since we know that we have a plus one like we have in the next four rows for metrics of rows columns right we have DP of rows one rows plus one and columns plus one which is what stores the sum of all elements till rows and columns so what we'll do is that we use that okay Colin - yeah plus one right and then as I was - yeah plus one right and then as I was - yeah plus one right and then as I was showing in the presentation that we need to subtract two rectangles right which would be so the row remains the same but the column goes for column one right so for example here the row right the room remains the same but the column is this is column one so we go here and similarly we subtract column remains the same this column remains the same but we go to this row okay which is Row one and since we have subtracted this segment twice so we find that so we just add AP of rows one column one okay sorry about Row one put in rows Row one and column you think I've written rows here as well so sorry about that okay right so um we have added that to get the right answer okay so let's see if this works mm oh okay let's try something fine so as you can see the time complexity for non matrixes of M into n right space complexity is also off M into n but the time complexity of the method which needs us to derive the sum is o of 1 because we just add and subtract a few values and get the answer so I hope you guys find this video helpful if you do please like share and subscribe keep pouring antek you guys
Range Sum Query 2D - Immutable
range-sum-query-2d-immutable
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`. * `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. You must design an algorithm where `sumRegion` works on `O(1)` time complexity. **Example 1:** **Input** \[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\] \[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\] **Output** \[null, 8, 11, 12\] **Explanation** NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `-104 <= matrix[i][j] <= 104` * `0 <= row1 <= row2 < m` * `0 <= col1 <= col2 < n` * At most `104` calls will be made to `sumRegion`.
null
Array,Design,Matrix,Prefix Sum
Medium
303,308
374
Yes, hello. I am Gary, a developer. I will not delay. The problem to be solved today is pass number 374, Haier 5 Lower. They say they are playing a choo-choo game. They say Lower. They say they are playing a choo-choo game. They say Lower. They say they are playing a choo-choo game. They say this game is as follows. I will call it i Computer. The computer picks a number from 1 to n. The input here is Annie, and we have to guess the number for Home the Goal. Every time we play, the computer tells me whether the number chosen by this rooster is higher or lower than the number we gave. In a function called 2 We can input the number we guessed and receive the returned value. It is said that it returns one value out of the world in a month - 1 is if the number we see is - 1 is if the number we see is - 1 is if the number we see is higher than the number the computer sees - higher than the number the computer sees - higher than the number the computer sees - 1 and the number we chose. If it is lower than the number chosen by the computer, it is one, and if it is the same, it is said to be 2. This can be done by solving the binary search in the same way as I posted in the last video. Well, let's solve it. The start date is one, and the end is &amp;. end is &amp;. end is &amp;. And in the sentence, start is greater than the band. If it is less than or equal to this, we will continue to do 1 and 2 statements like this. If so, we will call the number of characters function. Let's call it old and say trust the value we guessed. This time we will do it like this, just like we always play the game appending from the middle between 1 and n. If you always do this from the middle, you can focus on half. So, that's why we always use half as the guess value and then put this as an argument for this function. Then, if this is a name, then we guessed it. Then we It returns the selected number, and if the result is -. is -. is -. Then, if the result is 1, it means that what we chose is less than what the computer chose. It gives us a plus work for the selected cop. And 5. If I am again -, the I am again -, the I am again -, the same hero - work is what we same hero - work is what we same hero - work is what we choose. Because of the story that one is bigger than what the computer sees, I will reset the currently selected end value to the value minus the mid-ga wire. end value to the value minus the mid-ga wire. 4 The test has passed, and if you submit it, you will see that it has passed normally. That's all for this video. I'll see you in the next video. Thank you.
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
1,008
in this problem we have to construct a binary search tree from pre-order binary search tree from pre-order binary search tree from pre-order traversal so given a preorder traversal we have to construct a binary search tree and return its root node and how this output is printed so actually when you do the level order traversal of this tree you get this output so first we print it then we move to next level where we print 5 and 10 then we move to next level where we print 1 7 and the left children of this node is not there so we put null and then we printed 12 so this is how this output is printed so we don't have to do the level order traversal I have just explained so that you know how this output is given in this code and now let's quickly discuss what is pre-order traversal what is pre-order traversal what is pre-order traversal what is binary search tree what are its properties now suppose we have to do the preorder traversal of this binary tree so in pre-order traversal first we visit so in pre-order traversal first we visit so in pre-order traversal first we visit root node and then we visit left half of a left subtree and then we visit right subtree so let's print the value of root node then the next node as to so let's print its value then the left subtree and the right subtree so the left one is 4 and after that this node has no right and left children so we already visited 4 we already visited 2 so the next node is 5 then again this node has no left and right children so we have visited 5 we have already visited 2 and node 1 now the next node is 3 so first we visit the left subtree and in again in left subtree if we take this node so the this now the left subtree and then the right subtree so when we visited all the nodes of lifts our tree now it's time to visit the right subtree so 3 then the left which is 6 and then the right which is 7 so this is the preorder traversal of this binary tree and now let's see uh what is BST and what is binary search tree so binary search tree is a binary tree with spatial property so in binary search tree left node has value less than root node and right node has value greater than root node and now let's see this left and right children so this left children has value less than the value of the root node and the right children has value greater than the value of root node and all the values in left subtree is lesser than the value of root node and all the values in right subtree is greater than the value of this root node so this is the property of BST and now let's discuss various approaches to solve this problem so let's discuss our first approach so given a pre-order first approach so given a pre-order first approach so given a pre-order traversal and in pre-order traversal we traversal and in pre-order traversal we traversal and in pre-order traversal we first visit root node then we visit left subtree and then right subtree so what we can do is so we have to create a binary search tree from this pre-order binary search tree from this pre-order binary search tree from this pre-order traversal so we know the first element of the pre-order traversal represent the of the pre-order traversal represent the of the pre-order traversal represent the root value so what we can do is we can create route we can create a root node by using this value and then we can iterate the pre-order array from the iterate the pre-order array from the iterate the pre-order array from the first index and check where we have to place this value whether in left subtree or in right subtree so we take this value 5 and we compare with the value of root node so the D value 5 is less than this value 8 so we have to make this as left I love this node so we know the property of binary search tree where the left child value is always less than the value of its root node and the right child value is always greater than the value of root node now we move to next value which is one we compare with eight so it is less than eight we compare with five it is less than five so let's make it as left child of this node then the next value is seven so it is less than eight then we compare with five it is greater than five so let's make the make its make them as right child of this node then the next value is 10 so 10 is greater than 8 so let's make let's put them in right subtree so this node is the right child of root node and the next value is 12 so 12 is compared with it then it is compared with 10 so it is greater than 8 and 10 so 12 is the right child of this node 10 so this is the logic behind this approach so here we are taking the length of this array and if there is no element present in this array so simply return null we can't create binary search tree from MPR a then take this value present at 0th index and create a root node then traverse this array from first index till the value present at this end a then we call this method and where we pass the reference of root node and the current element so the current element is 5 and we pass the reference of root node so in this node only one element is there which is 8 then we recheck the current element value is less than the root node value if it is and if there is no left child then this will be the left children of this root node you can see this code where we compared the current value with a root node value and if it is less than the current root value so current root node value then we recursively call this method insert with left children so this will be the root node and then the current value so when it is 8 then there is no left children so it is null and the current value is 5 so when it is null we return the new node so we make this as left child of this node then we go back to this next iteration where we pick this one and we pass the reference of root node and current element which is 1 so we compare it is less than the value of root node then we recursively call then 1 is compared with this value again it is less than that and then again we pass the left child of this node and it is null so we return new node and we make them as left child one and then the next element is 7 so again the same process 7 is compared with it so it is less than 8 so we call this method and we pass its left child now it is 5 so 5 is compared with 7 so it is greater than 5 so we reach at this statement and we pass its right child and value so it's right child is null so we return this new node and 7 we put 7 here and then similarly with 8 and 12 so 8 10 is compared with a and it is greater than eight so we reach at this statement and where we pass it's right child and the current element which is ten so now right child as null so we return new node and ten is the right children of this node similarly with 12 and we make 12 as the right child of this node so this is the logic of this approach let's talk about its time complexity so it's time complexity is o and log n so now let's discuss our next approach in which we solve this problem in oh and time complexity let's see how we can optimize our previous approach so here we are going to use the property of binary search tree so where we know the left child value is always lesser than the value of root node and the right child value is always greater than the value of root node so when we have to choose the root node so it this value can be anything between the if we are taking integer value then it can be any value between integer mean and integer max so integer mean value is the minimum possible integer value and integer max is the maximum possible integer value then it's immediate left node should be any value which is greater than the integer minimum value but it should be less than this root node value which is 8 so the next when we take the next value we check this condition that it should be greater than the integer main value but it should be less than its root node value and then when we take this one so now we compare the left child of this node should be and greater than the integer mean value but it should be less than this value five and when we take this seven so I mean if seven is lies seven should be greater than its mean value and less than this value then it should be its left child but this is not the case so now this value is greater than this five but it is less than eight so it is the right child of this node when we take next value which is ten so it is less than the integer Max value but it is greater than eight so it is the right child of this root node Heat and when we take this value twelve so it is greater than the integer it is less than the integer Max value but it is greater than this node value which is ten so it is the right child of this node so using this property we can solve this problem in oh and time complexity and you can see it's code so in this code what we are doing is if the list is empty if this array is empty simply return null then we are solving this problem using recursion so where we pass this array and the integer minimum and maximum value so initially we take the integer minimum possible value and integer maximum possible value and the initial value of index is zero so we start with zero at index so now the base condition is if index is greater than equal to this array length then simply return null else we take the value present at this index which is eight and we compare whether it is lies between this mean and Max value yes so we create a new node and we increment the value of index now it points to this index and then in the left child of this node so when we create this No then we call its left child where we pass this array and mean value mean is this value integer mean value and the max value so when we create a left child it should be it will be between mean and this root note value so it should be greater than this integer a minimum value and it should be less than this root node value so then we can create them as its left child and the right node condition I mean they will write when we call this method for its right children in that case the minimum value should be this root node value and maximum value is the integer max value and first this method is called until it satisfies this condition that this five is less than this root node value but it is greater than integer mean value so this condition is satisfied in next recall again we pick this value and we check with this condition so again it satisfies then we take this value seven but so this time this condition is not satisfied then we run this condition at run this statement I mean we reach at this statement and we created right child then we move to ten and then we move to twelve so use so in this way we can optimize our previous approach and now let's talk about its time complexity so its time complexity is o n so in this tutorial I have discussed two approaches to solve this problem and if you know any other approach you can let us know through your comments so that the people who are watching this tutorial get the benefit from the approach you mention in the comment section so that's it for this video tutorial for more such programming videos you can subscribe a YouTube channel you can visit our website which is HTTP colon slash you every I'd come thanks for watching this video and please don't forget to like this video
Construct Binary Search Tree from Preorder Traversal
binary-tree-cameras
Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_. It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases. A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`. A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`. **Example 1:** **Input:** preorder = \[8,5,1,7,10,12\] **Output:** \[8,5,10,1,7,null,12\] **Example 2:** **Input:** preorder = \[1,3\] **Output:** \[1,null,3\] **Constraints:** * `1 <= preorder.length <= 100` * `1 <= preorder[i] <= 1000` * All the values of `preorder` are **unique**.
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
1021
213
we are given an array of integers representing the amount of money present in the house and these houses are arranged in a circle we need to rob the maximum amount of money from these houses such that we do not drop from two adjacent houses this problem is lot similar to the previous problem so it would be better if you watch this previous video for a better understanding here since the houses are in a circular order we must be concerned about the first and last houses if we are robbing the first house then we should not be robbing the last house because they both are adjacent houses likewise if we are robbing the last house then we should not be robbing the first house for the same reason that they both are adjacent houses in both these scenarios since we are breaking the circular chain we can represent these houses in a linear order therefore in one scenario we will be omitting the first house and robbing the maximum amount of money we can and in the other scenario we will be omitting the last house and robbing the maximum amount of money we can and from these two we will be choosing the one that gives us the maximum amount of money for robbing the houses in the previous video we have seen that if there is only one house we can drop whatever amount of money is present in that house if there are two houses then we will be choosing the house with the maximum amount of money and if there are three or more houses then we need to look at the previous two houses to decide whether we need to rob the first and third house combined or just the second house alone so now let's cut the solution if number of houses are less than or equal to 2 then we know that we can only Rob the house with maximum amount of money so we will return the maximum for robbing the houses using dynamic programming we will write a separate function we will store the number of elements in this variable if there is only one element in the array we can directly return that without doing anything we will create a new array of same size initially filled with zeros if there is only one house we will be robbing that house if there are two houses we will be robbing the maximum among the two for robbing three or more houses we will be using a for Loop at the third house or the current house we will be robbing the maximum of first and third houses combined or the second house alone and we will be returning the maximum amount of money we could Rob till the last house now we will be calling this function on two scenarios one in which we omit the first house and the other one in which we omit the last house finally we will be returning the maximum among the two scenarios let's try running the program it's working see you in the next video
House Robber II
house-robber-ii
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[2,3,2\] **Output:** 3 **Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. **Example 2:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 3 **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
Array,Dynamic Programming
Medium
198,256,276,337,600,656
563
Jhal Hello Hi Guys Welcome To Co Dear Students Question In The Street In This Question Root Of Ministry And At Least Ones Every Tree Not To Notice The Difference Between All Subscribe 12345 Left Side Factory Values ​​Is 30 Minutes Not The Dirty Factory Values ​​Is 30 Minutes Not The Dirty Factory Values ​​Is 30 Minutes Not The Dirty Channel Subscribe Notes 999 David Subscribe To A Tree It Doesn't Have Left Side Dard Ki Samadhi Left Update Nodal 200 Vacancy Date End Tagged As Defined Such Samadhi Episode Difference Of The Sum Of Subscribe To A Car To Fit Into It's Two Is Not Loose Subscribe Difference Of Two To 9 0 2030 - 01 2012 subscribe To My heart to subscribe our Channel and subscribe the world will be lit Sleep Mod All Wishes Do Not Tell Off To Say Not Difficult To Subscribe School - 93005 Not Difficult To Subscribe School - 93005 Not Difficult To Subscribe School - 93005 20300 subscribe and subscribe the Video then subscribe to subscribe our That Nowhere To Return Country December Distribution With Six Plus Two Plus 7 Exactly 215 19.50 Question and Example Exactly 215 19.50 Question and Example Exactly 215 19.50 Question and Example Knowledge and Subscribe 0 E Will Contain The Total Seats Of Every Not Know What Will U Will Write If Function Is Per Function Was Written Test Will B C Introduce Point X is an equal to helper will take root in this and will pass Aminent Person Will contain the action will contain annely addressed It's Value Evere Notes Value and in Return for Fashion Sudhir and Note 4 Route 4 route Relation Subscribe 280 From A That Nau Will Take A Very Much San Ki Vivek Aur Jab Assam Left And Samrat Restore The Value Of Left Thumb And Chamar Will Show The Value Of Life Itself Will Call Per Function A Helper Will Be Root Left To My Son Ki Country Vitamin E Some Of Village Street Similarly In Its News Til Store The Time Of Life In A The Root Right And Will Pass A Similar 100 Point What Do You Vinod Porn Content The Now Related Addressed Notes Value Every Note Salute Will Encounter This Some Should Give me sum plus to Lotus Valley of - subscribe and tell me everything is fine pieces simply return sum plus news plus seat current routes value is arranged 182 behind the best time velvet se 0258 subscribe thank you a computer is total left his words in total left visam sudhir will return tamil hits tamil plus news plus roots android 2.2 dispur sudhir will contain android 2.2 dispur sudhir will contain android 2.2 dispur sudhir will contain subscribe and subscribe the knowledge on now half syndicate knowledge submit a bluetooth settings update biogas cardamom video thank you to
Binary Tree Tilt
binary-tree-tilt
Given the `root` of a binary tree, return _the sum of every tree node's **tilt**._ The **tilt** of a tree node is the **absolute difference** between the sum of all left subtree node **values** and all right subtree node **values**. If a node does not have a left child, then the sum of the left subtree node **values** is treated as `0`. The rule is similar if the node does not have a right child. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 1 **Explanation:** Tilt of node 2 : |0-0| = 0 (no children) Tilt of node 3 : |0-0| = 0 (no children) Tilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3) Sum of every tilt : 0 + 0 + 1 = 1 **Example 2:** **Input:** root = \[4,2,9,3,5,null,7\] **Output:** 15 **Explanation:** Tilt of node 3 : |0-0| = 0 (no children) Tilt of node 5 : |0-0| = 0 (no children) Tilt of node 7 : |0-0| = 0 (no children) Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5) Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7) Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16) Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15 **Example 3:** **Input:** root = \[21,7,14,1,1,2,2,3,3\] **Output:** 9 **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-1000 <= Node.val <= 1000`
Don't think too much, this is an easy problem. Take some small tree as an example. Can a parent node use the values of its child nodes? How will you implement it? May be recursion and tree traversal can help you in implementing. What about postorder traversal, using values of left and right childs?
Tree,Depth-First Search,Binary Tree
Easy
1609
59
Hello everyone welcome to my channel court sorry with mike so today you have 59 but it is not medium at which rape is quite an edgy question if you have watched my video of spiral matrix one, you have to copy paste the code from it, you have to do a little notification, this question The solution is ok, that's why watch the video of Spiral Video Part One. Okay, I have also given the link in the description. Check it out from there and click on it. Okay, yesterday in Late Code, Part One of Challenge Matrix was also asked, so the name of this question is See Spiral Matrix Part 2, my liquid number is 54, OK IT bill, have other companies, I have written the name of only three companies, Microsoft, Amazon Pay Paper and many more companies, those who have been asked will be found there, all the company taxes will be written above the question itself. Okay, so the question this time is a little bit, just know what is different that this time I have given you the value and have told you to make it yourself okay and input the numbers in it in the order of spiral, okay and from number one to where to go. If we want up to n², then it is okay, then it should go from one to nine, then how come, one, three, go in this order, four, five, go in this order, 6, 7, go in this order, nine, go in this order. It has to be printed in spiral form, this is very small, 2dr is big, you are Dear, I will go even longer. Okay, so the question is quite simple isn't it and look at its output, it must be clear to you, the output is this, isn't it? So see, I have also told the direction in which direction the numbers are printed, starting from one. You are in a square, ok, the question is very simple, you must have understood it, and I found the solution and it is exactly like this because look what was there, a fool had already given it there, you just have to print it, friends, what is there? Brother, 2dr one is empty, you just have to file the number, at least this much was learned from the video of Spine Matrix One, how to walk in the anklet form, you only got one, is it in the form of spiral, right? You had already learned about travels in the spiral lesson, all you have to do this time is that this time you should not give numbers to it is empty, it is broken, right, you will become a quality variable, it is okay to keep its starting value as one. You will move forward in the lesson, you will travel, keep printing the number, put the number one here, then keep doing the number plus, it is okay, then if you add the number plus, then you put the number here, then make the number bigger, add the number 3 by plus, then four will become five. If you go then this question is very simple. You already know how to write traversal in spiral text. From my previous video of Matrix One, you already know how to move in spiral form. All you have to do is, this time keep a variable and keep its starting value one. And here keep entering the value of this variable one two three four five six seven. Okay, so let's see now. Remember I am repeating please. Watch the video of Parallel Matrix One, I have explained it very well in that. This is how we travel in spiral form, okay, so here if I tell you again, then give me a small request, but you watch that video, okay, here you will remember that first of all you will have to friend him, okay If it is then remember what is fixed in it. What is fixed in it? Top fixed pen, what is changing? First the pen is this, then this is this, then what is it? Is the pen going from left to right? So the pen is going from left to right. Let's take I Maa and where will I go from where will I start from left I &lt;= will go till right Okay, so what will happen in making this, &lt;= will go till right Okay, so what will happen in making this, &lt;= will go till right Okay, so what will happen in making this, we will go in this thing, if this thing is going on, then if this thing is going on, we if this thing is going on Okay, so if you input the number here, what will happen? What will be the number here? 123 Okay, now when I told you that this science, this row has been printed. And what was the constant, top was concentrated so it has to be sent down so I sent it down top plus so top came here okay now what do you have to print brother this is this now you have to go to this lesson okay this lesson What is the constant for me to know, right, this pen is constant, is n't it, and it will move very well, right, and if it moves from where to where, then will the doctor move from you, and what else, see, I had also moved my top, a top here. If DR moves, what will be printed, one this and one this, okay, that's why I am saying, look at my Spiral Me Part One, driving very well, I have shown the whole thing, okay, and its movement in a big matrix. I will also show how it will happen which I have shown in the experiment but here also you see, there is no problem, you know that while printing like this, it will go here, okay, let's see that too, okay. Maa take a very big ray, look at it, first it would have been fixed, we will keep the top here, we will keep dr here, left here, right here. Okay, so this will be printed of mine, so now we will shift the top down, top plus row. If there is no less in the future, then the top will come here. Okay, now mother, I have to print this. What is the constant in this? Look, the pen is constant, right? What else is changing? It is changing every day, so where is the value of the row from? How far will this go, you have to print this and this, then from where to where is it going, from top to bottom, okay, and the pen is your constant, right, so when this will be printed, mother, take your print. If it happened, then it was constant, now it has reduced, now this pen will not come down again in the future, so now I will shift the pen, move it from here and go to the right here is right, it will start pointing to it, similarly, now you have come. Here now you have to print this, see what is the constant in it, Ra is constant, the pen is changing from right to left, it is fine and the row is constant, so whatever is constant because it was constant and its less. If it is over, then Dr's [ __ ] is over, now Dr will have to be Dr's [ __ ] is over, now Dr will have to be Dr's [ __ ] is over, now Dr will have to be shifted up because this row has been printed, now Dr who is sorry, now Dr who is will point to this, okay this is also printed, now let's come here. But okay, so see what is the constant in this, on the left, this pen is constant, and from where to where is the row going, from Dr to top, my row is going from here to here, what is the butt constant, on the left, so when this row is printed. If you go to know what was the constant, if the pen was constant, then you will shift the pen and this is logical, you think where will you shift the pen, you will shift it from here to left, that is why you will logically understand yourself why I shifted the pen from left to right side. Let me tell you, first of all this direction will be this is the second direction, this is the third direction, this is the fourth direction, after that it has to be repeated, so my direction is yours, this is the six, okay, so mother, let's take this direction now. We give a name to each direction. Direction, if it is zero means we are printing this one from left to right. Direction is fine. If it is tu then we are printing this, ok these are the two. After this, when you go ahead, then Back here, this will go to left, you will go to right, and what is left right? Direction is zero, then here you will go to top, then bottom, this direction will be my zero, then one became one, you became three, then zero became because then this has to be printed. One then tu again three hua dot will continue like this, okay, so what does it mean that first I will print one thing in the direction, mother, after I have printed this, I will make the direction plus, okay 3. If the direction is greater than , then I will return it to zero okay 3. If the direction is greater than , then I will return it to zero okay 3. If the direction is greater than , then I will return it to zero because this is what you have to do. Right, if the direction is zero, then you will print from left to right. If the direction is one, then from top to bottom, the direction is you. If the direction from right to left is three, then from bottom to top is fine and shift to which. To do that, I told you here that the thing is constant, like mother, take it is printing, now it is printing, so what was the constant in it, or was it a constant, then the part of the thing that was constant has finished, it has been printed. Shift it down, okay, then similarly, you are seeing here, there was a pen here, so this pen ran out, so what did we do, okay, then we shifted it right, similarly, when it was printed. So we had shifted the DR up, okay so the logic is quite simple isn't it because you had learned how to travel from Spiral Matrix One, so now you will just copy and paste the code from code to code, just this time. What we will do is keep a counter or a variable named name, it will start from the starting one and it will keep increasing as we file each cell, right 1 2 3 4 5 6 and so on, okay, so that's it. Now I am just going to copy and paste the code of spiral one in front of you, okay and I will modify it a little by adding counter variable and your question will be solved, hence the solution of spiral matrix one and spiral matrix two is absolutely correct. That's it because you have solved this also with your already solved question, so let's see in the liquid, let's code from the beginning and see after submitting. Okay, so let's code this and exactly what I said, only the code for spiral matrix. Will paste it and solve it by doing this modification, then go to my anti video self repo, here you go to arrange, go to tutiya ray in arrange, go to 2d, you will get spiral matrix, okay, you also have the code in spiral matrix. I am fine, look, I am going to copy and paste it in the code, I have picked it all up from here, okay, I have picked it all up from here, and now I just copy and paste it here, okay, I have copied and pasted it here, but now look, something. Let's change here this time more is given, okay so I write here that if N is zero then my answer will be black, isn't it and if M was there then matrix dot size then what is M this time, that is also equal to M. No, what will we do this time vector off and immortal from pen is equal to ok top Dr left right is the code no change id tell me then which is the direction idea if it is zero then left you are right one then top you Dr tu hai to right tu left three yato dr tu top, all this is absolutely true, this condition is also absolutely true isn't it, as long as top is less than or equal to dr and left is left to right, then it will work if ID is zero then addition is zero. If you want to print left then right then remember the result dot push back matrix top i used to do so this time nothing has to be done what do we have to print in the matrix top of i remember what I told you either a name or a variable named counter So, it will start from one, what do we have to do, just print the counter, add it to the top eye, okay, remove this and first print the matrix. Part one in sparrow matrix. If we have to file here, then what is there in the matrix topper? I have added the counter and made it a counter plus and I will remove it. Parliament, this is true also, the question is mine. Look, it has been solved. Similarly, here in the matrix I am right, what should I do, I will make it plus and remove it. It is okay here too, matrix Dr. I = counter is okay here too, matrix Dr. I = counter is okay here too, matrix Dr. I = counter plus, I will make it plus and remove it, I will put the value in the left, I will make counter plus, okay, it is clear till now, everything else is well known to you, meaning it is made without looking, it is okay, it used to be bigger, we will make it zero again. It's okay to give I's equal to zero, it's okay to do ID plus 4, so what is it, can it be zero, can it be one, can it be three, can it, that's it, is n't it a little smart way and If you don't see anything then we pasted the code and just entered the value in the counter because we know how to travel. In the right spiral lesson, we know how to walk, so we kept walking and printed the value of the counter. So Let's See You Able To Pass Which Date Cases Using D Se Code Of Spiral Matrix Okay Spelling No Let's See If You Understand One Thing Well Then Later On It Will Come To You Like I Am Going To Walk You On Spiral Lesson Then Your One bana liya tu bhi bana liya hai solve this question they have passed which date in cases there is no doubt comment area video thank you
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
1,238
so today we would be solving lead code question number one two three eight and that is circular permutation in binary representation so what the question says is that you need to put in uh numbers from zero up till two s to the power n minus 1 and N would be given to us in an array such that the first number start that is given to you should always be in the 0th position uh rest all the numbers be at I and P at I plus 1 should differ only by one bit in their binary representation and at last P at 0 and P at 2 raised to the power n minus 1 must also differ only by one bit in their binary representation so let us go on solving this question uh and the numbers mustn't repeat okay so they should be distinct permutation means that the number should be always distinct all the numbers should be resting so uh if that is the case the number should be resting so we need something to get a check for so I would be creating a set okay set of integers SG I would be creating a vector that would be returning that we would be returning at the end Vector end rest okay and after this uh we would be calling our answer function um answer and uh I would be passing in my start or I think I should start with I will be passing in my address I will be passing in my St I would be passing in my n and I would be passing in my start yeah that is it and after all this I would be returning my um address okay that is it let us move on to our answer function so what answer and what are we passing in we are passing in vector of end Ampersand s and after this set of int St and uh integer n and uh integer start okay that is it um base case uh I know that uh these three lines make sense so I think creating base case at our very start uh would be fine so if at any moment my um rest dot size goes equals to power of 2 raised to the power n but any moment this happens then what you need to do is that let us now check for my first and last element so end X is equals to um uh yeah okay so before this uh as we said that we had our conditions that start should always exist so we need to push uh rest dot push back start at the very start and also if start is there so SD Dot insert start yeah just to make sure everything goes right so uh if end s x is equal to start uh xor what is at the back of our rest so rest dot back let us take their zor now after taking the Arizona if that is if that differs by one so how to check if that differs by one so return a True Value if and only if x and x minus 1 okay x and x minus 1 goes equals to zero um if there is a need of explaining this so I'll be explaining it at the last of the radio uh this line so yeah if there is a need if I feel that there is a need else I think we should all search for this line why is that even true uh if we all differ by one then zor would always give me uh a power of 2 okay if two numbers differ only by one bit so Zorb would only give me a power of two okay Power of 2 would exist in an integer number and a power of 2 minus one is and together then we will always get a zero just remember this life yeah after this uh I'll be pushing in uh my uh res Dot push or no I think I should get the last element if I get the last element out yeah so um okay and now let us move on to the follow for end I is equal to zero up till I is less than 16 and I have plus and we need to iterate and last okay so I need to um I need to create a last variable that would be uh that would be getting it last is equals to um whatever was last input or inserted in my uh Vector so res dot back yeah that is it and enter and current is equals to um last xor um one um and a left shift by I positions if my current or yeah we will be getting a number so now I need to check for that number if that exists previously or not and also if my current is less than um power of 2 comma n minus 1 and my uh current exists or does not exist previously so if St Dot find Uh current is equals to St Dot and in that case only I will be inserting it so St dot insert Uh current okay and uh rest dot push back current and uh if after all this I'll be passing or I'll be backtracking and if answer for these for this current also returns me true so if answer res comma St comma n comma start also returns me true if it returns meter uh I have answer then I'll be returning a two yeah and that is fine and uh after all this I'll be St dot erase my current and rest dot pop back my whatever might be the last value after all this if nothing happens so return the false yeah that is it I think that is good to go few errors might be there so um let us see if x and x minus 1 yeah and operator okay St dot insert yeah that should be SD not set yeah that is it and I think that is good to go okay error wire expected to six so are we not inserting it um if current is less than or equal to yeah sorry this is not equal to then also sorry my bad and that should be accepted yeah that is accepted that took us 0 milliseconds and if I just submit it uh that would be accepted hope so why are we getting a tle the I is equal to zero current is less than n is equals to 11. for n is equal to 11 if for current is the less than equal to 2 raised to the power n then this is right then that means that's not founded St dot insert current uh okay and then uh pushback yeah if answer returns true then you also return a true that is also fine um XT dot it is current and that's the best DOT pop back that is it and else return of false things are sorted but the Y is it so is it showing is it just because of this is it because it's creating copies okay yeah so sorry uh that was creating copies for our set so we need not create copies we'll be directly accessing the memory location offset and that is it uh that was all for the video I hope you liked it if you have any doubts please do comment down in the comment section and we'll be meeting in the next video uh till 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
499
hey everybody this is Larry this is December 11th uh where I will do an extra bonus uh problem that I haven't done before I'm gonna do it is Sunday and I am doing a little bit earlier in the day so I'm going to try to do a hard one and get it out of the way let's do a random okay so today's problem is 4.99 the maze free it today's problem is 4.99 the maze free it today's problem is 4.99 the maze free it is a premium problem so if you don't have premium my apologies but hopefully you know you can read the screen and then we'll do it together or something like this okay so there's a boy and a maze of empty spaces and was okay so okay uh empty space is a zero once and then you can go up down left right hit the ball and the ball stops you can choose the next dial okay so we can go through empty spaces by going right or up down left right but cannot stop and so it can and only go to a stop and then it moves okay uh there's also a hole in this Maze and you're trying to drop into the hole okay why would why do you have a soccer and a okay so given in this maze that's yeah given this maze Deborah the boys possession and the boys Precision home we turn a string of all the instruction that the boy should file with the shortest distance possible and you have to do a lexicographically minimum one okay so I mean this is a book it's not quite impossible okay the distance is the number of empty spaces traveled by the ball from the start position to the destination okay so I mean this is going to be dystra just because um yeah I mean you could do it two ways I don't know which one of my head I mean we might have to look at the constraints a little bit um but you can do it this is clearly a shortest path problem you could do it with die straight you could probably do with breakfast search them complexity is a little bit unclear without looking I mean at least I know the complexity but it may just be too slow so we'll have to take a look at it and then the other part of this is that it is the shortest path but with the path reconstruction especially um caring about the lexicographically minimum one which is actually a little bit tricky because usually the path reconstruction um I had to think about this a little bit because usually with path reconstruction you the easy way is to go backwards but in this case you might have to go forward and then do a simulation uh but um I think the concept of this poem is not super hard but it is one of those problems that is going to be implementation heavy and this is just from experience where there may be quite a few edge cases that we have to take care of so um so yeah let's I don't think there's anything that tricky so let's kind of jump straight into it let me look at constraints real quick all the times R and C is equals to 100 um that means that and if they're always a okay so RNC is equal to 100 so that's ten thousand that means that if so you cannot do breakfast search then um because in fee you can visit all the states I mean you could I mean the worst case is like a snake like type thing um but that's still a lot of state to do I think even though it would be so the advantage is that it's easier to implement and the proof is a little bit easier but yeah okay the maze will contain at least two empty spaces okay I don't okay yeah I mean this is just really annoying to do but let's start um yeah okay so now for x and Ranger four Y and major C we basically want to do start let's start Y and X and Y is equal to uh negative one we might go this way but and then here if Maze of X Y is equal to oh they give you the four whoops so I get I didn't have to look for the ball for some reason I thought I might have to look for the ball so okay so start it goes to Bar EX UI is equal to home okay and these are zero index just double checking okay good okay so then this is just dystra so let's set up a heap yeah this is just gonna be annoying it's not that bad though um and then let's have an enqueue function um trying to think about what's the best way to represent an edge is it simulation might be okay meaning that let's say we have a ball here right and we have this map if we wanna so the way to do it so with breakfast search you could just go like you know up and left or right or whatever but with dice joint what you want to do is stimulate going from here all the way to the top and I'll take you know but then now you're just doing a folder with five elements right and the problem with that is that you do get repeats maybe if other stops are um the modeling is a little bit tricky hmm can I do brief breakfast search what I mean if it's fully empty then you get in 200 or maybe even two because you have to count to space wait is it let me double check shortest distance possible what is distance there's a number of empty spaces okay yeah um because it's not the number of directions it's the number of empty spaces right so that's the kind of a tricky part as well it's left up left foreign this is so annoying to do actually I mean no that part is fine but I just have to figure out if the simulation is okay I guess we'll see I mean at first of all we'll just have to um at first we'll just have to um optimize this but yeah foreign that's pretty much it really um and then I want to do a distance right I'm a little bit lazy I need to okay that's a bad habit I think but anyway um okay so then yeah when Q Where The Boys uh sxsy and then now you know this is just regular diastrous stuff texture I always want to dice through it but sometimes feel correct me I never know anymore okay and then of course we need directions yeah okay um and then now basically for each of those directions we go NX and Y is equal to x y um okay while plus DX is NX basically we just keep on moving if we can and then now that it goes out bounds in the next time um oh and we have to check that um is you go to zero for spaces but okay and then now Alex and Y is in a good place so then what are we doing sorry I got a little distracted yeah so then now we're sorry friends yeah now we just put it in right so uh we should probably um so we assume that the space that we're currently at is whatever but yeah so then now count is zero let's just go to count as a matter and then we move one step one empty step and I have to double check that this is okay versus like an off by one but that's fine um and then now we unqueue it now to set this to zero okay and x and y and D plus count uh but only if we have if we want to maybe we could put in the function okay so maybe we just call it maybe B and Q right and then here we can put the if statements here so that if x y naught um is in distance so it's here and the distance is already um smaller than D then we return right otherwise if it's not in there then we do it and then yeah I think this is okay and we assume that this is already in bounce and stop due to this WOW statement um and of course with the camera if N X and Y is just equal to X Y then this would already have a distance anyway so um oh and this is actually if it's equal to we also don't want to enqueue it so okay um okay so we return impossible otherwise um yeah we might we have to do some other work first but I want to at least get to a place where um I just want to take a look to see if foreign typing I just want to at least take a look to see if this is at least on right well we have to debug it then you know we have to debug it first oh whoops let's see it was just like writing more code and then debugging um can I not set this up that's weird I didn't even declare everything but it gave a different one a thing instead okay so is that putting it possible we knew that but that means that we didn't get oh well yeah of course because it's impossible so that's accurate um wait is it did I miss wet that one let's see no this is not impossible so oh wait no I mean it's fine let's just return 10. so that we know for more queer so okay so it's still giving me impossible for some reason foreign distance of X Y is greater than D we continue so we don't process the same node more than once every and Q more than once okay but hmm that's weird but uh let's see let's print it out okay so it is doing something so it starts at where do we start at 43 and then we go to four is One Direction zero three is One Direction fourth two is One Direction um you can't see me but I'm just wait I'll divorce the grid here is because the borders of The Mazes are all worse um so it's not a grid okay so four three is actually here okay four oh three four two um O2 or not o1 oh wait because it would drop through the whole unit doesn't stop at the hole I see okay I have to add a thing for it that's fine uh let's actually see a lot of edge cases I didn't even know about but uh and um we have to add something to here but I think that's fine I also should have printed not here but I should have also printed the distance but I think that's fine I think that part is not that bad so okay so basically here we wanted to stop if uh NX and Y is equal to ex UI right so if it looks and why uh ex and animate series UI then we want to break so we want not of this right is that right so this is where we want to break we want the Knight of this which is you know modus total or whatever um okay so something like that maybe am I printing okay so now I'm printing stuff I'm printing the answer six uh which is that right so one two three four five six so that seems right uh what is case three case do we have a diagram okay no just this one uh I don't know the answer for that one but foreign I'm lazy okay I mean this is not that bad I just I'm looking to see if I could figure this out I'm lazy so okay so yeah I mean it works for case one and maybe case two so okay so that means that we're on a good track so now we have to do the path reconstruction which is kind of hard to do lexicographically to be honest or at least like not the usual way that I would do it so the usual way that I don't do it is doing it backwards but backwards you can really do lexicographically minimum easily but this one with the shortest path you just have to give a little bit of Dot and the way to do it is just greedy right um reflectographically minimum um you just have to do the one that gives you the first thing so let me rewrite this a little bit beam because basically we want to sort by how do we want to start by D d o r u right so down which one is down the Y left is um negative one on the x is that true they don't uh so four degrees four down okay so X is the negative First component so that means down is actually uh one zero left is this way and then white is this way and then up is this way right I think right and then we can maybe do it like you know uh or dlru right here it's just recreating the steps basically um so okay so if this is not in this then we return impossible otherwise then we just start from SX X Y is equal to x g y or start X star y oops and then here we just basically track which way is it to go optimally right so um so yeah let's just say d is equal to uh distance of e x e y and then foreign yeah basically maybe it will just do a voucher um we do a path I put a while so that I could do random with statements to break out with um but we'll see any more spaces I could so then now we go up down left right so for um I don't know I also want to do directions so that's why I do it this way um and this part maybe we can make it copy here um let me see if I can Okay so I just say get and I don't know right um for x y d x d y right so then now we can do something like um yeah right and then we return NX and Y and count and how many space that should be okay and then now we can just do Annex and Y is equal to get an um x y d x d y and also I forget the cap and then that's pretty much it um but before that let's uh let's confirm that this is still working ish right okay so it's working as before I think so this is good um yeah um okay so then how do I call it wait oh yeah okay so basically now we can do something like okay so here right and yeah maybe current is equal to zero as well foreign basically the idea is that we just have to check right um if the distance of NX and Y so now we have so basically you're just kind of so NX and Y is the middle point right so if the count plus this so current plus count is equal to distance of a d the last answer then we break but we keep the index right so the good index Maybe um G index is equal to index and then we break and then path dot a pen oh we have to do some other stuff too but let's have a plan I forget dos dot underscore order complete is always order completely except for when I wanted to I don't know if I turned it off though so maybe it did finally get turned off um we want to assert G index is not equal to negative one and also then now we want to update X Y is equal to n x n y um and also current because we move forward diminished steps right okay and then at the end we just return to do we joined the past together um don't know if this is quite right but yeah oh I forgot to enumerate okay that's unfortunate maybe um cone is zero campus did I mess up huh let's print this out just to see where I'm doing well there should be two things really okay so this is working on the first one um let's point it out then okay so x y and maybe right foreign how did that happen so it looks at all four directions right so D is sex distance of any oh I did it the other way huh because this is the distance from the beginning not from the end so I messed up in what I represent thank you I don't know that I can backtrack the other way but okay so I did mess that up let me think what I can huh hmm I messed that up actually a little bit this is the distance from the starting point not the end point that's why for some reason in my head I got that's just the distance to the end point um and the problem about this part or the tricky part about this problem is that is not symmetric right it's asymmetric meaning that you can't go backwards the same way because well you just can't because it hit your head was and stuff like this so I have to think about how to um no hmm oops can I do that in a good way also trying to make sure that I don't you know do some exponential backs and of course like there is there are ways where you can draw the back edges from here and then you know we do it the other way but that's just messy let me think if I can think about it everywhere so this is the distance from the end okay occur right but that's the distance from the beginning to that point sure so that means that discount will always be equal to this which is not useful um foreign reconstruction the other direction but the uh Alexa graphically minimum is kind of messing me up a little bit to be honest how would I do that then without like release I mean I know some ways of doing it but I'm trying to think about a way that isn't really annoying um so let's say we have the previous then what because you also don't want to update all possible cases to reconstruct it because that could be exponential or some something like this maybe I mean I guess you could draw the because then you could create a second or like you know there's an implicit second graph on the back edges and then you have to do another uh Traverso or whatever yeah and wow and that's just I mean I could do it just try to think about ways to not do it uh okay let me think I feel like we made good progress now this is from the start so we want to go okay yeah maybe that is the way to do it yeah okay fine okay fly I mean I guess it is what it is this is really annoying uh okay um x y no not in the previous X and previous y whoops just annoying XY okay fine try the wise previous of X Y is equal to just okay and basically this will just allow us to kind of do backwards with the path construction um yeah so I mean it'll fail but I just want to see okay so we four three is to oh I guess that's fine but why is this it have itself oh because it went down Maybe oh because of this yeah okay I mean maybe that's a special but then now you have like these weirdness also is what for two so one two three four two uh it shouldn't have itself right uh let me just add that here I mean you could we could have done dealt with it's just that's way more annoying okay so now I guess we're good with the previous uh and then especially you know even with the multiple ones this is really annoying as I kind of expected but I didn't think it'd be this annoying um okay so then now we start X Y is equal to e x e y and then we can just go backwards right so then now we have a Q I guess I can't usually you don't need a q but because there's multiple paths we need a queue almost like a breakfast search oh so yeah so now we want to basically have a second distance that's distance from the end yeah whatever just call it just in two because I'm lazy and then basically Justin two um I don't need to do it this way uh okay fine let's do another maybe and Q2 of X Y which is if x y and distant two then we return otherwise distance two x y is equal to D I forgot the D is and then uh what did I say and this is just my first search so yeah so we may be in Q2 of EX UI and zero and then now we're going backwards on the previous graph right so while length of Q is greater than zero x y d is equal to Q top left um and then now basically we just go through the previous so previous of X Y right so four and x and y in this thing uh do I need to oh yeah okay so then now we may be in queue two um NX and Y and then what's the D oh D plus one because we're doing a first search and that should be good except for when it gets to negative one but I think we can just ignore it maybe um okay right so then now we can um just do I need to wait what am I doing with the T so now we're counting the things from the frame but I don't think that the D matters we're just trying to look for it we need to count what am I doing Larry what are you doing I think we need yeah we just what am I doing oh geez um okay so we do uh I don't know I think I was thinking of something else because I was trying to optimize the number of steps but yeah I actually don't even need the D at all to be honest well we need a deep in our destiny um so we could do x y and then just D and then maybe Q uh from previous thing so then previous X previous Y and then node D what we actually want is the distance from yeah and we could figure this out right so it's to go so it goes because we reworded it a couple of times so I'm just a little bit lazy so we're just going to do this and then yeah so this is d yeah okay and then now let's point out this two and I think what we have to do is just change this to this two because that's what my original intent anyway is but let's print it out real quick uh it's missing this okay fine um I uh uh I'm going to see xcy because that's where um the zero distances but uh the negative one is the previous one okay fine we have to you know if Annex is equal to negative one continue something like this yeah is it in why would I infinitely Loop this foreign oh no I'm just putting too much but it's from the negative the infinite Loop though so that's a little bit weird did I miss something here actually this is should be a two so maybe that's the issue yeah that's good I mean maybe at least we got past this stuff and oh I fixed this but not Dad whoops uh okay it might still get the key area but what we want is that means that there's no path to it so then um it means if N X and Y not and just two continue because that means that path is not going to the shortest path but that's not that's upsetting but I might have gotten this part wrong so let's see distance of two oh yeah so this is these are negative so I'm kind of messed up on the direction I forgot I guess but that's uh that's why I have a print statement there okay so this is a little bit better but still not right um okay so let's go back so zero let's look at C you know this is right so zero one is zero uh zero three is two zero two is one oh yeah so two is one four three is four two is four wait what now for three this distance is wrong isn't it now it's well it's two plus four so this is it has to be uh okay so I do need to D in here somewhere okay fine because it just takes the distance but not the total distance so then I can do this um the way that I mess I there's a lot of coding on this one so I'm messing stuff up but it's okay we're making progress sometimes it is slower uh let's see how we're gonna fix it this time now foreign okay so I guess yeah let's just go back to doing it here and having just put the D we do and there's a zero um we get the D in here if this is on a thing then we have D plus um what is this thing okay so D plus this thing so I think that's fine except for previous is now X Y and this is the new one oops I run it again real quick hope uh the debugging kind of makes sense okay well this is now printing some weird stuff so uh I would run NX and Y that's why hopefully you're seeing Larry debug in real time and hopefully that's kind of useful but maybe not okay so 43 is six so I think now we're in a good place but now we're trying to see what's going on so it goes from for three to four three there's a comparison no good for three super sex should be good oh D is zero why is d0 oh no did I reuse d by accident that happens a lot shadowing okay so that's good so D is the distance oh no oh I confused it so what I want is this and then because that's the distance that's the longest distance and then this is it and then hopefully that's good looks like it's going to an infinite Loop somehow because I have a while true and we don't have a n so when do we end we didn't even consider that so yeah if X is equal to negative one we break because I think one of the previous is negative one Maybe not maybe just uh SX and Y is equal to s y then we break up but we have to append the path first I think so I think that's why because I think we actually filled out the negative one from here I'm waiting for it to finish so I could you know this is a really tough problem uh to get it right precisely and we haven't even yeah I know that it's and we haven't even gotten you know deaf to submit yet to just be on examples but it should this shouldn't be that long though so if I'm running an infinite Loop that means that there's another issue um I just thought uh oh whoops it should be gxgy because we're now going back again I was thinking about going forward and then back and then you know all these things um probably there's still some issue is not moving because it things going down you know by basically not moving it's saying uh and the reason why this doesn't terminate is because we filter that out here um and we didn't filter out here so basically yeah if X is equal to X and Y is equal to NY we continue okay so like I said a lot of match cases a lot of weirdness um honestly might not even be 100 done yet but let's give it some mint oh it is nice slowly got a lot of people but um I do wonder if there's a cleaner way to do the lexicographically minimum point because I did it in a way and I knew how to do it this way but I don't know it doesn't use you uh so I'm going to take a look at see if there's a is it just PFS I couldn't prove that the BFS is fast enough to be honest I don't know if this is like a python thing I think the bam I knew how to do it this way but I would hmm I couldn't proved up about tight enough because you could keep on I don't know but and then on that way you can maybe I don't know to be honest I don't know uh but anyway that's all I have with this one this is dystra I mean I use dystrom so this is a very dice tree uh complexity so yeah um which means that is you know OMG like e which is you know um yeah so oh really which I mean we is the same as you in this case anyway right because there's only four edges and most for each week um and in this case so log B is the same as log e kind of so yeah um and linear space we have just like a lot of linear space things so yeah let me know what you think let me show you the top let me scroll down a little bit and let me scroll you to the bottom and let me know what you think this the way that I did it is definitely very complex um apparently you could do my first search but I wasn't able to prove to bang that's why I didn't do it that way you may record that I kind of talked about it at the beginning but um yeah overall like I said algorithmically not a hard problem just a lot of weirdness that you have to take care of a lot of edge cases and making sure that you careful um that's all I have for tonight let me know what you think stay good stay healthy take your mental health have a great week friends I'll see you later and take care bye
The Maze III
the-maze-iii
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls onto the hole. Given the `m x n` `maze`, the ball's position `ball` and the hole's position `hole`, where `ball = [ballrow, ballcol]` and `hole = [holerow, holecol]`, return _a string_ `instructions` _of all the instructions that the ball should follow to drop in the hole with the **shortest distance** possible_. If there are multiple valid instructions, return the **lexicographically minimum** one. If the ball can't drop in the hole, return `"impossible "`. If there is a way for the ball to drop in the hole, the answer `instructions` should contain the characters `'u'` (i.e., up), `'d'` (i.e., down), `'l'` (i.e., left), and `'r'` (i.e., right). The **distance** is the number of **empty spaces** traveled by the ball from the start position (excluded) to the destination (included). You may assume that **the borders of the maze are all walls** (see examples). **Example 1:** **Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], ball = \[4,3\], hole = \[0,1\] **Output:** "lul " **Explanation:** There are two shortest ways for the ball to drop into the hole. The first way is left -> up -> left, represented by "lul ". The second way is up -> left, represented by 'ul'. Both ways have shortest distance 6, but the first way is lexicographically smaller because 'l' < 'u'. So the output is "lul ". **Example 2:** **Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], ball = \[4,3\], hole = \[3,0\] **Output:** "impossible " **Explanation:** The ball cannot reach the hole. **Example 3:** **Input:** maze = \[\[0,0,0,0,0,0,0\],\[0,0,1,0,0,1,0\],\[0,0,0,0,1,0,0\],\[0,0,0,0,0,0,1\]\], ball = \[0,4\], hole = \[3,5\] **Output:** "dldr " **Constraints:** * `m == maze.length` * `n == maze[i].length` * `1 <= m, n <= 100` * `maze[i][j]` is `0` or `1`. * `ball.length == 2` * `hole.length == 2` * `0 <= ballrow, holerow <= m` * `0 <= ballcol, holecol <= n` * Both the ball and the hole exist in an empty space, and they will not be in the same position initially. * The maze contains **at least 2 empty spaces**.
null
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
Hard
490,505
125
hey are you sleeping yes please shut up the stream bracket bike is now palindrome but this is well the palindrome is a straightforward two-pointer problem we have two pointers two-pointer problem we have two pointers two-pointer problem we have two pointers L and R which start at the leftmost and rightmost positions of the given string respectively while L is less than R we'll let two pointers move toward each other at each step it is important to know that we are enjoying all known alphanumerical characters we skip it by incrementing one position only for the corresponding pointer when there are multiple non-alphanumerical there are multiple non-alphanumerical there are multiple non-alphanumerical characters in a row we want to make sure to skip all of them if the elements they point to do not have the same lowercase letters the string is now palindrome else we move both pointers in one position toward each other and continue the loop after the while loop we know that the string must be a pattern drop and here is a complete code for this question
Valid Palindrome
valid-palindrome
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_. **Example 1:** **Input:** s = "A man, a plan, a canal: Panama " **Output:** true **Explanation:** "amanaplanacanalpanama " is a palindrome. **Example 2:** **Input:** s = "race a car " **Output:** false **Explanation:** "raceacar " is not a palindrome. **Example 3:** **Input:** s = " " **Output:** true **Explanation:** s is an empty string " " after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. **Constraints:** * `1 <= s.length <= 2 * 105` * `s` consists only of printable ASCII characters.
null
Two Pointers,String
Easy
234,680,2130,2231
42
so we have this idea of trapping rainwater so we're given this array which represents the heights of individual mountains so we can see zero one zero and the array represent individual this side zero one zero here the black squares are kind of the mountains and the blue squares are the water that is trapped so if we count up all the blue squares we can see that there are six blue squares so for this example we would want to output six so to kind of get some intuition about this that's let's look about at one individual element in this array so let's look right here where I'm kind of waving this mouse you see here we have a height of one for the mountain and we see that it's trapping one unit of water above it so I want you to kind of imagine if this two-story of imagine if this two-story of imagine if this two-story mountain here if the top square disappeared and it was just a one-story disappeared and it was just a one-story disappeared and it was just a one-story Mountain we can kind of imagine that the water would collapse to the left and there would be no water on top of the square so we have some intuition of you know the mountains on the left and the mountains on the right kind of holding this water in place and if you deleted certain squares from the left and the right maybe the water would collapse and maybe if we added for example if we made this to this mountain of size two into a man of mountain of size three then we can imagine that maybe water would be trapped kind of in these three squares here so we would have two units of water trapped at this element instead of one unit so we can kind of see that it has to do with maybe not just the squares directed to the left and directly to the right but maybe it tested it with the maximum the mountain of maximum height on the left side of a particular index and the maximum height on the right side of a particular index specifically if we take in the minimum of those two values that is the minimum of the maximum mountain on the left side of an element and the maximum mountain on the right side of the element so in this example on the left side the maximum on the left side of here the maximum mountain is of size two on the right side of here the maximum mountain is of size three so the minimum of two and three is two so you might think okay that means we have two units of water here but it's actually only one unit because we see here we have a man and a sized one so water can't fit where the mountain is so it's two minus the size of the mountain which is one so it's 2 minus 1 which is 1 so we want to calculate that value for every single element in our array so like if we look at this index instead the maximum mounted on the left side is going to be different it's going to be zero in this case so you know if we just if we calculated the max on the left and right for each element that's going to take a lot of time because if we say there are n elements in this array we have to look at every element on the right to calculate what the max right element is so and same for the left so for here we would have to look all the ones left all the ones right here we would have to do the same thing so we're looking from in different places and we're looking from each index we're looking at n different places to find the maximum so that's N squared time so we could do that and that would be a valid algorithm but it would be an N squared time so a better way to do it be maybe to store it make two arrays and store the maximum mountain at the left of each position in that position in the array and the maximum mountain on the right of a position at that position in the array so for example in the left max array for this element we would store you know - because the maximum is two on you know - because the maximum is two on you know - because the maximum is two on the left side but if we were at this part place in the array we would store three because the maximum left-side three because the maximum left-side three because the maximum left-side element is three at this location so we want to come up with those two arrays which we can do in L event time L then we can implement our actual algorithm using these two arrays in O of n time so let me just kind of scroll to the code and maybe you get a better idea and we have these two arrays we come up with which are the left heights which at each position I we have this the size of the maximum height for all the indexes less than I and the right side array which for each element I stores the maximum height for all elements more than I so this less than I this more than i sr i should say less than or equal to i more than or equal to I because will also be including the element itself so we build these by computing that maximum as I just described oh then we calculate the volume of rainwater using these two arrays so we look at every element in the array we calculate the current height at that element then we calculate the minimum remember we're looking at the minimum of the maximum height on the left side and the maximum on the right side so these two arrays store the maximum light on both of those sides so that's why we take the minimum of these two arrays well then we say that if our current height is less than the minimum ledge that would mean that we have this case where for example if we were here on the left side there's there exists a ledge that's greater than this ledge and on the right side there also exists a ledge that's greater so that means we're storing some water so in that case we increment the volume by the difference between the current ledge were act and the minimum of these leftt Heights and right Heights at this location
Trapping Rain Water
trapping-rain-water
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. **Example 1:** **Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\] **Output:** 6 **Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped. **Example 2:** **Input:** height = \[4,2,0,3,2,5\] **Output:** 9 **Constraints:** * `n == height.length` * `1 <= n <= 2 * 104` * `0 <= height[i] <= 105`
null
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
11,238,407,756
164
hey what's up guys so that song is 164 uh oh maximum gap uh yeah i hope you guys subscribe to my channel yeah so my channel autophysics must be abstract mathematics and horrible mathematics and sometimes since i'm practicing my coding so sometimes i pop post the code solution basically based on my understanding yeah so given an integer array numbers return maximum difference between two successful in sorted forms so uh the for example the answer is three for this case because if you sorted array you get one three six nine right so this is two three so you need to return the maximum okay the idea is that the which is 10 to a negative five right so you cannot uh i guess you can sort it right but the problem is that if you sorted you take n log n and the problem say that you must write algorithm they belong to the o n and they're using linear extra space so you cannot do sorting okay and uh the number is still 10 to the nine right so uh which prevents you use the count source so basically if you want to use the merge sort which is a log n uh it's not okay if you use a count sort which is m plus k right but now k is so large it takes 10 to nine right so it seems like you don't you cannot find it okay so the idea is to use the bucky sword okay but actually i think the bucket zone is not so important the idea is using the pinching pin gentle principle okay so the idea is that what is the so let me just ask question what is the minimum answer a minimum possible is now you can say the minimum possible answer is zero right because uh there may be a case that every one is the same right but let's just try to solve this uh in so this is trivial right but we need to have some more uh finer lower bound okay so idea is that let's demand let's say that g let's say g be the answer of maximum gap so let's say g is the maximum uh let's say g is the answer so g is a maximum gap okay then what you mean is that suppose let's imagine that you're sorted right so the smallest one is m and the second one right so second one a two that must that's or equal to m plus g right because g is the maximum gap and a3 must be that's or equal to m plus 2g and up to f like this is the maximum so who should which this at this maximum m must be less or equal to m plus n minus one g which one is the length of the array so now you get a lower bound of g which is greater than equal to m divided by m a minus one and then you can take the c uh take the cd okay so basically you prove that you can easily find a minimum answer right because you just if you want to find the maximum minimum this just takes all one time so finding so now you already find a gap you already find lower bound of the gap right so for example this one three six nine your g will equal to 8 divided by 3 take at least so become 3. okay so this 3 is the answer that it's not in this case it's just the answer right but we can but we just proved that the g cannot be less or equal to three okay so now we can use the box and i choose the size uh let's say so choose each bucket with size three okay so uh now here is a trick right so now we let's create a let's find a minimum and create the size trade the bucket okay so the bucket looks like uh so we have four bucket okay why we have four buckets right because uh the side is three right so that's so you start from one this is one two three and uh four five six uh seven eight nine and uh probably you don't need this okay so now you put one point here you put three point here you put six point here you put nine point here okay but what is the answer right the x answer must be the minimum the answer must be the minimum of this bucket minus the previous body a maximum of the previous bucket so the answer can be three and it must be already okay why this is the answer because i already proved that you greater than or equal to three so each two animal in the bucket cannot give you the answer right because i already proved that g much greater you go to the lower bound so the answer must be the maximum of the previous bucket minus minimum of the bucket let's say this is i bucket okay so that's so it's a minimum of the bucket i minus the maximum of the that bug previous by previous bucket okay provided that if the minimum provided if the bucket is not empty right if it's empty then i don't care right so for example maybe there is something here and there's something here and all these are empty then i only need this difference so i need the minimum minus the previous measurement provided if then if they are not empty okay that's it okay so basically find a gap and then do a body sort okay so answer the algorithm just find a gap and the dual bucket zone and use minimum minus maximum which is i and -1 if minus maximum which is i and -1 if minus maximum which is i and -1 if they are not empty and what you do is you find a maximum of this right this is the maximum gap okay so this is a linear time because uh you use box sort okay so let's say answer is lens and then unless if you go to two then you return the maximum and the minimum right because you only have two numbers so far stories and that's a maximum and minimum to be the max and mini and you can find a bucket so this is the size of bucket and you can find the size of the how many of buckets right so there are difference plus one okay so in rk in the first case we have uh we have like three buckets as i draw right because uh 9 minus 1 8 divided by 3 is a 2 right plus 1 and you initialize the each bucket minimum to be infinity maximum to be negative infinity okay then you go through first you find the index s which is a number of buckets so i minus minimum divided by bucket this is standard bracket sort and you change the minimum maximum okay so this is this time this is our tribute okay so finally you initialize the answer to be negative infinity and then you define the premax to be bucket zbex okay and you do the step if there is minimum if it's the minimum is not empty then you can use the previous formula basically bucket minus preview max and the update will answer and the pre max becomes a bucket max then returns basically this is just what i described okay so this problem is hard because it's hard to think of design problem but once you understand it should be very simple just using the pin joint principle see you guys next videos
Maximum Gap
maximum-gap
Given an integer array `nums`, return _the maximum difference between two successive elements in its sorted form_. If the array contains less than two elements, return `0`. You must write an algorithm that runs in linear time and uses linear extra space. **Example 1:** **Input:** nums = \[3,6,9,1\] **Output:** 3 **Explanation:** The sorted form of the array is \[1,3,6,9\], either (3,6) or (6,9) has the maximum difference 3. **Example 2:** **Input:** nums = \[10\] **Output:** 0 **Explanation:** The array contains less than 2 elements, therefore return 0. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109`
null
Array,Sorting,Bucket Sort,Radix Sort
Hard
null
343
in this video we're going to take a look at a legal problem called integer break so basically the question is that we're given an integer n and we want to break it into sum of k positive integers where k is bigger than or equal to two so basically we're given an integer n right let's say in this case n is like 2 for example we want to break it into sum of k positive integers in this case we want to break into two or more integers that has a sum that's equal to 2 right so in this case i can break it into 1 plus one right which they have the sum as is equal to n and in this case we have two right integers here right and we can in this case let's say if n is equal to three i can also break it to one plus uh in this case one plus two right or i can break it into one plus one right where i can break it into like two plus one and so on right so in this case we want to break it into two or more integers that has a sum that's equal to n and the maximum the product of those integers so in this case we want to return the maximum product that you can get so you can see here we have n is equal to 2 right so if n is equal to 2 um in this case i can only have you know in this case i have i can break it into two integer value which is one right plus one so in this case one plus one that's the only option that we have so in this case we have one times one right well you can also go with like zero but in this case you can see we have zero plus two is also two but the thing is you can see two times zero is zero so there's no way we can be able to get a maximum product right so in this case it doesn't really show but you can also see that we have another example where n is equal to 10 right so if n is equal to 10 uh in this case you can see we can break it into many things right you can see we can have like one plus all the way to ten ones right in this case we can also have like two plus two right we can also have like you know five plus five right so in this case 5 plus 5 in this case is 10 but in this case it uh 5 times 5 is only 25 right it's only 25 and we can also have like 6 times 4 which is 24 we can also have uh 3 times 7 which is 21 right but we can also break it into further more right you can see here we can also instead of taking the 6 we can also break it down to 3 right so in this case instead of 6 times 4 we can have 3 times 4 which is 36 right this is 3 times 3 which is 9 times 4 which is 39 that's 36 right so in this case you can see we can also break it out into uh more than two in positive integers and we basically can't be able to um try to get the maximum product right so in this case it's 36 that's what we're going to return at the end so in this case um let's take a look at a bit more on the constrained side so in this case constraint is that n is always going to be between 2 to 38 right let's take a bit more of examples here so let's say n is equal to 5. uh in this case what are some examples like what are some of integers that we can break it into in this case we can have we have a bit more examples right so you can see we have one plus one which is equal to five and if we were to get the product out of this it's just gonna be one and let's say if we do this in this case 2 times 1 is going to be 4 right and in this case this is also has a sum that's equal to n and then let's say if we have 2 plus 3 which is also equal to n in this case the product is six right and then here is basically four so you can see out of all those options we have six right but you can see here we can also even break it down for example like let's say if we have a situation like n is equal to 10 right in this case you can see we one options we can have like is six plus four right in this case six plus four is what six times four is 24 right but the thing is if this thing or this integer value can even further breaking it down right if i can break this down to three uh double threes right in this case three plus three six if those two value has a bigger product for this one right here then what's going to happen is that we're going to replace that with 3 times 3 right instead of 6 and same thing for 4 if i can break it down to 2 right in this case if 2 times 2 is bigger than 4 then we can just break it in down right we can break the integer down in this case but in this case four and two times two has the same value right so therefore we don't have to break it down but here you can see six three times three is 9 is bigger than 6 so we can replace that with a 9 and then this way we can be able to get a better value right bigger value so in this case if we were to solve this problem what we can do is that we can basically try to visit each and every single option right we can try to with all the option that we can get and let me draw the recursion tree here so here you can see this is our recursion tree right so basically we want to get the maximum product right return the maximum product for n and in this case is five so let's say we wanna call this function fn right we wanna find the maximum product for five for n in this case what we can do is we can basically try without each and every single option right so for example maybe like the first value that we have is one times right in this case one times four right one times four or two times three or three times two or four times one right but the thing is just like i mentioned before if the you know if this value right let's say if it's four times 6 and let's say n is 10 just like the previous example that i just provide if we can be able to break this 6 to further to 3 and 3 which causes a bigger product than the current value then we can continue to break it down but if it doesn't then we can continue to use this current value right so you can see that's basically what we're trying to do here so you can see here let's say we continue to break down four we want to try to get the maximum product for four and then we compare is four bigger than the maximum product of four right so in this case you can see we continue to do our dfs right in this case we know that fn of one or in this case if we was the maximum product for one is basically one right so we can let's say in this case it's just zero right because there is no way that we can get a you know break into well it's basically just gonna be one plus zero right 1 times 0 is going to be 0. and then we also have like fn of 2 which we already calculated here is going to be 1 right so these are all our base cases here so we know this is 1 is less than 2 right in this case i cannot if i break two down it will the max product is one or if i don't break it down it's just going to be itself right so i can just have this value itself which is going to be two right and then also here it's just going to be zero or 1 right so 1 or 0. this one is 2 or 1 right 2 or 1 in this case it's just going to be 2. so it's going to be 2 and this one is also going to be 2. so here what's going to happen is that fn of 3 is two but the thing is three is bigger than two right in this case if i break three down it's two the maximum profit the maximum product that i can get is two or it's gonna be this current value itself which is gonna be three right so in this case if it's three it's better right so the three is bigger so we have one times three and then here what's going to happen is we have fn of two f of two is one or it's gonna be two itself right so in this case what's gonna happen is gonna be two 2 times 2 is 4 and then here automatically we know that this is a 1 right even though this is a 0 if we break one down 0 if we use 1 it's just going to be 1 right so 1 times 3 2 times 2 3 times 1 in this case the best case is already just gonna be four right so in this case what we can do is we're gonna return four right and then we're gonna compare if we break four down it's gonna be four right the maximum product that we can get is four or we can use four so which is going to be for itself right so fn of four is four so maybe we can be able to like some kind of like caching or people to cache this right so in this case but if we don't cache this right the brute force approach is that if we don't cache this it's going to be exponential right but in this case what we can do instead is we can be able to cache this result right cache it into 2d array in this case like if we want to get the max product profit right the max product for you know if we break three down if we already done it is two but the thing is we can also compare this right in this case if we break three down is two or it's going to be three itself right we know that it's going to be three itself so let me just rewrite this here it's gonna be four and then here is going to be right it's going to be 2 but 2 is smaller than 3 so it's going to be 3 here right and then same thing here because 2 we already done it is 1 so 1 is smaller than 2 so in this case we have 2 and then here is just gonna be one because one is bigger than zero so out of all those you can see we have four we have six and four so in this case six is bigger so therefore fn of five right so in this case let's say if n is equal to 5 the output is 6. okay so this is basically how we solve the problem so let's take a look at how we do this in code so to solve this from code basically what i did here is i create a cache right this is our cache to uh one directional array right we basically want to cache the value right so we want to cache the maximum product of each and every single value up to n right so you can see this is our top down approach we have our dfs function we're passing in we want to find the maximum product uh if we break n down right so you can see here if base case is that if n is less than two right we can just throw return zero right because in this case um you know let's say if we want to break one down it's gonna be zero break zero down it's gonna be zero right so on and so forth and then what we're gonna do is that we're gonna see if it's already been cached before if it's uh if we already cached it we can return the cache value if not we can compute it here so this is kind of like there like the core uh function right the core feature of this function right so you can see here we have our max product for n so in this case we want to get the maximum product for n right this is n right here so zero and then what we're gonna do is we're gonna get the current max product so the current max product is gonna be if we break the current value down which is n minus i right so we're gonna go iterate from one to n we break that down to see what's the maximum product for this integer value right or it's going to be this integer value itself right just like the example that we talked about before it you know if 6 times four right is 24 if we can continue to break six down to get a bigger product then we will use this right if we don't then we're going to use six as the value that we want to get right so it's the same thing here so once we get the current max products we're going to get we're going to you know compare so for the max product for n is either max product for n or it's going to be current max times i right so what we're going to do then is we're going to cache this and return the max product for n so you can see here this is basically how we solve this problem using a top down approach and time complexity is big o of n and space complexity is big o of n as well because we're using recursion stacks the reason why we have big o of n right because we basically cache the result we only compute each and every single integer once right so this is how we solve it uh in top down approach and now let's take a look at the bottom up approach so the bottom approach you can see here we have a integer uh cache array with the size of n plus one right in this case we want to solve we want to basically find the maximum product uh for n right so in this case we want to get the index in right we want to calculate that and then here you can see we've defined similar base case right we know that we're working from the bottom to the top so in this case the first uh if it's zero if it's one it's going to be zero if it's two right in this case if cache is two right cache and x two basically means that if n is q two we have one right there's only one uh maximum power that we can break it down so we do is that we iterate starting from three to n right so same logic that we just talked about basically that for each and every single iteration we try to uh exhaust all the options right so you can see here we try with maybe like num minus i right let's say maybe num is three minus ones three minus two right and then we're trying to see you know what's the maximum product for non right let's say num is three what's the maximum product for three right in this case it's gonna be two and then you can see here for each and every single iteration we basically check to see it's either going to be cache at num minus one basically it's what we already computed before or it's going to be non minus i which is the current value itself right so at the end we compare you know the maximum product is either max product times i or it's going to be what we have seen so far right what like the cash at nom that we have seen so far right and at the end we basically return cache it and so this will give us a also a time complexity of linear and space complexity of linear as well because we're using a integer cache array
Integer Break
integer-break
Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers. Return _the maximum product you can get_. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** 2 = 1 + 1, 1 \* 1 = 1. **Example 2:** **Input:** n = 10 **Output:** 36 **Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36. **Constraints:** * `2 <= n <= 58`
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
Math,Dynamic Programming
Medium
1936
134
hey what's up guys John here so today I want to talk about another let's take a look at this little code problem 134 gas station and okay nice tickly let's take a look at this that's at this problem here so you're given like n gas stations along a circular route right where did the amount of gas at station Isaac a sigh and the cost and another cost array where the cost of this I is the cause where you need to spend from the current station to the next station and you need to return like the gas station which gas station you that can be start right you can start the starting point of the gas station where you can travel like the whole circle let's say you if you start from 3 you need to be able to travel the four five and then one two three and come back two three in the end right so if you cannot travel if we if you cannot travel the whole circle no matter which gas station you started you just need to return minus one all right so how should we think about this problem you know I think there's like some tricky start here I'll try to explain it so I think first thing we first we will need to know is that you know okay so the first concept if the total sum if the total gas right it's greater it's eco greater than the total cost right total cost then we know there has to be a station that can that will allow us to finish the whole strip right basically to circle to travel to all the other stations all right that's I think that's a fact we need to keep in mind and with that in mind and then the next thing is just a matter of how can we find that station right so what we'll do so basically what we will have like basically will be travel will be a loop through from the first station and then we were like we'll keep like a current gas and a current cost right so basically we'll you know actually we don't need to do this sorry yeah okay I just remove everything but okay so we just need to keep like a 10 basically current tank right current tank and on each station basically this thing what we keep adding the differences between the cast and the cost right basically that's the cata gas guess I miners cost high right so every time when we see a gas stations will keep adding the differences right to the tenth to the tank here basically we're accumulating all the gases we have seen so far and all the cars that we have seen so far and we track in this tank it's great it's smaller than zero right so even smaller than zero that means right what does it mean it means that we cannot go from the current station to the next station right because we don't have enough tank then we just need to move the start the starting point to our current I plus 1 right because we know and we will also need to clear this tank 2 to 0 right because that's like a basic start right so how basically we're starting making a new start we will we were like discard what we have travel to be up before so and in the end we just return this start so why will this work right I mean wow this works let's say we start from here and then we didn't with we didn't have coal to have to make sure let's say we start from for how can we know it can go file and then coming back to 1 2 3 4 and then 4 right so here there's a like cut let's see there's a like gas station here gas station like there's 1 2 3 4 5 6 let's see we're at station 4 here right where I stay tuned for and then we see oh that the gas is not enough the 10th the 10 is not enough for us to move from 4 to 2 5 right then what we have then we know if there is a possible gas station that can allow us to travel everything to do a holster a whole circle travel it has to be something right to this to the current station why right how can we prove that because you know from previously zero to here right we already we are we already accumulated all that gas we have we can collect and all the cars we can collect from the beginning to here right and so basically at any position here right so let's see for one in two or right at three right because let's say we accumulate everything in this range but when we start from here but how about the starting point right in between right and because we already have the total gas right so we have the total gas smaller than the total cost right so we'll have this fact until this for that's why we don't have enough gas to travel from four to five right let's say we can travel from one to two right let's assuming we can travel from one to two and we basically we're trying to see if this too is a very starting point right then the total gas miners are pre right so the pre is something like this right the pre gas we'll be miners and here there will be a total cost miners pre-pre cost right so total cost miners pre-pre cost right so total cost miners pre-pre cost right so let's assuming from 1 to 2 we can travel it right what does it mean it means that the pre gas let's say the precast and precast it stands for the travel the gas then the cars we need from 1 to 2 right let's see if we can travel from 1 to 2 and then the pre gas will be greater than the pre cost right and then the total gas miners pre gas will be that the rest will be the gas we have from 2 to 4 right and same thing for the total cost miners pre cost will be the total cost we have for the from 2 to 4 right since the total gas is always smaller than the total cost right and if the pre gas is greater than pre-cast the pre gas is greater than pre-cast the pre gas is greater than pre-cast then we have what we know that the total gas would definitely be smaller if this Foreman right so the remaining so there so the gas from 2 to 4 will be definitely smaller than the cost from 2 to 4 right because this one is smaller than total gas smaller than cars but here we're removing more right from the gas and of course the result will be even smaller than this one so we know even though we can travel from 1 to 2 but for starting from any point between 1 to 4 right there won't be anybody the point for us to travel the whole process basically so from 2 to 4 there won't be any enough gas right same thing for three right let's say assuming we can travel from one two three right but then front went from three onward to four there won't be any uh there won't be enough gas right so and then we know the only possible gas station will be on the right side we just keep doing it until we just return the final start and then we know our result because we are in because we also check if there is a valid right if there is a valid we just use the start point if not we just simply return minus one okay so all right so let's just do this right and we'll just do this right which to a sum right which to quick some gas right it's greater or equal is smaller than the sum of cost right then we do what we simply return minus one right that's how we check if there is a valid station right so if there is right what we do it tank we can maintain a tank here right so it for and then we tell start starting point which is I zero in this case so because we start from zero in range right in range length of gas right so we start from zero and then with what we keep up updating this tank right this gasps right gasps of I miners gasp sorry the cause of I and then if the tank is less than zero right then we know the starting point has to be somewhere on the right side right and then we just removed it with this clear tank just like as if we're starting as it as if we're starting from this starting point yeah this kind of like a like of Grady's concept here because every time right it's not in that there's not enough gas we are assuming right assuming okay so the next one we can the next one should be a can be our starting point basically we're being up optimistic right okay so if this one we know okay so we know what couldn't what station that 10 not which cannot be the starting point then we are just ridin the next available one right and we're assuming that one is our starting point right and then it's clear the time if this one is not right and then we just move this one forward again and again until we reach the end right and here it's safe for say for us to just return the start because that will be our starting point because we already checked if there is a valid gas station here right and then in the end we can just simply return whatever left for us right yeah cool I think yeah that's that should do it yeah I think there's some tricky sod here like once we have the starting point right how can we know it did this the letter last starting point and give us the valid result right so we have because we have some like checks here and like I said we have some simple proof that anything that laughed on the left side uppy before the current I won't be a valid start point and then we just remove all the other impossible gas stations and the last thing left will be our result right okay cool I think that's it for this problem and thank you so much for watching the video and see you guys soon bye
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
271
others the next question is include and decode string so basically you have to design your own algorithm to you know including the visual screen or energy code afterwards so you're not able to use the sterilized method so you cannot you know improve letter over here right so um so one way of doing this is straightforward like and so this is our entire input array strings array and how do we Define every single word as the decoding pattern so we can use this um this is hollow right Hollow is size of five oh size of five and then um we can convert list dictionary into a format into a string that will help us to dictate so I can say okay this is size of five right put the symbol in slash and then this is my word hello so this is one way to determine the uh one word right and then you have another which is going to be Hollow word so how the word is actually the five word as well so I can have another pair after the hollow right so I'm going to say five slash or right so this will be your decode string format right so you want to decode list and you return the strings on this right so uh you encode the string of words and you decode the entire s this is your s to the list of string of word right so uh using this format right basically we keep control the index after we keep on track the internet we know there's a slash after the integer right so it could be at 25 right so the index doesn't matter but we know like there's a slash after the integer before the word right so we can know this is the you know deliminator right something that is so let's stop holding um all right so here it is so in this one we convert the string sorry the array of string into a string right so I have a string Builder I'm going to put it XP I Traverse the entire list of string so I'm going to say string strange finish screen right so what I need is what I will have to um know my current uh size is going to string dot lens right and then I will append one slash and I will open the entire string then I will return spit.2 string return spit.2 string return spit.2 string okay so this is a pattern that we convert the list of word into one serenomy right so now we're getting list string into here then we have to convert this string back to this so we will have a list of string result I'm going for result and I will return it so right all right so uh how do we do this uh basically I'm going to have index so I've already seen the entire string so I would say I have less and install length so I have a slash represent the first one so extra index of the first one at right so it's going to be this one and I install this you stored in this index and then you search this symbol so uh actually I can do this so I can have a you know one slash a two slash you know E A then forward slash you know CC so I'm traversing the string array from index zero so I'm starting here uh I'm I need to find my first slash at index zero so I saw in here to go all the way right and see my first slash then I know this is a slash so I will have to what I'll have to know this is the integer the size of the word so since this is only one you know one character so you only jump one and then if this is two you want to know if you are at this position you are able to jump the entire size from here to search for the next slash so this is a pretty short format so if it's still confused just draw on the paper right so I'll have the size of size represent what the integer you want to convert to integer Direct Value so uh this will be the substream so let's start searching from a index I to slash right so we know substrate doesn't contain the last uh integer I mean last Index right so it's only starting from zero to zero as an example I was using so one slash a right zero to zero because this is one right so zero to one so it's going to be only and it's compared to this as an integer now we know the size right so we can take the word form slash plus one and then plus the size this is the size right this is this one is the size foreign slash plus size plus one so I would know my next pattern right but before I do it anything I need to what add the string Right add a string into the uh into the result so it's gonna be slash plus one and then all the way to I right so this will be the solution submit all right let's talk about the timing space it's a straightforward enough you know this is the encode and code you have independent size you know space independent time so um for every single end of a word is all of n's and then you know civerse every single string right so this is the land of the list of strings and this is land of word right so for the decode personally I would say list you enclosure this amount of time and then you append and then you put a word in there put a string in there right so this is the timing space and this will be exactly the same thing for the decode because you have independent space independent time so there's the answer right and then this is no meaning to debug like everything should be straightforward enough and the barber doesn't actually help you to visualize so this is a solution so if you still have question leave a comment below subscribe if you want it alright peace out bye
Encode and Decode Strings
encode-and-decode-strings
Design an algorithm to encode **a list of strings** to **a string**. The encoded string is then sent over the network and is decoded back to the original list of strings. Machine 1 (sender) has the function: string encode(vector strs) { // ... your code return encoded\_string; } Machine 2 (receiver) has the function: vector decode(string s) { //... your code return strs; } So Machine 1 does: string encoded\_string = encode(strs); and Machine 2 does: vector strs2 = decode(encoded\_string); `strs2` in Machine 2 should be the same as `strs` in Machine 1. Implement the `encode` and `decode` methods. You are not allowed to solve the problem using any serialize methods (such as `eval`). **Example 1:** **Input:** dummy\_input = \[ "Hello ", "World "\] **Output:** \[ "Hello ", "World "\] **Explanation:** Machine 1: Codec encoder = new Codec(); String msg = encoder.encode(strs); Machine 1 ---msg---> Machine 2 Machine 2: Codec decoder = new Codec(); String\[\] strs = decoder.decode(msg); **Example 2:** **Input:** dummy\_input = \[ " "\] **Output:** \[ " "\] **Constraints:** * `1 <= strs.length <= 200` * `0 <= strs[i].length <= 200` * `strs[i]` contains any possible characters out of `256` valid ASCII characters. **Follow up:** Could you write a generalized algorithm to work on any possible set of characters?
null
Array,String,Design
Medium
38,297,443,696
131
hey what's up guys this is sean here so today let's take a look at it called problem number 131 palindrome partitioning given like a string as partition as such that every substring of the partition is a palindrome okay and then return all the possible palindrome partition of s so i believe all of you should have known what is a palindrome right so palindrome means that you know a b a the palindrome basically the latter the string will be the same after reversing the string and then that's a palindrome and but for this problem it not only it asks you to check the palindrome but it also asks you to return all the possible palindrome partition of s where each of the partition is also palindrome and notice that a single ladder is a palindrome for sure that's why for this aab here we have two output here the first one is a and b and then a b but a and a b is not because a b is not a palindrome okay so i mean for this kind of question i ask you to return all the possible numbers you know we already used what the back tracking or the dp right and for this kind of like you have each of the possible ways of partitioning these things here right so we usually use the back tracking basically the backtracking my third will be uh the first one is the uh the first backtrack right so the first parameter is always the start index right where it's telling us where should we start right basically it means that we have figured out all the uh we have partitioned all the strings before the start now i'm going to try the partition from here onward and then we have gonna have like a current partition right current partition means that what is the current partition list here so the logic for the backtracking will be what starting from the start index and we're going to try each of the substring right from start to what 2n and we try all the all of those partitions the out of substrings if the substring is a palindrome then we know okay that's going to be one of our candidates we can just move the start to that to the index that's after that after the uh after this new palindrome stream and then we're going to add that new string to this part partition list here and in the end if we reach the uh if we reach n here the start is equal to n then we know okay we have find one of the answer one of the list where each of the item is a plain jump string all right and that's the basic backtracking logic here and actually to improve the uh to improve the time complexity when checking the when checking if the substring that from start to end here is a palindrome we can pre-calculate it we can pre-calculate it we can pre-calculate it we can precalculate we can pre-calculate all the substrings we can pre-calculate all the substrings we can pre-calculate all the substrings right we check we give all the substrings a boolean value which indicates if that substring is a palindrome so that here we can just simply use one time to get the uh to check if that substring is a plenum or not okay and to do that i'm going to use like a dp right to uh to check the palindrome i think that's going to be a to populate all the flag to check all the substrings if it's the substring is a palindrome we use a dp right and cool so let me try to implement that dp here maybe i'll try to explain a little bit more while i'm implementing that you know so i'm going to have like a dp right so at the beginning all the elements is false right so equals to n for this in range n right because i'm creating like a 2d array here whose size is n here to uh and this dp i and j dpi and j means that from i to j if this thing is a palindrome the value is like is true either true or false and that's the definition of the dp here okay and the way we're checking it you know i believe in lithgow there's like a similar problem just ask you to check if a string is a palindrome and we basically use the same logic here so i'm using i'm looping through the eye from back to the start so the reason being is that i want to use the uh the i and the j start from i and ending j that's why i loop from the end and then for j i loop so i look from i to n okay that's why that's how i uh i look through this i give the value for the i and j here right plus from i to j okay and the logic is pretty straightforward i mean if s i is equal to sj right because you know to check the palindrome you know let's say we have a b and a let's see if this is i and if this is j it can so the substring i to j can only be a palindrome when the it could be a palindrome right might be a polynomial when the iso is equal to sj that's this is the case otherwise you know if we have like b a and this is i this is j so the iron jr is not the same then it cannot be a palindrome right so we only assign this dp to true first thing first condition is the ice i has to be equal to be the i has to be same as xj here right and then if i si is equal to xj and then all we need to check is that if the dpi plus one and the dpj minus one if they are the palindrome right if they are the palindrome and then the cardinal is also palindrome right so and another case is that you know if the j minus i is smaller than two right so this is for the k for the one ladder case and two ladder case all right so for this case two cases as long as the i and j are the same and the j is and j minus one is smaller than two then we can simply assign this flag to two or like i said or the dp i plus one okay and j minus one right and j minus 1 and then we assign the dp i j 2 to 2 right and after this one we have store all the flat for each of the substring okay then we're gonna have like a answer equal to this one and then now it's time to define our backtracking functions right so like i said the back tracking the first one is start index and second one is a current partition okay and then here we call the backtrackings we start from zero and we pass in a empty list right and then we return the answer so the base case right so when the start is equal to n we know that okay we have traversed to all the strings and we have processed all the other strings right before the start which means that each of the substring in this current partition is a palindrome then we can simply do a pen with a current partition right i do a deep copy because this is a this is going to be a reference right that's why i do a deep copy of that and what and for i in range of start to end right if dp start to i it's true right it means that if that's a palindrome then we can update the partition with the uh the substring actually you know to further improve that substring the string slice i can just uh use a current string here so every time when we add a new when we are at the new index here we can simply do a append this thing to the end so that we can improve this one by changing this time complexity by getting a substring to one time instead of o in time right and then we have a partition append to the current string right and then since this is a backtracking it means that we're gonna remove that partition dot pop right and then right in the middle here we have what we have backtracking all right since we have we're at i here which means that the next thing next index starting point will be i plus one right and then we pass in this current partition right so only continue if the sub string is palindrome right palindrome okay cool i think let me try to run this code right here name partition okay so this one accepted let's try to submit all right so it's it passed um yeah let's see what's next and to calculate the time complexity so this one is a little bit complicated because you know so first right we have o of n square here right to pre-calculate it to pre-calculate it to pre-calculate it to precalculate all the uh the plenum flag for all the substrings and so the tricky part is this backtracking part basically you know we are we're what we are trying to get all the substrings we're checking all the substrings right and for each of the sorry basically we're checking all the partitions and for each of the partitions we're checking the if the string is a plenum or not and let's say we have a right so what is the total um partition what is the total partition for this kind of string you know you can think it in this way right so you can split the string on each of these locations right so how many places we have n minus one and at each of the places you have two options you either cut from here or you don't cut from here so which means that the total combination for this one is going to be the 2 to the power of n minus 1. and that's the total number of the partitions we have and for each of the partitions right for each of the partitions here uh we're gonna loop through basically we're gonna try to check if they are the uh if the string party if they are the substring right of this uh this partition combination they are their palindrome and that will take an o in time so that's why the total time complexity for this problem is like what it's 2 to the power of n right since this n minus 1 will be 2 to the power of n and times it yeah so that's going to be the time complexity all right so the space complexity is the same right i think the space complexity is going to be the 2 to the power of n which will be the total number of the backtracking because we'll be using that many of the uh the backtracking stack uh recursive call right to check that cool i think that's it for this problem you know this is a i think it's a pretty it's pretty interesting like i would say it's called the backtracking plus dp combination problem yeah i hope you guys like it alright i'll stop here thank you so much for you guys to watch this video and stay tuned i'll see you guys soon bye
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
113
so today we're looking at lead code number 113 it's called path sum2 very similar to path sum 1 which is also in this playlist so if you haven't checked out that video highly recommend checking out that video first because we're using a very similar template to solve this one just making some slight modifications okay so here we have a tree we're given a root of a binary tree and an integer target sum and we want to return all the root to leaf pads where each pad sum equals the target sum okay and a leaf node is a node with no children so we can see here our target is 22 and 5 plus 4 plus 11 plus 2 equals 22 5 plus 8 plus 4 plus 5 also equals 22. so we want to return an array an output array with the path values of these two pads okay here from root to leaf our target is five and there is no viable path that equals our target sum so we just return an empty array uh and here we have one and two also targets on a zero and we return an empty array okay and some constraints here we have a number of nodes in the tree is zero to five thousand okay and then the values are from minus thousand to one thousand okay so let's take a look at how we want to approach this we want to do depth first search traversal on this and we want to keep a slate array that's going to keep track of the path up to that point and we want to push and pop off that slate array as we hit the as we go down each level and then we want to pop off as we hit each leaf level okay so what do i mean by that so let's say we start here at the root okay we're going to have two recursive functions one that's going to traverse to the left and one that's going to traverse to the right for the sake of simplicity i'm just going to go all the way left and then go all the way right just that way it's a little more clear so in our initial function where our target is going to equal the sum so we'll just say we can actually call this sum running sum and this is just going to equal our target sum so we'll just set this at 22. okay we're going to have a slate which is just going to be an empty array initially and we're going to push in the node values as we traverse so our sum is 22 and if we're going to go left we're going to minus whatever is in our current nodes we're going to subtract 5 from our sum and our target is now going to equal 17 and we're also going to push this 5 into our slate okay now we're going to go left again and we're going to subtract whatever is in our current node which is 4. so we're going to subtract 4 from there and our target is going to equal 13 and we're going to also push in that current node into our slate or the current node value into our slate okay now we are here we're going to go left and we're going to subtract whatever is in our current node from our target so we're going to subtract 11 and our target is going to equal 2 okay and we're going to push this 11 into our slate now when we get to this leaf level we're going to check does our target equal whatever the value is at our leaf level node it does not okay it does not so we just backtrack out of there we just return out of there we don't do anything okay so we're gonna go back here and now we're here and our target is 13 we're going to subtract 11 and now our target is 2 on the right side and we check do these two equal they do okay they do equal so what we want to do is then push that value that leaf level value two onto our slate now our slate is complete we have a viable solution here so we have a global result and we're going to make a copy of the slate not put the actual slate but a copy of this slate scan it and put it in and push it into our global result okay so here we're going to have 5 4 11 and 2. okay now once we've hit this we pop off this 2 off our slate go back up we pop off this 11 off our slate we go back up we pop off this 4 off our slate we go back up and now we're back at the root and we're going to go on our right side we've exhausted the entire tree on the left side now we're going to go on the right side okay so we're going to subtract 5 our target is going to equal 17 and we're going to push on this 8 onto our slate let me just get an eraser and clean this up a little bit so it's not so messy okay and so all we're doing is traversing from the left to right i hope this is starting to make a little sense on how we're doing this okay so now we're going to push on this 8 onto our slate and now we're going to go left and we're going to subtract 8 from our target which is 17. so here we're going to subtract 8 from 17 and that gives us 9. and now we check does this 9 equal this 13 it doesn't so we don't do anything we just backtrack we go back up and now we come down and we subtract 8 again from our slate our target equals 9 but we're not at a base case so we go left again and we subtract 4 from 9 and now our target is going to equal 5. so we're going to do minus 4 here and then minus 4 here and now we check does this equal our slate it does i forgot to mention when we go down we're going to also push in that 4 onto our slate and now because this equals we're going to push in this 5 onto our slate and then push make a copy of this slate and push it into our result so it's going to be 5 8 4 and 5. okay we're going to now backtrack up and come down here and our target again is five does it equal one it doesn't so we return out of there okay and then this will come all the way back up to the root and we will break out of our depth first search traversal and then we just go ahead and return our global result in our parent function in our main function okay so let's that's the idea behind this now let's think about time and space complexity if the tree is balanced okay um then we are going to have to go traverse through every single node but when we reach this bottom here we're going to have to scan we're going to have to do a linear operation okay so if the tree is balanced we're going to do n and then a log n because the slate at worst case is going to be the height of the tree which is log n if the tree is balanced but we are not guaranteed that this is going to be a balanced binary tree so the tree could look like this you know it could be a one-sided tree here a one-sided tree here a one-sided tree here and if that's the case the height of that tree is going to be n it's going to be linear and so our time complexity here is going to be o of n squared okay where we're going to have to traverse through every single one of the nodes but then at the bottom we're going to have to take a linear scan to push that into the result and what about space complexity well it's a similar thing okay because we're creating this slate and if it's not balanced the slate could be the it could be n and then we have to make a copy of that and then push that into our result array as well okay so our space complexity here is also going to be n squared this is also true if we're even dealing with you know even a tree like this you know if every single one of these is a viable path then we have to create space for this for we have to create space for this path and for this path here so every single path you'd have to create space for so it would be n squared okay so let's go ahead and jump into the code okay so first thing we want to do is we want to take care of the edge case if our input is null so we can just do an if root is null then we can return an empty array now we create a global result we'll call this paths and we'll set that to an empty array and now what we want to do is go ahead and create our depth first search helper this will take in a node a sum and then a slate okay now what we want to do is we want to check if we are at a leaf node that's our base case so we want to say if no dot left is null and no dot right is null then we are at a leaf level and then what do we want to do here we want to check if the sum equals the no dot value our current node.vowel right that leaf our current node.vowel right that leaf our current node.vowel right that leaf level node if the sum if the running sum does equal that then what we want to do is push onto the slate the current node and then we want to make a copy of that slate and push it into our global result paths okay so we're going to just make a scan of that and then push it into our global result and then we just want to make sure we pop up pop that off the slate as well so that way when it goes back up when it backtracks back up we don't have that value on our slate okay and so now let me just create some extra space here now if we're not at a leaf level we just want to handle our recursive cases so if we have a node.left we have a node.left we have a node.left then we want to add to our slate our current node and then recursively call depth first search on the left side sum will minus the current node.val sum will minus the current node.val sum will minus the current node.val and then pass in our slate and then just pop this off our slate and this is just the same thing we're doing on this side except we're just doing it on the right side okay and now all we need to do is call that first search call our helper function on our root pass in the target sum and set our slate to an empty array and then just return pads all right let's go ahead and run this make sure it works and we're good okay so not too difficult of a problem you just got to make sure you have this pattern this depth first search pattern like in the back of your head if you know that pattern then you know you can solve these types of things you know really easily it's not too bad this still doesn't make sense check out the previous one path someone i go over the same pattern it's a little bit simpler because we're not dealing with the slate or anything but just go over these videos a few times and it'll click it's not too bad once it kind of clicks and makes sense okay so that's lead code 113 path sum2 hope you enjoyed it and i will see you all in the next one
Path Sum II
path-sum-ii
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** \[\[5,4,11,2\],\[5,8,4,5\]\] **Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** \[\] **Example 3:** **Input:** root = \[1,2\], targetSum = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Backtracking,Tree,Depth-First Search,Binary Tree
Medium
112,257,437,666,2217
59
given a positive integer in generate a square matrix filled with the elements from 1 to n square in spiral order that's about today's video less I mean kamalii this is where my dream started everyone this is Steve here today we are going through another little problem dude called 59 spiral matrix to you as we have gone through a spiral matrix yesterday a few days ago this one is basically a follow up when there is some nuances a little bit differences so this one is always a squared so let's take a look at this question first given a positive integer n generate a square matrix so this is a square it's always a square there is no chance it's going to be a rectangular feel with the AMEX from 1 to N squared in spyro order so it's Row is a number of n economies also number of n so given input 3 so it's going to generate a 3 by 3 matrix so looking at here is 3 by 3 rows and 3 columns and it's in spiral order it so see 1 2 3 and then it's not standing from the left side of the second row stuff it's going down from top right to bottom right 3 1 2 3 4 5 and then 6 7 and then 8 and then 9 this is the spiral order if you guys recall the previous legal question which is spiral matrix I'll put the link to my other video basically the first question of this series of questions final matrix 1 2 3 down in the link in the description below you can take a look at that one first but here basically the algorithm is very similar we'll just to use for variables Tom indicating the top row and left indicating the left boundary of the columns and right to indicate the rod boundary of the columns and bottom to indicate the bottom row and then or just to keep shrinking from left hand write shrinking towards the middle and from bottom and top shrink towards the middle as well just a the algorithm is very similar to you the previous one but we just need to tweak it a little bit because this one it's asking us to generate the matrix right not printing it out we're just generating we said we'll keep incrementing the value of the number and then assign the constantly updated value into the matrix and the correct position so basically we need to calculate the row and the row index and column index and then just keep incrementing the value assigned a correct value into this matrix that's it there is nothing else we can talk about we're just amused basically for loop similar to you in the previous solution use for loop to go through row column so for loops and outside there's going to be another while loop to control this entire thing that's it then we'll just start coding first we'll initialize the final and final result called result and so it's going to be a square the first thing we all check Conor case if N equals to zero will just return result and then we'll just have four variables as I just said top bottom left and right to control the four boundaries in the top is zero and bottom is n minus one and then left standing from zero and all right standing from n minus one then we'll have a outside while loop can to control the boundaries to say black is smaller than or equal to right and top is smaller than or equal to bottom as long as these two conditions hold we'll just keep iterating through and fill out on the entire n by n Square and by n square yeah square matrix yes and then so we'll start from well feel from the top left then go to the right so int that means we'll go column by column so we'll use J to indicate the column it's just a convention to reduce confusion and then and J's spanning from zero J is smaller than or equal to right boundary or do is j plus past and then we'll put that into we need one more variable or just call it number is standing from one so you see here this number and this number is standing from what all right and then here the that is top row so economies J and then it's just a number or number do let's press after that so after this first for loop where we are and we are here after the first for loop we add this side at three position and the position of three now we want to go towards the bottom right how do we go towards the bottom we need to do top plus one right so top is the first row and then we need to go to the second row right so top plus one and then we go towards the from the top right towards the top towards the bottom right so we're going down right now going down they spa loop dumb is a row by row so we'll use I starts from actually J should stand from that yeah J should not start from zero because the left boundary keeps shrinking that's the whole reason we have these four variables so and then I is going to start from top and then I as long as I is smaller than or equal to bottom then we just keep incrementing I and then matrix is the row and the right is the column then we'll just keep incrementing number after this after the second for loop when we are here oops well here well and this fives position so at five position what we need to do we need to achieve towards the left so that means we are going to do right - one so right here going to do right - one so right here going to do right - one so right here the right boundary is at two so we need to decrement 2 by 1 so 2 - 1 so here and to decrement 2 by 1 so 2 - 1 so here and to decrement 2 by 1 so 2 - 1 so here and then next step we need to go from this position towards the left another follower here int that means a column by column so we'll use J starting from right and then J is greater than or equal to left side left boundary then J we keep decrementing J and matrix then this is bottom this is that's the row index the economy next is J so that is number + + so at this moment when we is number + + so at this moment when we is number + + so at this moment when we are at this position we're at J are we are at this position we're at J from the seventh position we need to move up then we need to decrement bottom index bottom decrement it is that right yeah bottom decrement then we need to go up stand for the row by row go up so I start from bottom and then I greater than or equal to top I keep keeps decremented and then this matrix is going to be I stir well index column index is left and then a sign number to this matrix number and then increment number again at this point where we are at this matrix the spiral matrix were at 8 here and then from this position we need to move towards the right so we finished one once by one entire loop in on four sides so now we're starting the second loop again so it's going from left towards the right so at this point we need to shift at the left boundary towards the right so from the left boundary is at eight here towards the right a to nine so laughter boundary is to go up that's it this in this these four loops let me just have a quick double check J starts from left smaller than right keeps going up that's the top row and top incrementing and then we start I from top as long as top is smaller than bottom I keeps coming up and then that's the right boundary that's correct and then right is going to shift towards left then we start from J from the right and then as long as J is greater than equal to left Jay keeps decrementing that's the bottom that's correct bottom row hmm is that correct yeah I think so and then from the bottom I starts from the bottom as long as n is greater than or equal to top I keeps going down so and that's on the left side so I think that's correct and there were just a returned the matrix that's hit submit and see you cannot find symbol number matrix oh shoot variable number one that should be matrix submit 8.33 memory that's matrix submit 8.33 memory that's matrix submit 8.33 memory that's very low submit it again same okay every way but basically this is the idea of the follow-up question spiral matrix to the follow-up question spiral matrix to the follow-up question spiral matrix to again we would this is a common technique of very general that we can apply to you similar problems we use for variables to control the for size the for boundaries then we keep shrinking towards the middle so in the fall in the four loops and then there's an outer wire loop to control the access the break condition that's it for this problem you guys I hope this video could help to how people understand the solution of this problem and how to tackle it if you have any comments questions please leave me down in the comment section below and if you like this video please do me a favor and gently tap the like button that's gonna help along with the YouTube algorithm and also don't forget to subscribe to my channel I would really appreciate it thank you very much I'll see you guys in the next video
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
1,248
Hello everyone, this is our problem today and in this we have to find how many numbers of off we will say to whom, OD number should be present and one key should be given to us in the input, as if we understand it through the example. Our first example is that we have been given the name 1211, like 1211 is also free and the number is present, so like this, we have to find it, so we do one thing to understand a question, like how will we solve it, like our 11 If we do this then this is it and then increase it, then if we look at the second element then increase that order too, let it remain as it is, again if more came, then increased it again and if it came, then increase it, now here. See, like what we need and from here till here I am that number, then what is left from here till here will have three OD numbers in it, so by doing this, let us see how we will solve it through hack map, so we will take it by name. There are 3, we take one and we take an account here in which we will store the count of how many OD numbers are present till the index and we take an account which will store how many numbers are off, so first on the index. That is OD like norms of I module of 2K if this van goes to A then we will increase the alt count then whether the first one is present or not, if it was not present then we put its corresponding van value, it becomes that which is our Hot count, this is our value, after that you will increase further, now you checked that it was not present in the map, kept 2K corresponding van value, after that you and is or and is gone and here on you, we will have to increase by one because you It was already present and as soon as 3 came, we want K3, so we will increase the account, so our count, which was already zero, has now become that in the map, four minus three was present here and its value. So who are we in the count plus this is equal, you are the one who is counted, we will return it to him, return, this is our output, how much time complexity did it take for us, which one of us will get extra space, then that of Bigg Boss N So in the court, we have to take an order map of these three types, we take a map, after that we take a variable, we give it a counter of how many more numbers have come till the particular index, after that we will check the number. And by doing this, if this element is odd, then we will increase the account here and if the other count is equal to the goal, which means it is ours, then we will increase the account, after that we check it in the map. If that account is present or not, mines k9equaltump.in. k9equaltump.in. k9equaltump.in. If it is present, it means that it is already higher in the map, then what will we do? Will we increase the account? No, if who else is already present in the map? If it is not there, then we put it in the map and calculate its value using WAN. We will return it and check the answer. Now we have a code, we run it and see how our court test is. The final submission has been set and let's see. Our code has also been set on the final submission. Okay, let's meet in the next video with a new problem
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
128
hello and welcome back to the cracking fan YouTube channel today we're solving lead code problem 128 longest consecutive sequence given an unsorted array of integers numb return the length of the longest consecutive elements sequence you must write an algorithm that runs in Big O of end time let's look at a very basic example we're given this input 100 for 200 1 32 so basically we want to construct the longest consecutive sequence of numbers we can here so let's see uh we have 101 do we have you know maybe 99 or 101 no so we can't really do anything with this uh what about 200 well we don't have 199 and we don't have 2011 so we can't really do anything with that either what about four well do we have three yeah we do we have five no but maybe we can go backwards so we have four we have three and then from three we have two and we have one so actually we can build a sequence 1 2 3 4 uh and that actually is our best answer here so basically we can just use whatever elements we have and we can put them in any order we want similar with this nums here as you can quickly glance from this is actually the numbers um from basically Z to uh it looks like eight right so let's see what we can do here so we have two zeros which doesn't really do anything for us um actually can we have duplicates let's see if it matches so we have zero uh and then we also have a one here let's see do we have two yes we have two oops two we have three we have four we have five we have six seven and we have eight okay so it looks like we can't do duplicates uh because the final answer is nine so basically we can rearrange our numbers in any order we want um and then see what the longest sequence we can get so looking at the basic examples it's quite easy to figure out how to do this now before I actually get into the actual solution for this because we know that we need to do it in Big O of end time let's first think about what the naive solution is because this will actually motivate um how we actually solve it for the optimal case so let's think about this to check if we have a sequence we need to basically for any number we need to start checking to the right of it and to the left of it and basically see how many elements there are on the left and how many elements there are on the right if we add that plus the number in the middle then that is the length of our sequence so what we could do and we're not going to do this because this isn't the best answer um we could basically just put into a you know we can hash we can create a set of all of the numbers that we have and then what we want to do is for each number we're going to check okay do we have um you know whatever that number minus one is uh yes okay then we want to basically keep going until you know we exhaust that number uh and then we also want to go to n + one and then we also want to go to n + one and then we also want to go to n + one and then we want to keep going to the right and we're going to do that for every single number here until we get our sequence so for example with 100 if we had our set being like 0 100 4 2 uh 1 3 2 then what we want to do here is that okay we're going to check okay do we have 99 no okay so we can't really do anything there do we have 101 no so the length of that sequence is just one if we just took hundred on its own then we're going to get to four so do we have a five no but can we get a three yes can we get a two yes can we get a one yes can we get a zero no okay so the sequence ends there it would be 4 1 3 2 now you know this is pretty efficient you know we're doing lookups in a set and this is you know a set lookup is Big O of one the problem here is that we need to do this operation for every number so that's already a big O of n operation just to go through every number but now we need to actually do a big O of n search across all of the potentially other numbers in here um because for each one we need to basically search uh the rest of the array to see if we can find uh those numbers so we actually will get some duplicates here and our algorithm will actually run in Big O of n^ s time which actually run in Big O of n^ s time which actually run in Big O of n^ s time which is not what we want because the issue here is okay we've done it for four and we've established that we get 1 2 3 4 as our longest sequence but what happens when we then process one we'll also do 1 2 3 4 and then also for three we'll also get that 1 2 3 4 and also for two we'll get 1 2 3 4 so notice all of this duplicated work and you know if you have something like this where actually all the numbers already in a sequence you're going to have to redo this lookup bigo of n times so that's actually why we have you know n squ here for this algorithm so instead of doing it for this we actually want to just do it one time instead of um starting it at four we basically just want to start it from one and then go all the way to the right so we need a mechanism that will actually let us do that so this is the Crux of the solution and we'll actually just go over how to do this in the code editor because it's really simple but essentially what we want to do is the same approach we just did with the naive solution except instead of checking every single element uh we want to be smart about where we actually start checking such that we don't repeat ourselves and you'll see how we do this in the code editor it there's really no point of going through an example with it because it's really straightforward in the code we'll just do it there but just remember that we need a smart way of actually uh making sure we don't duplicate ourselves in the logic so let's go to the code editor and I'll show you how we're actually going to do that okay we are in the code editor let's type this up like I promised the code is really simple so let's begin remember that the first thing that we need to do is actually put our numbers into a set such that um you know we have something to process here and we can do the lookups efficiently so we're going to say that nums is actually going to equal to a set of nums so we're going to put this into a set so that we can easily do efficient lookups now what we want to do is we want to iterate over each of the num in nums and figure out what our result is but before we do that let's initialize our longest streak variable which is going to store our result obviously it starts at zero because we haven't processed anything yet so now we're going to do for Num in nums here's where we want to be smart remember we don't want to duplicate things so for example if we had 1 2 3 4 in our array if we process the four first we would get 3 2 1 um and then also when we do it for one we would get 1 2 3 4 and then if we did it for two we'd get the same answer and same for three right we don't want to duplicate that work we want to be smart so what we're actually going to do is we're going to say if num minus one is not in nums then what we want to do is we want to start from that number so if there's nothing to the left of our number then that would be the starting point right so say we had again the numberers 1 2 3 4 if we were processing one um we can see that there's nothing to the left of it so that way we can just go right and by having this constraint we'll make sure that we actually never duplicate ourselves in the processing CU say in our set three actually comes first right because two is already in the set this is not the starting point of this sequence two could be the starting point but actually when we get to two we realize that one is the starting point so we want to make sure that there is never an element to the left of our current element before we start counting that way we can be sure that our start element is actually the start of the sequence and we can just simply look for Num plus one uh until we reach the end of our sequence so that's the way that we're actually going to be smart about it because okay again if we get four then three could be the start of our sequence so we're not even going to process four because we know that there will be a sequence three and four that will um be longer than just four so we don't even process four and that's how we're going to avoid our duplicate uh processing here and bring the time complexity down so if we found the leftmost point of our sequence by saying that if there is nothing to the left of our current number then we want to go to the right and see how long the sequence can go so we're going to say uh current equals num and we're going to say that current streak uh is going to equal to one because obviously our current number is the number that we take and we're good to go now what we want to do is keep going to the right of our current number and just process as far as we can so we're going to say while current + one exists in nums so while current + one exists in nums so while current + one exists in nums so while it's in nums we're going to say that the current streak uh is going to get incremented by one the current number will get incremented by one and we just run until this while loop will end on its own then when the while loop ends we need to update our longest streak so we're going to say longest streak is going to equal to Max longest streak and whatever the current streak is so we will update our solution if there is a better one once our four Loop ends we just need to return the longest streak now okay if you're still confused I will make this super crystal clear for you uh let's look at this example again so we put this into our set so what we're going to do and maybe yeah okay this is a good example so we're going to put this in our set and I'll use curly braces to indicate that it's a set so let's go through this one by one so the first number that we process is going to be 100 so what we're going to do is we're going to check is there 99 in our set so 99 in the set no so that means that we can process to the right of 100 assuming that it's the start point so we're going to say the current number is 100 current streak is one and we're going to try to look for 10 101 so obviously 101 is not in this um set so we can't do anything the longest streak just becomes one right so longest streak just becomes one because we were able to take the 100 now we get to the four and previously when we did it naively we would have processed and got that we can build a streak of 1 2 3 4 but we have since three is in our nums we know that we can build a sequence of 34 so starting at three we can go to the right and there could potentially be more things here but there's no reason of doing anything with a four as the starting point if we know that there is something with a three because it will always be longer so that means that we don't even process this four then we get to this 200 here and again we're going to check is 199 in the set no that means that this could be a starting point um it's not obviously because 2011 is not in the set so we don't do anything the longest streak is still one then we get to the one at this point we check okay is zero in the set no so we can start processing okay so then we're going to hit this while loop we're going to check okay is two in here yes it is uh so now the current streak will become two because it was previously one uh and then we're going to check is three in nums yes it is so now the current streak is four then we're going to check is four in there yes it is we update the current um streak and then we're going to check is five in there it's not so that we break this while loop then we update our longest streak variable to be four and then you know we' continue so four and then you know we' continue so four and then you know we' continue so with three obviously two is in there so we don't need to process it two one is in there so we don't need to process it so you can see how we basically skipped running for four three and two and this is where we save on the time complexity so now if you see we're going to just submit this let me make sure I just didn't make any serious syntax mistakes with my uh unexpected indent what happened here uh did I screw something up on the indentation not nums um let's see for numb and nums if huh why is my indent wrong huh interesting what is wrong with the indent oh wow that why is that's so weird Okay anyway that's weird wrong answer what am I did I not return the right variable longest stake okay that's just stupid all right there we go now if we actually spell it right um we'll get the right answer okay longest stake uh let's now submit it and um hello okay accepted perfect so what is the time and space complexity here so obviously for this solution to even be accepted it has to follow the requirements in the problem and that is that it's Big O of n so we create this uh nums here which is going to take Big O of end time obviously to make a set out of a list uh and then for our processing as you can see we actually don't repeat processing um so each element will actually only be processed one time which means that this entire Loop here is also Big O of n so that means that our total time complexity is just Big O of n plus Big O of n but ASM totically that's Big O of n uh so this is the time and um the space complexity as you can see we basically need to build a set out of our nums so that's just going to take Big O of N and that is your time and space complexity relatively straightforward okay so that is how you solve longa gez I cannot speak today I can't type today um yeah this is how you solve longest consecutive sequence hopefully you enjoyed this hopefully you found the video informative and you didn't uh cringe at my mistakes and spelling mistakes but it's fine we like to have fun on this channel uh you can see that I'm doing this live all right if you enjoyed the video why not leave it a like and a subscription to the channel really helps me grow otherwise thanks so much for watching and I'll see you in the next one bye
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. **Example 2:** **Input:** nums = \[0,3,7,2,5,8,4,6,0,1\] **Output:** 9 **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Union Find
Medium
298,2278
1,662
hello guys welcome to algorithms made easy today we will be discussing the question check if two strings arrays are equivalent in this question we are given two string array word one word two and we need to return true if the two arrays represent the same string and false otherwise a string is represented by an array if the array elements concatenated in the order forms the string so in the first example as we are given this two values in the array if we concatenate them we get abc as a string and the same string is what we get when we concatenate all those strings in this second array as well as the two strings are equal we return true in the second example we see that the two strings are not equal because from the first array we get acb and from the second array we are getting a b c so we return false given are the constraints with the problem that the array will contain only lower case letters there are two hints given with the problem the first hint states that concatenate all the strings in the first array into a single string in the given order and the same with the second array and the second hint states that both arrows represent the same string if and only if the generated strings are the same now we will see two approaches to solve this problem the first approach is by using the hint given to us with the hint given to us we know that we need to convert the two arrays into string and then simply compare them so that will be a pretty short code so let's write it down here we have a function make string that converts the array into a string and then at the end we just need to simply check if the two strings are equal or not now we define the function will have a string builder because the append operation or we can say the concatenation of strings is fast in string builder then in string literate over the array appending the string into this and at the end simply written the string when we run this code it gives us the right to the let's ask this for a false input as well make this value d so it still gives the right result let's submit this so it got submitted successfully now the time complexity of this approach is o of max length between the two arrays and the space capacity will be of k where k is the length of the string as we are using a string in order to hold the string formed by the arrays now how we can solve this problem without using any space in order to do so we need to iterate over the two arrays side by side comparing every character and then at the end if the two indexes are at the end of the two arrays then we are sure that the two arrays create the same string so we will see how we can code this we'll reset this now as we know we need to have indexes for the two of the array one pair of index will be which defined which index in the array that we are checking and a second index will be which character in that string we need to check so the index array will be int array index 1 initially be 0 and same array index 2. now we need to have the internal indexes which will be id 1 which will be 0 and id 2. now we need to loop till we reach the end of word one and one two so we'll have a while loop for that wherein we'll check if now inside this we need to first check if the character present at index id 1 of the string present at array index 1 is equals to character present as id 2 offstring present at array index 2 so we'll write that in code like this and in the same format for the second array as well if the character are not equal then we can simply return false from where no need to continue forward if not then we need to increment the two indexes that is id 1 and id 2. now that we have incremented it there will come a chance when we need to jump from one position of the arrow to other and we need to jump from one to other when we have reached the length of the string in the first which means if id1 is equals to the length of the string present at array index 1 then we have to jump so we need to first make the id1 at 0 because we will starting with 0 and then increment the index 1. same needs to be done for index 2 as well copy that as we discussed if at the end the array index 1 is equals to word one length that it has reached the end of the first array and also the second array then we are sure that the two strings are equal let's run all the sample test cases at once so all the test cases are successful when we submit that score so it got submitted successfully the time complexity now becomes of n where n is the length of the string but the space complexity now becomes o of one thanks for watching the video see you in the next one you
Check If Two String Arrays are Equivalent
minimum-numbers-of-function-calls-to-make-target-array
Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._ A string is **represented** by an array if the array elements concatenated **in order** forms the string. **Example 1:** **Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "\] **Output:** true **Explanation:** word1 represents string "ab " + "c " -> "abc " word2 represents string "a " + "bc " -> "abc " The strings are the same, so return true. **Example 2:** **Input:** word1 = \[ "a ", "cb "\], word2 = \[ "ab ", "c "\] **Output:** false **Example 3:** **Input:** word1 = \[ "abc ", "d ", "defg "\], word2 = \[ "abcddefg "\] **Output:** true **Constraints:** * `1 <= word1.length, word2.length <= 103` * `1 <= word1[i].length, word2[i].length <= 103` * `1 <= sum(word1[i].length), sum(word2[i].length) <= 103` * `word1[i]` and `word2[i]` consist of lowercase letters.
Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even.
Array,Greedy
Medium
null
1,169
hello yours welcome back to my channel I am back with another problem from read code I hope you are enjoying all the problems there I am applauding today's problem is invalid transactions from lead course so a transaction is possibly invalid if the amount exceeds thousand dollars are it if it occurs within 60 minutes of another transaction within the same name in different city so there are two conditions to make our transaction is invalid basically first time the first thing is if the amount exceeds thousand dollars and then it's invalid transaction are if the same name transaction of the same name happens within the 60 minutes in another city then there is also invalid transaction so we are given with a set of transactions right so the transaction consists of some comma separated values representing name time in minutes amount and city of the transaction so now we are given with the list of transactions we will have to output the transactions which are possibly invalid right so by using the two conditions so for example if you go this example that the number one else 2800 MTV Alice fifty hundred beatings so as it said first is name and then next is time and the next one is the amount and the last one is a city that's what it says right so in this there is there are no transactions which are exceeding thousand dollars so from this we cannot anything identify rate so for the other thing is the same name and within different city rate so let's see for the same name and different city so name is Alice yes it matched and it should be different city MTV and beating so there are different city but let's look at if they are within 60 minutes of each other so the time is 20 and time is 50 yes so they are in fact invalid transactions because they are they happen to be within the sixty minutes of each other right so now we will have to say both of them are invalid transaction so that's the output that we are going to give let's look at another example right just to exercise the first option there are thousand dollars so in here Alice and Alice both st. names are same but here the transaction happened within the same city so we don't have to look for whether they are within sixty minutes are not right the other thing that we would look for is okay this is less than thousand dollars so it's valid but this is greater than thousand dollars right 1200 so for this input the output is just only this transaction will be the output so likewise so basically exercising two conditions right so let's look let's go look at how we can solve this problem right so since we are dealing with four different parameters named time amount and city we're going to get create a placeholder class with four fields write that and create an array of that placeholder class to store all the transactions that we are seeing given as the input and once we create the array rate we'll have to fill out by splitting the string into four different parts right so now sort the array by using a new icomparer class the chi camper is basically you want to identify the values which are invalid right so you sort that array and then detective it is within thousand dollars the sorting is based on the x so that the sorting that we have to do is based on the Soyuz time that is the second thing right so time is a second thing that we are going to see right so the other thing if they're if they are in the same basically time right so we will go through the what do you say the name basically right so first it's the time and then if the time matches then it is a name that you have to use so that is the logic that we are going to I compare our class and then once the started once the sorted array is available we will be going through the shattered array and do the detection of whether it is greater than thousand dollars are within the knee sixty minutes for the same name within another city or not so likewise so that's the that is the way to do it let's go look at the code right so first as let's look go look at the place called a class so the placeholder class is the transaction which contains the name time amount City right so these are the four fields right so this is a place called class for this place or correct class we are writing an icomparer so this is the I component that we are going to use it to start the list of the transaction so first we are going to compare the name if the names are same then we are going to compare the time otherwise if the names are not same we just go over the name so that is what we are going to use first name and then time this name same name is same then we are going to look at the time if the name is not same then we don't have to worry about the time because even its name is different even if they hunker within 16 minutes we don't flag it as invalid transactions right so this is I compare our class that we are going to use so let's go back to the main method where we are going to write the invalid transactions function so let's get the length of the transactions and we have a answer this is the hostel that we are going to return right and then we have created a array of transactions right likewise we created a dictionary of transactions right so likewise and now we go through the each transaction and split this transaction into four different parts name time amounted city and store them in the transaction array so you start this transaction array by using the new transaction sort right so the sort is based on the name and the time if the name is saying then we will going to go the time if the name is not same we'll just go the name that's it so that's what it is so let's go so once a sorted array started then we go through the sorted array if the transaction amount is greater than thousand right just go add it to the hot stud that we are going to return so otherwise right so otherwise what we are going to use is starting from the next element if the name is same then we will have to see whether the city is different and the time is less than 16 if so we add both transactions to the list the answer that we need to return otherwise we just break if the name is not saying we just break we have to go to the next element so likewise this will be repeated for n number of times right for each of the objects finally we are going to return the answer list which will have the invalid transactions because that is what we have identified so this is one on one condition and this is another condition where we are checking for so hope you understood the problem so let's look at the time complexity of this algorithm right so the time complexity we are going through each transaction here so we will say this will be for this for loop it will be equal to the order of number of transactions and we start we are going to start using the trans start right so that will be typically a sorting algorithm will be order of n log n all right and now we are going through that entire set starting from 0 to n the worst case complexity for this will be order of n square right the typical this is the worst case let me so this is a worst case so the overall time complexity for this would be order of n square so this is a worse case that we are saying not normally this is not the that is magical that you see but you probably it is anywhere from order of n order of and to order of n square right so that's what the practical complex okay hope you understood the problem if you like the solution please subscribe to my channel and share among your friends thanks for watching I'll be back with another video very soon till then Bob
Invalid Transactions
largest-values-from-labels
A transaction is possibly invalid if: * the amount exceeds `$1000`, or; * if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**. You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**. **Example 1:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\] **Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. **Example 2:** **Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\] **Output:** \[ "alice,50,1200,mtv "\] **Example 3:** **Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\] **Output:** \[ "bob,50,1200,mtv "\] **Constraints:** * `transactions.length <= 1000` * Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "` * Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`. * Each `{time}` consist of digits, and represent an integer between `0` and `1000`. * Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
Array,Hash Table,Greedy,Sorting,Counting
Medium
null
1,358
Hello welcome to me youtube channel number characters a b and c so basically we have given a string ok and in it we have to extract the number and substance in which a list of a b and c i.e. abc should be present i.e. abc should be present i.e. abc should be present in this so let's take an example After that, what will we do that I will track further So what will we do with the account, what will we do with the light, which is on the left, we will remove the size from it, what will we do Let's keep it in the counter, it is of such good size and we have to make mines in it. After that, when we meet for the first time, what will we do, now we have to move the one on the left, then we will remove the one on the left. Then we removed one, removed another one and it became zero, then we will move ahead, we moved forward with J, then we have got A here, so now we will band one account to another, then we will get all three ABCs. Gone then what will we do now When we will move forward then it was given to us and then what will we do if we meet all three characters in the map So what will we do 6 - 4 That So what will we do 6 - 4 That So what will we do 6 - 4 That means you This time hum log ka tu ed ho jayega 2 ed ho jayega Jo yeh par hum log aaya hai What substances will there be in it ABC Ek yeh ek yeh aur ek yeh hum log ka aaya hai him Which time will be the latest B C A B and B C A B C? After that when you have come B C A B C and the last one who has come is the one who is A B C and the last one does the most. What will we do with it in this form? We will put it in the map. Light one, whatever character will be on the right index. Put whatever character will be on the MP of S off right. We have to check And if we don't have a map of our character on the index on the left, then as long as our character on the index on the left, then as long as our character on the index on the left, then as long as we keep moving to the left and then check, it's possible that someone at the beginning If there is a deputy or an epithet, then in the end, if ever another C comes, then what will happen to it, directly, we will check the condition
Number of Substrings Containing All Three Characters
find-positive-integer-solution-for-a-given-equation
Given a string `s` consisting only of characters _a_, _b_ and _c_. Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_. **Example 1:** **Input:** s = "abcabc " **Output:** 10 **Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._ **Example 2:** **Input:** s = "aaacb " **Output:** 3 **Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._ **Example 3:** **Input:** s = "abc " **Output:** 1 **Constraints:** * `3 <= s.length <= 5 x 10^4` * `s` only consists of _a_, _b_ or _c_ characters.
Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z.
Math,Two Pointers,Binary Search,Interactive
Medium
null
205
hey everyone welcome back and let's write some more neat code today so today let's solve the problem isomorphic strings we are given two strings and we want to determine if they are isomorphic but what are isomorphic strings well the simple definition is they are isomorphic if all the characters of one string can be replaced to get the other string so replaced so basically that means that s and t both of the strings have to be the exact same size and luckily that's not something we have to worry about basically in this problem all inputs are going to be the same size anyway so that's one but it's a little bit more nuanced than that and they explained that in the next paragraph so let's just take a look at the first example we're given two strings egg and add and when they say replace all characters of one string to get the other string they mean that all occurrences of a certain character must be replaced with another character while preserving the order of the characters what that really means is that all e's for example an egg we have an e all e's have to be replaced with another character in this case it's kind of obvious we'd want to replace the e with an a character so that we can convert this word into this word and the next character g in this case obviously has to be replaced with a d if we want to get the other word but the thing is if we say that okay g's are going to be replaced with d characters we're basically creating a mapping saying that g's are going to be replaced with d so we have to continue that so basically the next g character is already decided we have to convert it into a d but that's okay in this case because if we do that we do end up getting this word basically what we're saying is that any character from s can only map to a single character we can't say that g maps to two different characters like d and maybe e as well or something and that becomes really clear when we actually look at the second example which is this so let's just go character by character okay f in the first string but we have a b in the second string so what that means is that probably we want f to map to a b right we have to do that we have to map f to a b if we want even a chance to be able to convert this into this string but let's look at the next character oh okay so o needs to be mapped to a in the second string so we're going to say o maps to a that works so far right we can convert the first two characters of this into the first two characters of this but the problem comes when we look at the third character we have an o right so we want to map this o to an r if we want to finish the string but we already decided that o's are going to be mapped to a's we can't just change that and we definitely can't map it to two different characters like r and a so basically once we've gotten to this point we realize it's impossible for us to map this into this these are not isomorphic strings so we have to return false in this case but there's one last little trick kind of thing that i want to show you because i think this is probably what a lot of people get tripped up on for this to be isomorphic with this we also have to say that this is isomorphic with this right so well we're just going to kind of swap the positions of these put bar here and put foo here and now try to check if they're isomorphic okay b maps to f so good so far b is going to map to f a is going to map to o that's good so far right we can have a map to o now we have r mapped to o as well now this doesn't look like a problem at first right because a is mapping to o but we're not having a map to two different characters we're having r now map to o but we have two characters two different characters a and r both mapping to the same character we can't have that either and they mentioned that right here no two characters may map to the same character so this is i think what people might get tripped up on in this problem and basically it means that when we are going through the strings and creating that mapping that we are gonna have to have the mapping go both ways right we're gonna have to say okay b maps to f and also f maps to b now for the actual algorithm on how we can efficiently solve this problem and it's not too different from what you might think if you were doing this manually and you had a really long string you would probably want to write out the mappings right you would say okay b and f so we're going to write out the mapping b maps to f right you'd probably do use like a piece of paper or something right and we're in this case actually gonna have two mappings right making sure that we map one to the other and the other to uh the other one right so i'm gonna say here f maps to b as well and it'll make more sense as we finish this example so next we'll say a maps to o so here we're going to say a maps to o and over here we're going to say that o maps to a so far so good right but now we get to the third character r maps to o so over here that's perfectly fine r maps to o but when we do it up here we see that o maps to r but o was already mapping to a different character up here right o maps to two different characters so that's how we know that this is not isomorphic and then we can return false so i hope this idea of you know using a piece of paper or something to map from one string to the other and vice versa makes sense be and then think about it what kind of data structure would we want to use to do these mappings well the easiest way and the most efficient way is to use a hash map because we know that inserting and basically reading and writing to a hash map is always constant time big o of one so that will be the most efficient solution for this problem because with a hash map the overall time complexity is just going to be iterating through both strings and we know that both strings are going to be the same size so let's just say the size of the string is n technically it would be two times n because we have two strings but you know this reduces down to big o of n anyway and the overall memory complexity is also going to be big o of n because clearly we are going to be using some hash maps to kind of store these mappings so with that being said we can actually jump into the code now okay so now let's do my favorite part running out the code remember we're gonna have two data structures i'm gonna call it map st and map ts basically indicating that in one of the maps we're gonna be mapping the characters from s to t and in the other string we're going to be mapping the characters from t to s and they're both going to be hash maps this is how you can do hash maps in python and then we just want to iterate through the strings we know they're the same size so we can use an index for both of them our pointer i we're just going to iterate through the entire length of one of the strings and we're going to get the character at index i from both of the strings so let's just call them character 1 and character 2. so character 1 is going to be from string s character 2 is going to be from string t before we actually do the insertions like this is clearly what we want to do right from s to t we want to map character 1 to character 2. and in the other map ts we want to map the character 2 to character 1. but before we even do this we want to detect if this character already has a different mapping if it has a different mapping than this then we have to return false and that will stop our algorithm but if that's not the case then we will continue and do this insertion and then continue to the next iteration of the loop so how can we detect if it already has another mapping well first in python at least we don't want to get a key error so first we're going to check if c1 is in map st and if it is and basically is map st the mapping of that character one is it different than c2 what we're about to insert right because this c1 to c2 is a is what we're about to insert but if it has a different mapping already that's when we know we can return false but we're not done just yet we have an or condition because we know that we have two hash maps and if the opposite is true basically if this mapping also if there's a different mapping than this one then we also return false so we're basically going to copy this exact same thing with the other hash map so if c2 is a key in the map ts the other map and if map ts where the c2 is not equal to c1 then we know it has a different mapping already and again we will return false if either of these is true but if neither of them is true then we can do the insertion continue to the next iteration of the loop and keep doing that until we exit the loop and if we do exit the loop then we know that definitely they are isomorphic and we can return true and if you want to say one line of code which really isn't important but i like to we can instead of you know using an index i we can get rid of this and iterate through c1 and c2 because we know these strings are the exact same length in python you can iterate through two strings simultaneously like this zipping them and you know just do that if you know feel like saving one line of code but it's not important let's run this to make sure that it works though which actually is important and on the left you can see that yes it does work and it is pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Isomorphic Strings
isomorphic-strings
Given two strings `s` and `t`, _determine if they are isomorphic_. Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. **Example 1:** **Input:** s = "egg", t = "add" **Output:** true **Example 2:** **Input:** s = "foo", t = "bar" **Output:** false **Example 3:** **Input:** s = "paper", t = "title" **Output:** true **Constraints:** * `1 <= s.length <= 5 * 104` * `t.length == s.length` * `s` and `t` consist of any valid ascii character.
null
Hash Table,String
Easy
290
1,448
hey everyone welcome back and let's write some more neat code today so today let's solve count good nodes in a binary tree this is according to leak code this is microsoft's most asked question of 2021 so far and in my opinion it's actually a pretty good problem to understand a lot of good fundamental knowledge can be gained from this problem so we're given the root of a binary tree that is going to always be non-empty we want to count the number of non-empty we want to count the number of non-empty we want to count the number of good nodes in the tree and a good node is defined so for example take node x it is defined as a good node if for example let's take this node 4 if from the path from the root node all the way down to this node this path in particular if there are no nodes in this path that have a greater value than this particular node so basically along this path if there isn't any value larger than 4 then this node 4 counts as a good node what about 1 let's take the path from the root to 1. are there nodes greater than the value 1 along this path yes because this node 3 is greater than this node 1 so then 1 is not a good node so we can solve this problem in linear time big o of n time where n is the number of nodes and memory complexity is going to be log n or in other words the height of the tree which technically could be greater than log n it could be as big as n and we can accomplish this with a simple tree traversal in particular we're going to be using pre-order traversal meaning to be using pre-order traversal meaning to be using pre-order traversal meaning when we recursively run dfs on this we're going to process each node before we do recursively the left subtree and recursively the right subtree so the first question is the root node technically a good node well this is basically the entire path are there any nodes greater than three no so technically yes the root node does count as a good note so what we're going to do now we've counted one as we found one good note and now we want to know how many good nodes are there in the left subtree and how many good nodes are there in the right subtree well first let's do the left subtree even though we could do it in the opposite order but i'm just going to do the left first so to count how many good nodes are in this left subtree first we have to run the dfs on the left child but before we do that we have to pass to this left child we have to pass what's the greatest value we have seen so far we don't have to pass all the values we've seen so far we just have to pass the greatest because then we're going to check for every node is this is the greatest node that we've seen so far somehow greater than this node if it is then this is not a good node so to this node we're gonna pass the value three we're gonna now process this the greatest we've seen so far is three one is smaller than that this is not a good node so this does not count but we still have to recursively run dfs on the left and right now when we do run dfs on the left obviously it doesn't have a right subtree but on the left subtree what value are we going to pass here well we would want to take the max of 3 which was the parents max and the value here of course one is smaller than three so we're going to pass three to this uh node as well so far the max we've seen is three is the max greater than this node it's not so even though they're the exact same value this still counts as a good node so that's what we learned and so now we have seen two good nodes so far now the same thing we're going to do on the right subtree literally the exact same thing just recursively doing the same thing we're going to pass 3 to this node because 3 is the max value we've seen so far from the root right if there was a really big value here we wouldn't want to transfer it to the right subtree but we're counting from the root downwards so let's look at four is this max value greater than four it's not so then four does count as a good node now let's do the same thing for the left subtree but when we go to the left subtree we're not passing three we're passing four because so far now along this path the max value we've encountered is four so we're going to pass four to this child node one now obviously four is greater than one so this does not count as a good node same thing on the right node we're going to pass 4 down to this node the max we've seen so far is 4 but this value 5 is greater than it 4 is not greater than 5 so this counts as another good node so all together you can look we have one two three four good nodes and we would you know from the root what would we actually do we'd say okay we so far we found one uh good node at this root in the left right plus left this is basically the equation we're going to use one plus left plus right of course left is actually going to be one because there's one good node in the left subtree right is actually going to be two there's two good nodes in the right subtree so one plus two that's going to be four so from the root we're going to return four good nodes in this entire tree so with that being said we can finally jump into the code okay so we know this is going to be a recursive function but in our recursive function we're going to have to pass in more than just the root so which is why i'm going to define a separate function inside of this function dfs obviously we're going to pass in the node or the root or whatever you want to call it but we're also going to pass in what the max value is so far from the path from the root all the way down to every particular node and i didn't mention this but our base case of course is going to be if the node we reach is null right so if not node now what are we going to return then does an empty tree have any good nodes of course it doesn't so we're going to return 0 right ok so now we got to a node that is non empty we want to know is this particular node a good node or not well let's compute that into our result so we're going to say okay result is going to be 1 if this node is a good note how do we know if it's a good note if the node value is greater than or equal to the max value encountered so far otherwise the result so far is going to be 0 meaning this node is not a good node next we want to do is update our max value so far right we're just going to take the max of itself and the max of the current node's value so we've updated our max value so far why did we do this because of course we're going to need to pass this along to our dfs recursive call of course we're going to run dfs on the node's left child passing in the max value and of course we're going to do the exact same thing on the right child the right subtree passing in the max value so far now what are we going to do with the results of these two recursive calls well this function itself is just counting the number of good nodes so we're going to take the result of it and add it to our result for both of these function calls we're going to count the number of good nodes in the left and right subtree adding it to the result once that's been computed then we can go ahead and actually return that result value so you can see that this dfs is basically computing the result that we want of course we want to compute it for the entire tree so when we actually call our dfs we're going to call it on the root node now what default value can we pass in for the max value so far well we could pass in some kind of negative infinity right or whatever but it actually works out as well if we just pass in the root value because as long as this root is greater than or equal to the max value so far it does count as a good note and we know that the root node always counts as a good node so this is going to work out for us now what we actually want to do is return the result of this function call and then we're good to go as you can see it's pretty dang efficient so this is a good fundamental binary tree question to understand your pre-order traversal and it also happens pre-order traversal and it also happens pre-order traversal and it also happens to be the most common asked question by microsoft of 2021 so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Count Good Nodes in Binary Tree
maximum-69-number
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good**. Root Node (3) is always a good node. Node 4 -> (3,4) is the maximum value in the path starting from the root. Node 5 -> (3,4,5) is the maximum value in the path Node 3 -> (3,1,3) is the maximum value in the path. **Example 2:** **Input:** root = \[3,3,null,4,2\] **Output:** 3 **Explanation:** Node 2 -> (3, 3, 2) is not good, because "3 " is higher than it. **Example 3:** **Input:** root = \[1\] **Output:** 1 **Explanation:** Root is considered as **good**. **Constraints:** * The number of nodes in the binary tree is in the range `[1, 10^5]`. * Each node's value is between `[-10^4, 10^4]`.
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Math,Greedy
Easy
null
1,324
elephants so today we discuss this question of lien code being clean 172 question number 1 3 2 4 print words vertically so in this question you are given a sequence of words or like a sentence in this there are different words and you have to stack them vertically in vertical order and then print the words as it is in the output as a string vector as you can see in the example we've been edge over W a rd i owe you and then this becomes one word this becomes 1 this becomes good and you have to return this as an vector a vector as a string vector of string ok so but the main trick in this question is like I'll show you with an example this R is a word like to be or not to be so if we stab this to be or not P so this place becomes empty and the question state that we have to put white spaces here not we can't ignore these void spaces but we have to ignore this white space because if we stack these words in this order only this word are the trailing spaces have to be ignored but the spaces which come before this we can't ignore them and we have to put a white space in place of that as you can see in this example they have stacked those words but the T till T they have put the white spaces but after that they have not placed anything so this is the question and we have to print the vector of strings so there can be different strategies and different methods to print this I have just done the basic and the most simple one but the code has become a little lengthy but the concept or the method is very logical so let me help you get to the code so what I have done is first I have added a white space at the end of the string that we can end the while we are moving in this string we can end add a wide space so that upward is completed I'll let you know how this boy got missed working so first I had my twitch at the end and then I count the number of letters in the string and the first objective of my first loop this for loop is what I am doing is finding the word which has the maximum length word in this whole sentence says that the maximum letter word in the sentence is 3 so if it is 3 now in this the first word is 2 3 so the 3 is the maximum letter word in this whole string so this loop found the Maxie which shows the maximum led length of the word in the input then what I do is because as you can see in this example we have to add buffer spaces to accompanies this spaces in the final word so we have to put buffer spaces so what I did is I'll go through each word in this letter in this string and what I do is if I encountered a white space like first I'll go from T then BOOM then I encounter a white space so it means a bird has completed so a word has completed then what I'll do is I add underscore at the last of those words so that we make those letters of the word equal to the maximum later what I'm assuming to say that the first letter is T then po but as you know we have also we also have to add a buffer value such that the length of this word becomes equal to the maximum letter of the word possible so I add a buffer underscore and then we push it in this vector of P so what it does is it makes all the letters of equivalent and it has is by backspace understood at the end of those data then what I do is I will make a vector and I add those words into that practice is that if I encountered this underscore I put a space so that what I do is then I move from each good okay I'll move from T then I put it in this string at T then pull I'll put it here book and then there's also white there is also underscore because we have make all the strings of equivalent because it's too later work is also be an underscore and then because this underscore I add a space here I hope you are understanding my point because T I add here oh I add here and because they also understood because we have made all the words of equivalent of three this is also under square and if you have encountered underscore we'll put a white space that's what I am doing here I'll if I encountered an underscore I'll put a white square where in space if not I just add that word and then I'll in the file I'll form a vector string I'll form this vector of different strings length but the thing is this also trailing underscores at the end of those words so then I have to again look through those words and see if there is a white space at the end I'm doing a loop from the end to the start of each word I'm trained to each word and on an each word I'll go in from back to the front and if I encountered a white space I am just ignoring it and the first word is encountered I will make the flag one so that it doesn't ignore the front white spaces I hope you understand it because they are also write this in the friend but I just want to you versus at the back so I'll mark here a flagon and just when the first byte space from the back I encountered it just ignore it but when the first word is encountered is make the flag one so that it doesn't ignore the MySpace's at the start and then it adds all those the new word in this and then I'll copy back those bad word in to answer and the answer area and then I just return the answer re I know this is the sounds it will be confusing but you can repeat this video and again clarify your doubts if you have some doubts please mention out in the comments below and I'll see you in a next video thank you
Print Words Vertically
where-will-the-ball-fall
Given a string `s`. Return all the words vertically in the same order in which they appear in `s`. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word. **Example 1:** **Input:** s = "HOW ARE YOU " **Output:** \[ "HAY ", "ORO ", "WEU "\] **Explanation:** Each word is printed vertically. "HAY " "ORO " "WEU " **Example 2:** **Input:** s = "TO BE OR NOT TO BE " **Output:** \[ "TBONTB ", "OEROOE ", " T "\] **Explanation:** Trailing spaces is not allowed. "TBONTB " "OEROOE " " T " **Example 3:** **Input:** s = "CONTEST IS COMING " **Output:** \[ "CIC ", "OSO ", "N M ", "T I ", "E N ", "S G ", "T "\] **Constraints:** * `1 <= s.length <= 200` * `s` contains only upper case English letters. * It's guaranteed that there is only one space between 2 words.
Use DFS. Traverse the path of the ball downwards until you reach the bottom or get stuck.
Array,Dynamic Programming,Depth-First Search,Matrix,Simulation
Medium
null
7
now i have a coding interview question integer reversal that was asked by linkin you are given an integer that integer can be positive or negative and you have to reversed the integer the reversed order would be like this four three two one and this integer can be negative for negative this value we should return minus 4 3 to 1 in this problem we have a constraint what is that we have 32 bits storage in our computer memory we can't store a value that we can't store in 32 bits all right if the reversed integer takes more than 32 bits then just returns zero and that's called overflow for integer overflow simply just return zero we can store minimum value in 32 bits this one minus 2147483648 and we can store maximum value in 32 bits this one two one four seven four eight three six four seven for test if we have this as input then we should just return 0 because this number is greater than the maximum number that we can store in 32 bits how we can solve this problem try solving this problem in your own when you are done come back to the solution video here's my solution to this problem integer reversal for test we have this number 4 3 2 one and minus four three two one and we can solve this problem by doing pop and push operation let me show you how that might look likes i'm going to declare a function reverse that sticks the integer then i'm going to declare a variable reversed equals to zero then run a loop until the integer becomes zero then pop in modulus 10 and x equals to x divided by 10 and in here we're doing pop operation we're just getting the last digit from the number and we're just removing the last digit from that number all right here pop equals to n modulus 10 in this case we get the number 1 right here pop equals to 1 then x equals to x divided by 10 here x divided by 10 it becomes 4 3 to 0.1 and for integer type 4 3 to 0.1 and for integer type 4 3 to 0.1 and for integer type it should be 4 3 2 without decimal part right and here we're just doing the prop operation we just get the last digit and we remove the last digit then for now just ignore this if statement all right and here in this line reversed equals to reverse time 10 plus pop and here we are pushing the number to this variable reversed here's reversed time 10 we have 0 right 0 times 10 equals to 0 plus 1 pop equals to 1 so the reversed become 1 at this sketch then for the next iteration of this loop pop equals to n modulus 10 in this case we have the number 4 3 2 in this case in modulus 10 mean 432 modulus 10 and it equals to in this time 2 pop equals to 2 right and x equals to x divided by 10 and we're just removing these two from this number right then we're going to push the number to this variable reversed reverse times 10 here 1 times 10 equals to 10 plus 2 equals to 12. all right for the next iteration of this loop pop in modulus 10 it becomes 3 and we're going to just remove 3 at this line and we just remove 3 and here we're going to push the 3 to this variable reversed and here reversed times 10 here 12 times 10 equals to 120 plus 3 equals to 123 right and for the next iteration of this while loop pop equals to 4 and this time we have the number 4 right and we're going to just remove 4 from this number and then we're going to just push the number to this variable reversed reverse time 10 that means 120 times 10 it becomes 1200 plus pop here we have pop equals to 4 and plus 4 and it equals to 1 234 right and in the next iteration number equals to zero right and here it should be in not x okay and also this is n not x all right and that's how it works and it also works similarly for this number minus four three two one okay let me show you how that works for this number okay for pop operation for first time pop equals to minus one okay then n equals to n divided 10 it just remove the last digit from this number and we're going to just append to this pop for first time reversed equals to minus 1 then in the next iteration the number 2 equals to pop the pop equals to number two and we just remove two then we're going to just push two to this reversed it's minus two okay not just two minus two and then minus 1 times 10 equals to minus 10 minus 2 equals to 12 minus 12 all right and for next iteration pop equals to number 3 and then pop equals to minus 3 and then we're going to just remove three then we're going to just push to this variable 12 times 10 times 120 minus 3 equals to 123 in the next iteration pop equals to minus 4 and we're going to just remove 4 from this number and then reversed equals to reverse times 10 123 times 10 equals to minus 1230 plus pop and in this case minus four then minus four and reversed times ten equals to one thousand two hundred thirty minus four so minus four it equals to minus one thousand two hundred thirty four all right and that's how it works now i think you have a clear understanding of these algorithms now let's see how this works these two if statements now let's talk about the constraint to this problem first let's talk about of this first if statement let's say you're given this integer and then what you have to return right now let's figure it out we can store minimum number this number and maximum number this number in 30 to bits okay now for this proof and for this push operation let me show you step by step okay if we reverse this number it will look like this number first eight four six three eight four seven four one all right these numbers becomes like this without the last iteration for two right now in these iterations we just get pop equals to two and we just remove two from this number right then it comes to this if statement reversed greater than max divided by 10 if we divided this by 10 then it will be like this 2 1 4 7 4 8 three six four it just popped out the last digit because it's integer type all right then we're going to compare does the reversed number is greater than this number for this sketch the reversed is greater than the number we get by dividing 10 so in this case we have to return 0. now let's talk about this step if we have this number seven four six three eight four seven four one two if you're given this number then what you should return now let me demonstrate you step by step in this sketch if we reversed this number then it will look like this all right if we reversed this number by this pop and push operation this number look like this number will look like this without the last iteration right and in the last iteration we have pop equals to 7 and here we just removed seven from that number okay now we have the last digit is seven then it comes to this statement if reversed is greater than max divided by 10 and this number is not greater than this number right and this equals to max divided 10 and it falls when it's false then it moves to this condition reversed double equals max divided 10. you see this number and this number exactly the same right then again we have to check does the pop is greater than 7 here we have pop exactly 7 not greater than 7 so it's evaluated false because the pop is not greater than 7 but it's equal so it's evaluated false so we should not return in this case 0 then we should push the 7 to this number and we have to return this number understand and if we have a number in here like 8 in the place of 7 then and pop equals to eight right that's greater than seven so it's true and if it's true in this sketch if we have the number eight in the place of seven then we should return zero not this number in that sketch okay and that's how this statement work i know it's kind of difficult to understand please try with your own examples now let's talk about this part now we're going to talk about this if statement now let me show you step by step let's say you're given this number as input then what you should return all right now if we have this number and if we reverse the number then the number will be look like this without the last iteration right and then the number would be like this minus nine four six three eight four seven four one right and then we'll go to this statement and this statement is false so we go to the statement does reversed less than mean divided by 10 and it's just this part right and it will be like this all right and this part now does this number is greater than this number this is greater than this number we know that the bigger number comes first and if this is the distance of this number then the distance of this number would be here and obviously we see that this number is greater than this number from this little map in this case we should return 0 right because this condition evaluated true right now let me talk about for this number if you're given this number as input then what your code should return now let me talk about that if we reversed this number by this pop and this push operation then the number will be look like this if we reverse this number by this pop and push operation without the last iteration the number will be look like this 2 1 4 7 4 8 3 6 4 right and in the last iterations we have pop equals to minus 8 right and then we're going to just remove the 8 from this number and then we go to the statement this statement is false then we back to the statement and here this statement is false right this number is equals to this number in this sketch and this is this number right also this is this number all right and this is equals right in this sketch so it falls then it evaluated through this part it's true then it check does pop less than minus eight and it also falls because pop equals to minus eight and minus eight less than minus 8 it falls so then we need to push the number to this reversed variable and it will look like this here 8 then we have to return this number and here what we did right but if we have something here that is less than minus 8 that means here if we have the number minus 9 instead minus 8 if we have the number minus 9 then we have pop equals to minus nine and here minus nine is less than minus eight right and from basics math we can see it if this is zero then if eight exists here then the nine should be in here okay so eight is the bigger number of these two and then in this case we should return zero right we got the pop here minus nine and it's less than minus eight in this case we should just return zero and this is the solutions to this problem now i think you have a clear understanding of this problem and how to solve problem like this feel free to check out the solution code i attached to this video thanks for watching this video and i'll see you in the next video
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
81
mmm-hmm hey guys how's it been going mmm-hmm hey guys how's it been going mmm-hmm hey guys how's it been going long time no see there's outbreak of new I don't know coronavirus here everything's tend to be like stressful and we are starting to work remotely from home I hope this could be suppressed as soon as possible today let's take a look at number anyone surge in rodeo so little ray - they're supposed to have a race ray - they're supposed to have a race ray - they're supposed to have a race sorted in ascending order and he's worried at Assam cave unknown like this one it will be yeah put its first three numbers no oh wait where are you spit up here first four numbers to the backward and there's an eel right here and we're given a target to search you found we return true if not we return false it's kind of the same as similar - yeah it's kind of the same as similar - yeah it's kind of the same as similar - yeah there's a follow-up here this is a there's a follow-up here this is a there's a follow-up here this is a follow-up problem to number problem we follow-up problem to number problem we follow-up problem to number problem we have solved before which is number 33 we're numb may contain duplicates so that before there's new duplicates and now there's a new there might be depleted so we have to actually this the solution must be similar teacher to similar so just a copy paste the code here and to some slight modification if you want to know the details of number 30 33 please search on my channel there will be a detailed explanation there for this new one let's just do a brief recap about how our previous solution so the talk the new the B array we received actually is something like these are two part the first K 1 2 K the K plus 1 to N which is in both of this sub-arrays which is in both of this sub-arrays which is in both of this sub-arrays they are ascending this is a constraint that is one will be bigger than SN in a previous problem because there is my beam there would be no duplicates but now it's no it's different it's now it's bigger or equal to right okay so we're doing the same we're using binary search it's the basic structure will be the same to pick the middle one middle number and compare if it's the same with the target we return true currently now we only return the true or false so if it is smaller than it for the middle there might be middle there would be two possibilities for middle right it's middle here which is this one or this one right for this one how can we judge this in the previous solution we judge this by comparing two s 1 which is si and now we have different problems that is actually they will be possibility of the s 1 equal to xn ok so now the first case if number middle is bigger than it equal than it mmm this is not good right if it is equal to it we can just wishes to return right okay so if Nam's middle is equal to num sy we return mm-hmm return mm-hmm return mm-hmm false right so we have removed the equal here so if it's bigger than it then you must be here oh sorry target is small in the middle and number middle is bigger than in here okay so we can surely we can safely if target is figured wait a minute okay so if yeah case is this and if target is bigger than it mm-hmm wait a minute bigger than it mm-hmm wait a minute bigger than it mm-hmm wait a minute oh god there's some problem here if target is smaller than the middle and now if middle is the same as he is if it's same as si if it's same is si the middle this is weird because we can surely say that if the number if speaker than si it must be the case like this right so now because now target is more than middle if it's here the target might be here or here so we're now compared to target with s I again if okay if it's bigger than it then be bigger than si then we're sure we say this is true right else if target is smaller than this more than it then we say the turkey must be here so we can sure the move I to needle that's true and therefore the other case will return true right if it's the same as si and I'm sorry okay so for the other case if target if nums middle this modern si it's more than that it then they must be the case like this then there's only one possibility that's target is here so we move j2me the minus one it's unfair and for the other case if it's the same SSI but this is weird because this is it's tricky let's say if because I might be equal to SN if middle is the same as I can lick it could be posed right it could be both this is hard so the only thing we can know that because target is smaller than the middle target is smaller than it if s 1 is in the middle we can only know that s 1 is not a target right because let's say there is a 1 &amp; 2 1 the middle is one a 1 &amp; 2 1 the middle is one a 1 &amp; 2 1 the middle is one right but we can if you want to search too we find the one we don't know where it is because the 2 could be replaced to 1 as it doesn't change the middle or change the eye or change the J so we only thing we know is that if the middle is not a target then the number same as it cannot be the same could not be the target so if for the other case is what we do we plus remove eye one step further ok now for the case of target is bigger than it we do the same this is the same ok so if the middle is bigger than it so if middle is bigger than it we can do the same right if middle is bigger than it then he must be the case like this so for the big one because it's bigger there was only one chance that did this so this is true but it's if it's smaller the middle is smaller than if and the other case then the middle is like this right and now if we say target is peak in the middle it might be here or here how we compare target with s1 if you speak minus one then you should be here give a smaller then you speak this one right so we come to know J 1 J 4 J I think I is should be use J if we compared to this one sure we used you stage it doesn't matter I think okay if miss figure no bigger than it then this must be here so we can be J 2 middle oh it's true so and now if else--if oh it's true so and now if else--if oh it's true so and now if else--if target is smaller than MJ with I with model okay so before the other cases we return true yeah for the one possibility that if the middle is the same as its high hmm we don't know where it is we do the same with plus we move the first one right maybe this one cannot be that possible cannot be the case so we add fast you find nothing we return false I hope this could pass actually I try to these problems of fear for a few times and oh sorry Hopi bears oh hope it bad okay let's submit yeah I just tried a few seconds ago OOP Oh God the error hmm why I return to ah God forget to change this yay it is accepted hmm good so that so from this problem I learned something that if we are going to search we need to break the problem down into some subproblems like for this one there might be like contained duplicates so we can just remove this constraint and suppose that there's no duplicate numbers and we can solve that by binary search easily and then we can add spite modifications and stop it mm-hmm hope it modifications and stop it mm-hmm hope it modifications and stop it mm-hmm hope it helps so next time don't forget to follow my subscribe my channel and yeah have a nice day bye
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,041
hey everyone welcome back and let's write some more neat code today so today let's solve the problem robot bounded in circle and this actually according to leak code premium happens to be the number one asked question by amazon of this year 2021 and this is actually a pretty unique problem what makes this problem difficult is that it's definitely different from most other leak code problems that we've solved before and it's been a few days since i uploaded so i'm a little bit rusty but that's okay so let's get into it we're basically given an infinite two-dimensional plane we have a robot two-dimensional plane we have a robot two-dimensional plane we have a robot that initially starts at the origin zero and faces the north direction and this robot can receive one of three instructions it can receive the instruction just to go straight by one unit so whatever direction it's facing initially it's going to be north it's going to go one unit in the north direction the other two instructions are not about moving but about rotating the robot so it can turn 90 degrees to the left or it can turn 90 degrees to the right so if it starts facing north you know that's one direction it can face west east and south so basically there's four different directions that this robot could face and so the robot is going to perform a set of instructions given in order and it's going to repeat these instructions basically forever and you know this could be an example instructions right go turn to the left twice and then go again and what we want to do is given these instructions we want to return true if and only if there exists a circle in the plane such that the robot never leaves the circle basically using these instructions does the robot get stuck in an infinite loop that's the question we're trying to answer and it definitely doesn't fit into many leak code problem patterns that's what's going to make this problem a little bit challenging to explain but i'm going to do my best so let's get into it so suppose that this is kind of a two-dimensional grid that we have and two-dimensional grid that we have and two-dimensional grid that we have and that these are the instructions right go turn to the left 90 degrees again go and if we repeat these forever are we going to get stuck in an infinite loop or not well let's just kind of simulate this at first so initially we start at the origin let's have our direction facing north right so initially we are facing north and so we want to go twice so what's going to happen well we're going to move by 1 then we're going to move by 2 we're going to be in this position still facing north and then we're going to turn left twice right so if we turn left once 90 degrees then we're going to be facing left if we were if we do it twice then we're going to be facing down right south and then we want to go again so then you know we go down one then we go down two then we start back at the origin the only difference is now instead of facing north now we're going to be facing south but so obviously we got back to the start right now my question to you is okay well we have we're gonna basically follow this exact same path but now we're starting at a different direction right now we're facing south right so my question is are we going to go through another loop just as we did before yes because this path is going to be some kind of vector on this two-dimensional grid right in this case two-dimensional grid right in this case two-dimensional grid right in this case the vector was up by two and then went straight down by two so in total the vector was a net difference of zero right it basically started where it ends and so even though first we were facing north now we're facing south it's gonna follow that same path it's gonna go it's gonna move by two and then it's going to go back in the same direction that it came from because this vector you know is a 0 vector it doesn't really move anywhere so with this at least yes we're going to return true because this robot is going to be stuck in an infinite loop now what if we had a different set of instructions what if instead of having this we just had a gg a go that means we'd start at the bottom we'd move by two up in the north direction right so that's what our vector would be just you know north by two and then you know that's our entire instructions right so then we're gonna repeat that again on the second iteration so then our vector is yes going up by two again and then going up by two again et cetera right that would be the instruction so in this case we'd return false because it's obviously not an infinite loop it's just going to keep going straight up it's not going to go it's not a cycle where it's going to return back to the origin right so that's the case where we return false now what if the actual instructions were uh go and then turn left twice what would be what would happen then would then it turn into a loop well let's take a look at what the vector would be the go is just going to be north by two right starting from the origin go north by two and so then we're gonna be here facing north and then turn left twice right so if we turn left twice then we're gonna turn to the left and once again we're gonna be turning down right so assume that this is kind of what our uh result would look like our robot is here they're facing down but we are we're not at the origin right so now if we run the instructions again what's gonna happen we're gonna go twice in this case we're gonna go down because that's the direction we're facing and then we're gonna turn left twice uh so we get down here we turn left twice we turn this way and then we turn this way so now we're back at the origin facing north so pretty much we just completed a loop it was two iterations right first we went north then we went south and now we're back at where we started and we're facing the same direction that we were when we originally got here so as you can see that this whole component this vector it changes two things it changes the position that we're at and it changes the direction both are important if we want to know if the vector creates a cycle or not so how do we know if it's going to get you know stuck in a cycle well one is if the position the change in position is zero meaning after an entire iteration through the instructions we started at the origin and we end back at the origin that obviously means the change in position is zero that means we have a cycle right the change in direction is also important suppose the position actually does change right we start let's say we start at the origin but we move up by four right and then we get into a different position right that's perfectly fine it could still end up in a cycle right it could still go back where we started but it depends if the direction changed or not in this case let's say the direction does not change we go up by four and then we go up by four again because the direction never changes and we keep doing that so basically the direction does not change right we change position but the direction doesn't change then we're going to return false because of course then it's never going to get stuck in a cycle it's just going to keep moving in one direction but the position changes and the direction changes then we are guaranteed to have a cycle because let's say okay in this case we went up by two right but let's say our direction or we went up by four but our direction changed 180 degrees so now we're facing down so then we're going to do the exact same vector going in the opposite direction we're going to end up back at the origin so in that case we kind of have a cycle of 2 right a cycle of 2 where the direction changed by 180 degrees so we get stuck in a cycle of 2. suppose the opposite happened or not the opposite but something else where instead of changing 180 degrees we do change 90 degrees what's gonna happen then well in that case it's you know we went up by four this time we're going to go right by four because initially the direction we're facing is right and then we're gonna change direction again by 90 degrees so let's say we're facing south then again we're gonna move forward by 90 degrees now we're going to be facing left and once again we're gonna go straight by four and then we're gonna get back to where we started so you can see that if the change in direction was 90 degrees uh and the position change then we're gonna get stuck in a cycle of four if it was the opposite if instead of facing the right this was changed facing to the left then we'd have the exact same cycle except on the other side of this two-dimensional grid we'd side of this two-dimensional grid we'd side of this two-dimensional grid we'd have a cycle of four so basically all the cases that i just went through you can see that the either we have you know a cycle of size zero or we have a cycle of size two or we have a cycle of size four so basically if we ran through these instructions if we do a simulation of these instructions four times right and we are back at the origin back where we started that means that we have a cycle right or what another thing we could do is basically run this simulation exactly once and then see that criteria that i mentioned if the position did not change then we have a cycle or if the position did change and the direction also changed then we are also guaranteed to have a cycle so that's what i'm going to do because that's with this solution we only have to iterate through these instructions up here only once so that's the way i'm going to do it but you could iterate through them four times and then manually check if we have a cycle or not but that is enough information for us to write out the solution okay so now let's get into the code so remember there's two things about our state that we're going to be maintaining one is the direction so the x direction and the y direction which i'm going to initialize as 0 1 what that means is that what direction are we facing we're facing the positive one y direction basically we're facing up we're facing north uh this is basically going to indicate where we're going to be moving uh and we're going to be looking we're going to be determining our position in these variables x and y so initially we're at the origin so we can say zero so if we let's say we got a go uh instruction in our instructions list basically to our position x y we're just going to add the these direction x direction y add them to here which is only going to end up updating the y value which is what we want because we're facing north right now so like i said i'm going to do this by just iterating through the instructions once so for every direction in the instructions what are we going to do well there's three cases right one is if the case is a g meaning it's the letter go we want to go another case else if this direction character happens to be a left that means we're rotating left and the last else is gonna be if it happens to be a right character an r uh there's only three cases so we can leave that in our else case and like i mentioned the easiest case is the go right the go is just going to tell us how we can update our x and y basically to the x we're going to add the direction x value and to the y we're going to add the direction y value now that's easy now next is the rotation right we're either going to rotate left or we're going to rotate right there's many ways to write out this code i'm going to show you a way that i actually did not come up with but if you recall from linear algebra what i do know is if you're rotating 90 degrees you're basically swapping the x and y uh values right you're basically making a perpendicular line so the direction x and the direction y are going to be swapped sort of right that's point to rotating it so let's copy paste these and just reverse it so direction x is going to be set to direction y is going to be set to direction x but one other thing suppose we're facing the up direction right we're facing uh the up direction meaning right now our direction is 0 1 x is 0 y is 1 and we want to rotate left so we're obviously going to swap x and y direction x is now going to be set to 1 and direction y is going to be set to 0. but 1 0 basically is the direction to the right x being 1 means we're facing the right but we actually want to be facing the left direction so what we're going to do instead is set direction x to the negative of direction y that's just uh you know the way that it works out you i forgot most of my linear algebra so i just had to read this in the discuss section but if you remember this is kind of how a property to rotate left works and to rotate right is just going to be the opposite so suppose you know we're facing this direction and we want to rotate right we would basically want to reverse this we want we don't want the negative to go here we want the negative to go here because suppose maybe we're facing the right direction and we want now to rotate 90 degrees to the right so we want to face the down direction and to do that we would have to set the direction y not set it to one but we'd have to set it to negative one so that's kind of an example for that but basically this portion is kind of just the math and this is just an easy way to write it i didn't want to write super long confusing code even though this is kind of hard to come up with but this is the entire code once we're done with that then remember what was our condition for returning true we're returning true if the x and y basically we end basically the position did not change if the position did not change the x and y is going to be 0 meaning we started where we ended that means we have a cycle so then we return true the other case is if the direction did change by at least one direction it doesn't matter what the direction is but it changed by at least one so how do we know that well we can check if our direction x in direction y is not equal to what it was initially what was it initially it was 0 1. so if it's not equal to 0 1 after one iteration through the instructions that means the direction changed if the direction did change that means we have a loop right i kind of showed that in the picture drawing and this is the entire code now it's definitely not easy to come up with you know code as readable as this on your own on your first try i was not able to either but some of the intuition i did i was able to explain it so i hope that this was helpful you can see that this is a very efficient solution not super easy to come up with though so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Robot Bounded In Circle
available-captures-for-rook
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * The **east direction** is the positive direction of the x-axis. * The **west direction** is the negative direction of the x-axis. The robot can receive one of three instructions: * `"G "`: go straight 1 unit. * `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction). * `"R "`: turn 90 degrees to the right (i.e., clockwise direction). The robot performs the `instructions` given in order, and repeats them forever. Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. **Example 1:** **Input:** instructions = "GGLLGG " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G ": move one step. Position: (0, 1). Direction: South. "G ": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. **Example 2:** **Input:** instructions = "GG " **Output:** false **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. **Example 3:** **Input:** instructions = "GL " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G ": move one step. Position: (-1, 1). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G ": move one step. Position: (-1, 0). Direction: South. "L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G ": move one step. Position: (0, 0). Direction: East. "L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. **Constraints:** * `1 <= instructions.length <= 100` * `instructions[i]` is `'G'`, `'L'` or, `'R'`.
null
Array,Matrix,Simulation
Easy
null
232
yo everyone this is Leo 232 Implement Q using Stacks I don't particularly like this problem I don't know if it's CU it's trivial or why but I just don't really like this problem that much but um I'll do it anyways because it's on the grand 75 list but uh we just have to implement a first in first out Q using two stacks um the que should have all the normal functions of a should I have all the support all the functions of a normal Q such as push Peak pop and empty so yeah not too difficult um so how we do this with two stacks um I kind of did an illustration so I can show you uh visually so let's say we have a Q right we add one first then we add two and then we add three so we add numbers like this right the number we're going to add goes here and this and the numbers that were that we first add are going to be on the mo rightmost side right so first in first out so using a stack essentially we're going to maintain that order by maintaining all the numbers um in a first in first out operation like this so when we pop from the stack we're getting the first number we put into the stack or into the quote unquote Q right so when we want to add a new number such as let's say four what we're going to have to do is we're going to take this stack and we're going to empty it into the second stack like this right then we add the new number four and then we empty this stack by popping everything and putting that into the first stack again and see how we maintain our um first in first out kind of fashion um using a stack and yeah that's how we use a two stack one stack basically just track keeps all the numbers in the proper order meaning first in first out um the second stack we only use when we want to uh basically append a new number to the queue um we have to empty it like this and then put it back in right so that we can maintain our uh first in first out kind of um ordering because that's important okay I don't think that's too difficult conceptually should make sense so we're going to start off by obviously creating our Stacks which are just lists in Python so now we're going to do the push thing which is what I just showed you um so we're going to say while um while the first stack has anything in it we are going to add to the second stack by pushing or by popping from the first deack okay now after we pop everything from the first stack and append it to the second stack that's when we actually want to add our uh the actual number or the actual value we're going to add to our Q our new number okay so add that to the second stack now we take everything from the second stack and pop it into the first deack okay so we're going to say self. S1 append self. uh let do. pop okay um now when we want to pop something thing the ordering is already in a first in first out fashion right that's why we're doing things like this when we're pushing um so everything should already be in a first in first out uh fashion so we can just pop and we'll get the um the number I'm saying q but really we're using Stacks but I'm just saying conceptually this is how our que works is where when we want to get the first uh item out uh from our que we're just popping from the stack to for that to happen um yeah now Peak is essentially like we're popping but I said we don't actually want to pop we just want to see what's at the top of the stack also the reason we do negative one right is cuz um we add the four then we add the three then we add the two and then we add the one back see how we maintain our first in first out ordering here but since this is the last number that's added to the stack um that's why we want to get whatever is at whatever is the last element of the list conceptually I'm drawing the stack um in a vertical fashion like this but like technically our list looks something like this right it looks like this right so that's why we want to do s return self dot S1 and then negative one so we can get whatever is the last element of the list since that's our how our ordering looks like in our list um so yeah uh now to check if um to check if our stack or rather our Q is empty well to check if our Q is empty we need to check if our stack is empty right um if there's nothing in the stack we're going to return true which means so technically when we call this function empty is going to check is there nothing in the stack if there's nothing in the stack it's going to return true which means it's empty okay so return not self uh S1 right return it's basically asking is there nothing in the for stack and return true or false okay pretty simple yeah uh I tried to explain explaining everything as best I could I think part of the reason I don't like this problem is it's just it's annoying to explain because technically um I'm talking about oh this is what the Q looks like but we're not actually using a q we're using a stack to implement the que so when I refer to the que I'm technically referring to the stack in this particular problem so it's just kind of annoying to explain this problem so that's probably one of the bigger reasons I don't like this problem but um yeah I tried showing that uh illustration here so I hope it's a little bit clear but yeah problem isn't really too bad it's just annoying to explain everything for this particular problem so yeah I hope this helped and I'll see you later
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
713
hey what's up guys this is john here so uh this time i want to talk about uh today's daily challenge problem uh number 713 subarray product less than k a pretty good medium problem okay so you're given like an array of positive integers okay so this everything every number is positive and it asks you to count and print the numbers of contiguous sub arrays whose the product of all the elements in the sub array is less than k and yeah so um i mean this problem i think it can be solved in uh dyna binary search solutions and but a better solution is just like using a sliding window like with two pointers so basically you know what's this problem is that you know the key observation is this uh we have this array here x okay so let's see uh with this range of the is this range of the data okay if this if everything basically if everything inside this sliding window is the uh it satisfies the uh satisfied the product of everything inside the sliding window here is smaller than k then we know the total number here of what is this is a 1 plus 2 plus 3 plus 4. basically that's the total number of the sliding of the sub arrays right who's because since the uh since uh the longer the sliding the bigger the sliding window is the bigger the product is right basically if this thing is uh smaller than k so any of the sub arrays inside of this inside of the sliding window is also like a valid sub array so basically so all we need to do is just that we just need to uh loop through each of the numbers here and we use that one as the right pointer okay because you know the reason being is that let's say we have a again we have this x here let's say everything inside here is like it's it satisfies the case here so at the beginning when we are at the first here the first one here the uh the left pointer it's pointing to here pointing to the beginning of the ray here so our right pointer is this one okay so if this one satisfy there are conditions here so then we have the total number the total subarrays we have is one and now the right pointers move to here and if this one also satisfy our conditions so basically we have two more like sub arrays so what are those two more sub arrays the first one is this element itself and the second one is that basically the length of this one the length of the current sliding window minus one that's why we have a two here and let's keep it keep moving right so now if we move to here if still it satisfy our condition so now we have three more elements here so one plus itself okay one this is the itself and the other one is this one is from the two to the third one okay and just and the last one is the three it's the total the whole array itself so the more we have this is four here okay so let's say we have four here and then let's say when we uh when the when we move to here when we're moving to here and the total product is exceeding is more it's greater than the k here then we cannot add five here right because that's not the valid the value of the move so basically if that's the case we just try to shrink the left pointer let's say if we shrink the left pointer to here okay to here and then this thing satisfy our current conditions okay and then instead of five here we need to add three okay and then we just loop through everything we just keep going until the right pointer reach the end then we have our total answer here cool so let's start coding here and we have uh what do we have a uh left equals to zero okay and then for right and number in enumerate nums okay and then we have an answer here answer is like the zero and we also need the current product okay equals to one things so every time we have a current product times uh is the card number okay while well current product is equal greater than k okay then we uh we do a current product divided by the uh basically we're trying to update the sliding window so uh to get to us a valid to get to the valid point here and the nums up the left okay and then we do a left plus one okay now we have a valid uh value sliding windows now we can simply add our answer right minus left plus one okay yeah and in the end we simply return the answer yeah i think that should work i mean no here okay so submit uh o here so when the k is yeah so basically when the k is equal to zero then it means that or even more also when the case equals equal or smaller than one that means that all uh it means that there's no sub array that is less than k in this case because every single element is greater than zero which is starting from one okay so if that's the case right i mean for everything inside here it will always be greater than the then than the k here so we'll keep we'll basically we'll just keep moving the left pointer so that's why we have a uh invited index exception here so we can simply do that if the k is equal or smaller than one here we simply return zero yeah cool so accept it i mean and yeah the space complexity right i mean the other part is o of n right that's for sure and how about this one here uh it seems like we have a nested and inside here but you know notice here notice that the left is always increasing so in total we have like also a n here a n of a while loop here inside of the for loop here basically would it will not like a be going to be a nested o n loop here so it's going to be a o n plus or right so in total it's also o and all of n yeah i think that's pretty much for this problem you know i think one things i stumbled a little bit was the uh you know at the beginning i was able to find out like the you know for this kind of things here uh if we have a stable a valid uh sliding window here i mean i was trying to get everything inside here basically that's going to be the end times and uh n minus one divided by two that's a total number total like slight total number of uh valid numbers here but then i mean that's the only one part right but how about if we're trying to move the sliding window right you're trying to move the sliding window here how can we update that okay i mean we can update that i mean because before i was trying to use like the left pointer i was trying to use the left pointer in the for loop so basically i was trying to see from here onward from this point from this left pointer here what is the biggest uh window sliding window we can extend from here okay but then that's not a right solution because if we are trying to go into here we're gonna cover some duplicated like duplicated uh numbers along the way here and yeah and here if we're trying to count from the left point side right we have to count everything but if we are counting from the right point side all we need to count is the how many new sub arrays this new other this right new right pointer number can give us this is definitely a better solution okay cool guys i think that's what i want to talk about for this problem yeah okay thank you so much for watching this video guys stay tuned see you guys soon bye
Subarray Product Less Than K
subarray-product-less-than-k
Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`. **Example 1:** **Input:** nums = \[10,5,2,6\], k = 100 **Output:** 8 **Explanation:** The 8 subarrays that have product less than 100 are: \[10\], \[5\], \[2\], \[6\], \[10, 5\], \[5, 2\], \[2, 6\], \[5, 2, 6\] Note that \[10, 5, 2\] is not included as the product of 100 is not strictly less than k. **Example 2:** **Input:** nums = \[1,2,3\], k = 0 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `1 <= nums[i] <= 1000` * `0 <= k <= 106`
For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.
Array,Sliding Window
Medium
152,325,560,1083,2233
1,611
hello and welcome to another video in this problem we're going to be working on minimum one bit operations to make integers zero and you're given an iner n and you must transform into zero using the following operations you can change the rightmost bit or you can change the I bit in the binary representation if the IUS oneth bit is set to one and IUS two through zeroth bit set to zero return the minimum number of operations to transform n into zero so in the first example they give you three and three looks like this so what you want to do is you want to turn this one into a zero and then you can turn this into a zero right so we're going to use the second operation then the first now we have a six so for a six what you want to do is you want to turn this into a zero then you want to turn this into a one so it's two operations then you want to turn this into a zero and that's four operations total so this problem is honestly uh very hard to get like without doing this before I feel like so I think if you got asked this on an interview realistically like it would probably be um kind of hard to do and I'm going to try to explain as best I can so what we need to First figure out is what these operations are exactly so the first operation is pretty straightforward right we can just change the last bit from like a zero to a one or a one to a zero and so on so we can just flip this bit as much as we want now the second operation is the kind of confusing one and so what this means essentially is if I want if I have a number like this in order to change this bit what I need is I need the bit to the right of it to be a one and then I need yeah I need the bit to the right of it to be a one and I need all the rest of the bits to be zero and notice there's really only one bit that you can have this with because if I need the right of my bit to be a one and the rest of it to be zero you can't have multiple bits like that right you can't have two numbers that the bit to the right of it is one and the rest of it is zero because like if the if this was like this let's say even if it was Zero I can't have something else here with a one right like because then we'd have two ones so notice that for this operation this will really only work with one number at a time also notice that another important thing to notice is if we're able to do this we're basically able to go back and forth with our logic so if we can change six to zero we can take these exact steps and turn the zero into a six because these bits are these operations are flipping a bit from one to zero from 0er to one so you can basically do you can do it back and forth so if we take a look like if we have zero we can literally take this reverse so we can say like okay let's do operation one change this into change this 0 into a one then we'll do operation two change this into a one then we will do operation zero again and then finally we will do operation one and so we basically did the reverse another thing so one last thing is since you have two operations and those operations change usually a different bit right so one operation will change one bit and one operation will change the other bit you basically never want to do the operations uh you never want to do one operation twice so you're going to want to do like one two and then one two and so on because if you do one or two you basically just reverse what you did right so it's kind of redundant so you're never going to have it where you are going to do um the same operation twice so we need to build some more intuition for this unfortunately because it's kind of a tough problem but first of all to realize the first step we need to realize is to change a bit to zero like let's say we have something like this to change this bit to zero we need it to look we need our number to look like this we need the number to the right of it to be one and then the rest of it to be zero so if we have a number like this to change this bit to zero what it's going to look like is we need to change this bit to one somehow we need to like do some operations to do this then we need to change this to zero and then we need to kind of do this again right to change this to zero we need to get this to be a one somehow and then change this to zero and then same thing we can just do our operation uh the easy operation to turn the rightmost bit change this to zero and fin change this to zero so we're actually going to walk through this whole thing starting with this number here and we're going to build some intuition and I'm going to write down like Steps we're doing so we're going to go all the way from this to zero so this is eight and you're going to this is going to be important to look at all of our cases so remember we can do operation one or two but we can't really do operation two here because in order to do operation two you need a format of one and some zeros so because we can't do operation two we're forced with doing operation one so we're going to change this into a one and I'm actually just going to label it uh actually yeah let's label it so we'll just say like 0o one we'll write this we'll write a few of these actually instead of 0 one so we're going to say we did Operation one here then in theory this should be like 1 two one two something like this because like I said you never want to do the same operation twice so this is going to very easily get us from this to the next one so we want to do operation two now ideally so operation two we can do we can change this bit because everything the bit to the right of it is one and everything to the right of that is zero so let's do that so we're going to change this to this now we want to do operation one because we don't want to reverse so operation one we'll just flip the last bit then we want to do operation two we can only change one bit this bit over here so we're going to say 1 one 1 0 or 1 one is Zer then we want to do operation one so 1 one 1 um operation two so we can change this bit to a zero so one 01 operation one okay now finally we have what we want right we have our number in the format we want to change this so now we can actually change this into a this now we're going to do this again so we're going to start at four this is four and we can't this is going to be the same thing and it's going to take us four steps so we're going to do operation one operation two so operation one is going to turn this into one operation two will turn this into a one operation one will turn this into a zero oops there we go and now we have exactly what we want where we can turn this into a zero so operation two 0 1 0 now we're going to do it again so we're almost done here so we have 0 1 0 so this should take two steps and so we're going to do operation one and then finally operation two and we have one last thing to do to turn this into a zero we'll take one step right so to turn this into a zero we will do operation one so notice another thing now that we figured out to turn a number like this is 2 to the K to turn a number from 2 to the K to 2 to the K minus one so 2 the k 2 the K minus one takes how many operations so this took eight right to turn 8 to four took eight to turn four to two took four to turn two to one took one and to turn one to uh zero took Z took one so we can notice from here and this is always going to be the case you can try bigger numbers that to do this right takes two to the uh K operations and to turn a number 2 to the K all the way down to zero is like let's look at this so it's 2 the K plus this is 2 the K minus1 right plus 2 the K minus 2 Kus 2 all the way down to 2 to the 0o right so this is a um this is a series and we want to figure out like what the actual summation of this series is quickly so if you think about it like let's say we have a number here so this is some bit if you think about it this is the 2 to the 3 power right so this is the two to the three power and this took this bit symbolizes eight so if this bit is on this symbolizes eight and this is indeed did take us eight this bit symbolizes four this bit symbolizes two this bit symbolizes one so if you add all these up right so if we add 1 0 plus 0 1 0 this is how many operations it took to go from R8 to 0 right so this adds up to 1111 and what is 1111 it is one and then all zeros minus one so this is two to the k + 1 minus 1 because essentially you have + 1 minus 1 because essentially you have + 1 minus 1 because essentially you have to turn a number down from one power to the next power so to take a two to the sum power and make it go down to zero it takes 2 the k + 1 minus the k + 1 minus the k + 1 minus one okay now this is if we had a number that was just one and a bunch of zeros what if we didn't like let's say we had also notice if we actually write down these numbers so let's do that as well this will give us more intuition so this is eight this is uh I do this right yeah this is eight now let's take a look at actually yeah actually what we need to do is we need to get all of the numbers in here so we're going to take all of the numbers that are in here not counting the last bit because last bit's all always one so this is eight let's say let's take a look we have one we have three we have two we have uh six yeah six 7 3 2 right so we have every single number from 1 to seven now let's look over here same thing we're going to disregard the last bit so we're going to disregard this bit we're look at the first two bits so we have one we have three we have two same thing we have every number now same thing disregarding last bit we have uh yeah well there's only one number here I guess there's only one right because every yeah and then there's only there's nothing here but essentially to get a number down to the one before it we basically made every other combination of numbers that we could right with this one bit so with this bit on we made every single combination possible here so if our number was remember these operations are reversible right as we said before so if you wanted to go from here to here we can also take these exact operations and go backwards so for more intuition if we started at one of these numbers it would be faster to turn this into um into zero than this number here right because this like let's say we're at this step here like let's say we start with this number here well to turn it into zero we would have to go to here which only takes four operations and then the rest of it but to turn this into zero we would need eight and then four and then two and so on so whenever you have a number that's like 1 0 1 let's say this is basically we can write this down the number of operations to turn 1 0 into zero minus the number of operations to turn one1 into zero so that we have like a recursive case right we can essentially say okay we can get the most significant bit we can figure out how long it takes just that into zero like if this whole number was just like one and all ones with this um thing here and then we can say that whatever it is that minus this part here right so we're going to get the most significant bit we're going to use this formula and then we're going to turn that most significant bit into a zero and then we will recurse to this so that's the other kind of tricky part is when you have a number it's actually faster to turn something with a bunch of ones in here already into a zero than turning this into a zero and it's also this is better to do than just the other way you could have done it oh can you do it yeah the other way you can do it I guess is you can turn the numbers into zero starting at the right number at a time but this is going to be worse so you can like turn this into a zero then turn this into a zero I think because for the operations you're only counting the number and the numbers to its right but this is going to be slower than just saying okay let me just use this equation here to figure out where's my most significant bit how much does that take to turn that into a zero then I turn it into a zero and then I subtract this part here and so hopefully you can see now from here that anything that is not this that has this number of bits is going to take less time to turn into zero because we went from here to here and then all the way down so we basically saved like if we started with this number we saved ourselves four steps if we start with this number we saved ourselves three steps and so on so the worst number to turn into a zero is this here because we have to build up everything else same thing here right if we're turning this into a zero this is going to take less than turning this into a zero because you have to go from here to here so that's the intuition behind it so now we can kind of write down our algorithm it's essentially this right here right so the number of operations to turn something into a zero is the number of operations that turn that most significant bit into a zero minus the number of operations that turn this into a zero into turn the rest of it and to get the most significant bit now we can talk about this briefly it's going to be pretty easy so let's say we have like something like this all we have to do is we'll just store a copy of this number and we can just keep shifting it to the right until it's zero and then we can just add one to the most significant bit so the way to do this is we can initialize first of all we can have like a base case of like if n is one or zero then we can just return n right because to turn one into all zeros we can just change the last one and if it's zero it's already Zer that's their base case but let's say we were trying to figure out like what's the most significant bit here what's the power so this should be two to the three so this should be a three so the way this is going to work is we are going to initialize our most significant bit toga1 because we want it in um in base zero and then we're basically going to say okay while this number still exists let's just shift it right and let's add one to the most significant bit so what's going to happen here is we're shift Right add one to the most significant bit shift Right add one shift right Right add one shift Right add one so now we have 1 + 4 which is add one so now we have 1 + 4 which is add one so now we have 1 + 4 which is three then when we have the most significant bit we can just do our equation right where it's two to the most significant bit + one so it's 2 to most significant bit + one so it's 2 to most significant bit + one so it's 2 to the k + the k + the k + 1 minus one is our actually uh yeah this formula over here and then we need to subtract the rest of the number so if our number was 11 one01 then what we need to do is we need to take this bit turn it into a zero the way to that is if we know our most significant bit is three in this case it's very easy to do you just take a one you shift it left three times so you would get something like this and then you just um exor it with your number right so if you exor this with your number you would get 0 1 01 so we got rid of our most significant bit and then we just recurse and subtract that and that's basically our code so hopefully you get it's not super easy and this is this I would recommend yeah like to learn this you basically basally have to like play around with it and learn these patterns and this is not super easy to find but you can kind of if you bring this down you can kind of see that like okay if this takes eight this takes four this takes one and so on the way to do it is you just add up all of them and then it gives you a bunch of ones and the way that is just the next one and all zeros hopefully you can see that definitely not an interview question I'd be asking but let's code it up so we can say if n is less than or equal to one we can just return n because to turn one into a Zer is one to turn Zer into Z it's already a zero now what we have to do is we have to make a copy of n so we'll just say like xal n and then we'll say m bit equals 1 we'll say while X is non zero let's shift it right and let's add one to the most significant pit and then finally let's return two to the most significant bit + one remember the most significant bit + one remember the most significant bit + one remember 2 to the k+ 1 minus 2 to the k+ 1 minus 2 to the k+ 1 minus one so that part is that then we also have to subtract the recursive case right so we have to subtract self. minimum one bit operations and what we have to call it is on RN xord with one shifted left most significant bit times r that look and there we go so it's pretty efficient so let's talk about the um yeah the other thing is honestly uh if we take a look like here uh the constraints is 10 to the N but they I mean you do kind of get a hint of like you just want to work with bits so you don't really care that the number is too big you're never going to like use the whole number you're just going to work with bits so let's figure out the time and space for this one but yeah this is definitely one like if you get asked this in an interview question probably pretty unrealistic to do given time constraints so this is honestly just like a cool one to work with bit manipulation but not a super good interview question so I think they don't show down votes anymore unfortunately but I think I would expect this one to have a lot of down votes because it's not super relevant to coding interviews in my opinion okay so um yeah so let's go through the time but everything else is still kind of useful to see these patterns as kind of useful and things like that so for the time what are we doing right we are finding the most significant bit in our number so to get the most significant bit essentially if we have a number of like n to get the most significant bit you're basically shifting one to get to the leftmost bit so you're going to have to go with every s you're going to have to go through every single bit of the number so that's going to be log n right to get it so this while loop is going to take log n um and then the number of recursions is if you think about it you are changing one every one bit one at a time right so if a number has like n Bits you're changing all the on to zeros one at a time I think there might be a way to do it like a little bit more efficiently where if you have like ones and then zeros you can say like you can skip some um but honestly I don't want to spend any more time on this problem so yeah so anyway this while loop is log in and since we're changing one bit at a time uh you would also have to multiply by the number of bits in the actual um number again right so we're going through all the bits once and then in the recursive case we're going through all the bits again so it be like log squ n which is still pretty good right because like 10 to the 9th I don't know what the log is let's say let's call like 100 then this is like you know 10,000 or then this is like you know 10,000 or then this is like you know 10,000 or something which still really fast um hand space so this is the recursive stack frames um because we don't have any other variables so this would be log of n space because essentially you're recursing down one bit at a time so this would be login um recursive set um and yeah I think that covers everything you wanted to cover so hopefully you liked it and if you did please like the video and subscribe to the channel but yeah definitely not a great one to uh definitely not a great one to ask on a coding interview so but hopefully it was useful and if it was please like the video and subscribe your channel and I'll see you the next one thanks for watching
Minimum One Bit Operations to Make Integers Zero
making-file-names-unique
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`. Return _the minimum number of operations to transform_ `n` _into_ `0`_._ **Example 1:** **Input:** n = 3 **Output:** 2 **Explanation:** The binary representation of 3 is "11 ". "11 " -> "01 " with the 2nd operation since the 0th bit is 1. "01 " -> "00 " with the 1st operation. **Example 2:** **Input:** n = 6 **Output:** 4 **Explanation:** The binary representation of 6 is "110 ". "110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010 " -> "011 " with the 1st operation. "011 " -> "001 " with the 2nd operation since the 0th bit is 1. "001 " -> "000 " with the 1st operation. **Constraints:** * `0 <= n <= 109`
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
Array,Hash Table,String
Medium
null
74
hey guys how's everything going I'm Jay sir I'm not tech lead today let's take a look at number 74 our lease code search a 2d matrix we're asked to write an efficient algorithm that search for a value in an MN matrix the matrix has following properties the first one integers you know each row are sorted from left to right the first nature of each row is greater than the last integer of the previous row so the order of all the numbers will be just from left to right when the one way is done it will move be moved to the next night right yeah so in this order we are supposed to search for a target if it is if the target exists we output true if not we return false well it's pretty straightforward it was just a typical I think it is a typical binary search problem like first we do we detect which row the number should be in like we searched we took the first number of each row as array like 110 23 4 3 we choose to the middle 10 is smaller than 10 so it must be in the first half and when we are sure whether which row it is in we can now do a second round of binary search and find the target right so it's actually two round ok let's do it a late I could be 0 let J equals matrix news right for the first round of binary search we're not to return the result immediate immediately all right we are going to find the rent wrench for 3 we choose the middle 10 if it's more than 10 so it must not be in 10 which means we are gonna throw the right half right okay so when we are choosing the middle of the inj we need to choose the ceiling not the floor if you choose the floor we need to keep it right if it's bigger than ten we need to keep ten also it might be in this row that will be at what each to the infinite look so which is the ceiling and through the right half okay the search was stopped when I meets J that's the row which with the target should be in okay well Iseman and J now we choose the middle as we said the middle should be math ceiling choose the ceiling throw right half okay cuz number equals matrix the head right so middle zero if a number is smaller than target if it's more than target then we should move i right and the I my the middle of my the middle and I yeah we just threw the left half okay I should be I middle what if the equals let's check first check if equals yeah then there is it return true and it's done if it's a smaller then we said item it'll yeah for the right if num is bigger than the target then it should be in the previous row we're safe to move J to middle minus one so when I meets Jake Rowe is targeted and then we do a second round of binary search to search a target in the specific row right let's K equals zero let's l equals matrix I got 9th minus 1 here's a problem matrix I don't know it whether it is exists or not it's if the matrix is empty then this would be undefined and then this will be generating error so let's take consider of the edge cases now L should be valid and then let's search for this time about a research whether the number exists or not so when I meet CA it there is 2 possibility that the number is to possibly least integrity right so it will won't stock each walk well only stopped when I surpassed J now this time we can just safely choose the math the floor or the sitting we either one is okay let's choose the left one oh god this should be K and L if nom equals target return true if num is more than target big so then we can safely set I equals middle plus 1 for the other case we can safely check Jake was middle minus 1 so this is the basic form a pattern search and at last if we come to this line of code then nothing to check anymore we return false we run the code time the first search we costs log em to search the row and then we log n right so it's actually log MN we submit we use several variables to store being stored index the space will be constant oh we got time in limit exited hmm wait a minute okay we get the seal okay oh god my bear should be I submit again yeah we're accepted and it's fast enough so it's pretty straightforward just pay attention to how we handle different kinds of binary search for the first one we need to keep the number which is smaller than it might be the solution so we choose the seal and the throw the right half and he stopped when I miss J but the next one we will search the existences number that's why we all keep search until left to surpass the right and we keep the floor it doesn't matter we keep the floor here or not actually because we will throw we will give up the middle anyway so yeah this let's just try if we use sale if used if we choose this you know it doesn't change the it doesn't change yeah but it I don't know why it's just a slower yeah anyway so that's all for these problems hope it helps and see you next time thanks for watching bye
Search a 2D Matrix
search-a-2d-matrix
You are given an `m x n` integer matrix `matrix` with the following two properties: * Each row is sorted in non-decreasing order. * The first integer of each row is greater than the last integer of the previous row. Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_. You must write a solution in `O(log(m * n))` time complexity. **Example 1:** **Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3 **Output:** true **Example 2:** **Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 100` * `-104 <= matrix[i][j], target <= 104`
null
Array,Binary Search,Matrix
Medium
240
1,754
hi everyone welcome back to the channel today let's solve the median question from the contest largest merge of two strings and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic clinical questions with clear explanation animation and visualization now let's look at a question in this question we are given two strings word one and word two and we want to construct a string merge in the following way while either word one or word two are not empty and we can choose one of the two following options if way one is now empty then we can append the first character in word one to merge and then delete it from where one and on the other hand if word two is not empty then we can append the first character in word two to merge and then delete it from word two and we have to return the lexicographically largest merge that we can construct and here is the definition of lexicographically order for example one word one is c-a-b-a-a for example one word one is c-a-b-a-a for example one word one is c-a-b-a-a and word two is b-c-a-a-a and word two is b-c-a-a-a and word two is b-c-a-a-a and the largest lexicographical emerge we can get is cb cab and then 5 8. and for example 2 with a given world 1 and world 2 this will be the largest lexicographically merged string that we can get and the data constraint for this question the length of word one and where two would be less than three thousand to solve this question we can use a very intuitive and straightforward approach which is basically a greedy algorithm since we want to get the largest merge of two strings lexicographically so we just always pick the larger character among the two words and the tricky part is that if two characters in the two words are the same then we will pick the lexicographically larger string and in python this can be easily done just by comparing the two strings y1 and where two and then we will merge the remaining characters at the end now let's look at the code returned in python would be very straightforward so first create a variable called merge which will be returned at the end and then while where one and where two are not empty then if where one is bigger than word two let's go graphically then we will pick the first letter from where one add it into merge and then remove it from where one otherwise we'll pick a letter from word two add it into merge and then remove it from where two and then at the end add the remaining characters from either way one or word two into merge now let's see the code in action okay and here we'll be looking at example one word one is c a b a and word two is b c a and starting from the first letter c is bigger than b so we will add c into merge and remove it from word1 and the next b is bigger than a so we will add b into merge and remove it from where two and the same c is bigger than a so we will add a c into merge and remove it from word two okay now the first letter in both words are a so we have to compare the lexical graphical order of two strings and since there is a b in word one so where one will be bigger than word two in terms of the whole string so we will pick the a from where one add it into merge and then remove it from where one okay and now b is bigger than a so we will add b into merge and remove it from where one and now all the remaining characters in word one and word two are all a's so we will just concatenate all the a's into merge so the largest merge string we can get is c b c a b and then five a's and this will be the final output for this example and this will conclude the algorithm finally let's review so the key algorithm to solve this question is the greedy approach that we always pick the larger character lexicographically among the two words and if the two letters the two characters are the same then we will pick the lexicographically larger string and then we will merge the remaining characters at the end the time complexity of this approach is linear and the space capacity is constant and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one
Largest Merge Of Two Strings
largest-merge-of-two-strings
You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options: * If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`. * For example, if `word1 = "abc "` and `merge = "dv "`, then after choosing this operation, `word1 = "bc "` and `merge = "dva "`. * If `word2` is non-empty, append the **first** character in `word2` to `merge` and delete it from `word2`. * For example, if `word2 = "abc "` and `merge = " "`, then after choosing this operation, `word2 = "bc "` and `merge = "a "`. Return _the lexicographically **largest**_ `merge` _you can construct_. A string `a` is lexicographically larger than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. For example, `"abcd "` is lexicographically larger than `"abcc "` because the first position they differ is at the fourth character, and `d` is greater than `c`. **Example 1:** **Input:** word1 = "cabaa ", word2 = "bcaaa " **Output:** "cbcabaaaaa " **Explanation:** One way to get the lexicographically largest merge is: - Take from word1: merge = "c ", word1 = "abaa ", word2 = "bcaaa " - Take from word2: merge = "cb ", word1 = "abaa ", word2 = "caaa " - Take from word2: merge = "cbc ", word1 = "abaa ", word2 = "aaa " - Take from word1: merge = "cbca ", word1 = "baa ", word2 = "aaa " - Take from word1: merge = "cbcab ", word1 = "aa ", word2 = "aaa " - Append the remaining 5 a's from word1 and word2 at the end of merge. **Example 2:** **Input:** word1 = "abcabc ", word2 = "abdcaba " **Output:** "abdcabcabcaba " **Constraints:** * `1 <= word1.length, word2.length <= 3000` * `word1` and `word2` consist only of lowercase English letters.
null
null
Medium
null
76
Minimum Window Substance So basically we have two strings given soti and we have to find d minimum window in s which contains all d characters in t so first of all we will create a mapping of which character is occurring how many times so that On the basis of this, we can get the window valid date, then we will start the starting window, if we go to the statement with express starting valid window, then it means that there can be a possible output, then we will update the result, then we will try to see if we can leave it and as much as possible. We will do as much stringing as we can so that we can get a smaller window and will keep updating the results from it. We will start getting it and we will return it.
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
374
hi coders today we will solve two binary search problems in the first one we will apply binary search on the indices of the array while in the second one we'll apply binary search on a number range the first problem is problem 704 binary search on lead code i am discussing this problem for two reasons first to familiarize with how to apply the template second if we know how to search for a target element in a sorted array of known size it will form bases for an important question that we'll discuss in the following video where we need to search for a target in a sorted area of unknown size as i mentioned earlier we will be using templates to solve problems here we will use template i have added a link to the template in the description in this problem we are given a nums array which is sorted in increasing order and a target element so the nums and the target are the input parameters the aim of the problem is to search for the target element in the nums array if the target exists then we need to return the index at which it is located otherwise we will return minus one we need to write the algorithm in login time complexity and we know we can achieve this logarithmic complexity using binary search let's see what changes we need to make in template one here the law points to the zeroth index that is the start of the array and high points to array.size 1 that is the end points to array.size 1 that is the end points to array.size 1 that is the end of the array this range is good because this is where we need to search for the target element next we need to add a search condition if the middle element is equal to the target then we need to return the middle element and we are done the else if block here is to shift the search range to the left and we need to shift our search range to the left if the middle element exceeds the target that is all the elements to the right of the middle element would be greater than the middle element and since we have already checked the middle element the new range would be low to mid minus 1. by the same logic if the middle element is less than the target we'll shift our search range to the right this scenario is handled by the else block by default if we did not find the element we have to return -1 as element we have to return -1 as element we have to return -1 as mentioned in the question i have written the code that we discussed so let's try to submit it so this works i've added the code link in the description now that we are done with our first problem let's solve our second problem number 374 guess number higher or lower on lead code the game that we are playing is a guessing game we pick a number from 1 to n and we need to guess that number every time we guess a number wrong we will be told if the guess number is higher or lower than the pick number this information will be provided by a guess function call which can return -1 guess function call which can return -1 guess function call which can return -1 and 0 minus 1 if the guess number is greater than the pick number one if guess number is lower than the pick number and 0 if the guess number is equal to the picked number and we need to return the pick number one way to solve this problem is by doing a linear scan for all values one by one from one to n and check if the guess function call for that value is equal to zero if it is then we got the answer and we need to return that but note that we are wasting the information here we don't care if that number is higher or lower than the pick number we only care if it's equal to the pick number that is minus 1 and 1 are equivalent if we recall the first question in which we use binary search template 1 to search for a target element in an array and use that target value to shift ranges either to the left or to the right doesn't the pick number here look like the target it's just that the target is hidden but please note that the comparison reserved for the target can be determined using the guess function returned values that is -1 and 0 that is -1 and 0 that is -1 and 0 enabling us to alter our search ranges if we think about the range on which we can apply binary search the answer value can be among 1 to n which is a monotonically increasing number set so we can take 1 to ns the range and apply binary search on it let's try to alter our template one as you can see the input parameter is in here return type is here int since the range is from 1 to n low will point to 1 and highway point to n let's make a guess api call on the mid so we can reject half of the range of the target that is a picked element is not equal to the mid i have stored guest function called result in res variable if res is equal to 0 guess number is equal to the pick number that is mid is equal to the pick number and we can return mid so this block is handled the else if block will shift our search range to the left we need to shift our search range to the left of the middle element when mid is greater than the target that is guess number is greater than the pick number which happen when res is equal to minus 1 so the search condition here would be res is equal to minus 1 and here it would be res is equal to 0. so this is done in the else block we'll shift our search range to the right if the mid is less than the target that is the guess number is less than the pick number we can see that happens when res is equal to 1 there are only three values that res variable can take 0 1 and minus 1 we have already covered 0 and minus 1. so we can use a else block here we don't need to use a else if block by default we can return any value other than 1 to n i am returning here minus 1 by default ideally the control should not come here because we are given that the number is picked from 1 to n and control will reach here only when no number is picked from 1 to n i have written the code that we discussed let's try to submit it so it works i've added the code link in the description that's all for this video the following video will solve a binary search problem on a sorted array with unknown boundaries thank you
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
20
all right so today we're looking at leeco 20 valid parentheses i'm going to first start by creating a stack and then i'm going to create a dictionary filled with the parentheses i already did that because it's a little hard to type out and then we're going to say for the character in the string if the character is in the dictionary then we're going to do stuff but if it's not that means that it's a opening bracket and we're going to want to append that to the stack so if it isn't a dictionary that means that we can just take the top element from the stack but we can only do that if there's stuff in the stack but if it's not then we can just assign the top element to be some random character so it automatically fails the next step is just asking if the top element is not equal to the dictionary with the character as the key so that means it's false but at the end if all is well and the for loop finishes then we can just return not stack because we want the stack to be empty by the end of the for loop and that's how you do valid parentheses
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
1,326
hey what's up guys sean here so this time let's talk about another dp problem uh number 1326 minimum number of tabs to water to open to water a garden so basically you're given like a number of gardens right from zero to five and also another array of the tabs so at each tab on each tab the range this tab can converter is from the index itself plus the range itself basically the value of this the value of the of this element here is the range starting from the current index so for example four here right from starting from index to start from index one it can go right to range four and this side also four right so that's the range okay so how are we thinking about this problem right so you know we can think it in this way right so every time let's say we just iterate each of the type here right so we can get the left and right with the current index and the number of the range itself we can get the left and the right basically that's the uh that's the range this current the current like a type can convert right and then we define the dp here right the dpi so what does dpi means the minimum like uh tap need are needed to be watered fro to garden eye here to garden eye so d so dp2 means right dp2 means how many gardens right so from garden zero to two right what's the minimum types we need for dpi right okay and then what does the dpi means right so let's say every time we have this range from left to right and then we know with current uh with current like tabs uh to let to in the range of left to right in the range left to right let's say there's like a j here right j so any dpj here right any dp j right so because the current one the current uh tab will take one right what would take one how about the previous one right then the previous one will be like dp left right so that's uh dp left means from whatever we it took whatever it took to water the uh to water until the left one so now since with the current type all we need is a plus one right because with the plus one we know we can range from we can water all the range from left to right so within the left and right all the dps we can update it with the current dp left and plus one right and in the end we just check the dp uh n here yeah that's the kind of brutal force brute force dp solutions and okay let's try to code it here okay so dp right so since we're trying to get the mag the minimum so we're gonna initialize all the values to uh to system max right and then the value will be m plus one right because we need the first one to be a dp0 to be zero basically that's the base case if it's zero if it doesn't have any gardens we need zero uh zero tap to water it right and then we just loop through for i in range n right so for each of the top here uh for each of the tab yes sorry actually the uh let's see so we arrange the uh the range here the top range right in the enumerate numerator like ranges right we first we get the left and right so what's the left is gonna since we are we're bounded right from the zero to the uh of the left and also the end to the right so whatever over this uh this two side boundaries we don't care right so then we need to do a minimum here i'm sorry a maximum right since we're doing a boundary with zero and the current i minus type range right so that's our left bound boundaries here how about the right boundary is going to be minimum right on the other minimum and right that's the left the right boundary i plus tab range right then for j in range left and right uh since we're doing our left plot since the 2 is exclusive so we it's to write plus one for every uh element in the range plot left to right and then dpj right equals to what it goes to the okay so since we're doing the minimum right so we're gonna do like minimum every time we do a j here and then what so dp left right so every time if we have the left until the left right and not then we know if on the left we took like a k times so then the next time we only need to use k plus 1 to water until the current j because the current range can convince everything from left to right so and in the end we just return dpn right dpn here dpn if right if this dpn is smaller than the system max right because that's we are sure with this like dpn until this end has been watered right otherwise right we just return a minus one right and that should do it yeah cool yeah it's a it's not a very hard problem but it takes some time to think of a way of doing this dp you know this is not the quick the fastest solutions but i think this is like the a more intuitive way of thinking about this basically for each of the range here we got the left and the right and then here's the idea so within the range left and right since we caught uh define the dp here so dp means starting from zero to current j what's the minimum tabs we need to water everything right so since we have left and right and for all each element in the range left and to right then we can get the dp lab basically how many types we need to water until left and then we plus one that's the value in the dpj right and we try basically all the ranges possibilities and we keep updating the js in the end we'll get the dpn yeah cool i think that's that should do it yeah i think that's everything i want to talk about this problem uh cool guys uh thank you so much for watching the video and see you guys later bye
Minimum Number of Taps to Open to Water a Garden
sum-of-floored-pairs
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-indexed) means the `i-th` tap can water the area `[i - ranges[i], i + ranges[i]]` if it was open. Return _the minimum number of taps_ that should be open to water the whole garden, If the garden cannot be watered return **\-1**. **Example 1:** **Input:** n = 5, ranges = \[3,4,1,1,0,0\] **Output:** 1 **Explanation:** The tap at point 0 can cover the interval \[-3,3\] The tap at point 1 can cover the interval \[-3,5\] The tap at point 2 can cover the interval \[1,3\] The tap at point 3 can cover the interval \[2,4\] The tap at point 4 can cover the interval \[4,4\] The tap at point 5 can cover the interval \[5,5\] Opening Only the second tap will water the whole garden \[0,5\] **Example 2:** **Input:** n = 3, ranges = \[0,0,0,0\] **Output:** -1 **Explanation:** Even if you activate all the four taps you cannot water the whole garden. **Constraints:** * `1 <= n <= 104` * `ranges.length == n + 1` * `0 <= ranges[i] <= 100`
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Array,Math,Binary Search,Prefix Sum
Hard
null
72
Hello hello friends welcome back to my channel home or doing great and space administration difficult my channel please do subscribe my favorite playlist subscribe statue subscribe research by research different on president of the rings for all players in description subscribe this video Distance That Given There Words Women And What To Find The Minimum Number Of Operations Request You Can Give Very Sorry This The Calling Operation Adhir They Strike Media Can Give One Example Top The World Was His House And What Does And OS Right Cross Left Sukhbir and Sukhveer What does it is the president of you will give you the way to delete that and put all the and face in front of subscribe dhund hi dhund total number of operations at do the minimum number of subscribe button not wake up sid And subscribe to RSS feed subscribe that when like what pimple digital spy angry and 10 48 thousand balance what they are taking x-ray Switzerland side subscribe now taking x-ray Switzerland side subscribe now taking x-ray Switzerland side subscribe now so let's get them and experiment for going through subscribe during subscribe remember and subscribe the Channel Please subscribe and subscribe the Difference from word and Jhalawar saaf not r physical length york and where are index robbers have traveled yes subscribe channel subscribe word is not difficult word of what they do it is the subscribe must note c what we can replace you That they can consider replacing so Baikunth house that they replace her with art craft for 10 minutes tis triplets one of the state is not saunf vikram putra haq na will go par aisi 210 in that case owais sudhir wa sirvi do the thing Will be seen even after due to android 2.2 and android 2.2 and android 2.2 and subscribe toe's white and this defeat and this business man tried to drawing tool that they can either remove or you can either in search of a trip base rate increase and its note Se So Lets Se Left Side Subscribe for this particular in the video Come and distance will become Tubelight Guddu told Bigg Boss for the This is equal to three Take Possible two Three Lot Tours Nov 11 2012 Right Subscribe to James subscribe and subscribe the unit two is so hard work year after sales forest minister girls current account delicious unit remote planets can delete them that hand side and distance e-mail Vikram and this frill playlist one e-mail Vikram and this frill playlist one e-mail Vikram and this frill playlist one character first one replaced character end digital arrest Twitter The Video then subscribe to the Page That Doing All This Right Issue Replace Digital Prints And Other Side Operations Effective To-Do List Se More Than 60 202 The State Thanked Her No Matter Which Place In The Soil Backem And Director Smartphone I Want From dancing features to 1000 this darkness is instituted of which subscribe button video is collector delete 200 wheel thin increment is two head not I'll come a free website with free water spray press f8 remembered with regard to just give and subscribe to that edison System 3 That And When Will Increment This Is Good For And Jjikot And Birthday Gift Appointment 1483 Only Kand Develop Then Office Will Be Free In That Case No Will Have To Adapt The Amazing Remove * Remedy Share And Subscribe Must Subscribe And Subscribe Do jhalar part approach like replace delivery festival light of nation but in this case which constantly replace friend characters in the state and what ever be required to reduce 149 subscribe replacing subscribe and subscribe half of this program and this problem with dynamic programming approach should get Into Real Row That Algorithm State Problem Suna Decade Programming Software Government Does Well Hey Are Which Is Equal To And 200 Subscribe 504 Oye Give 12512 Sunao E Will Work For Two Against Another Dynamic Programming Lord And What Is The Meaning Of This Is The Meaning Of The Word Boys Contact - 151 - subscribe The Subscribe To Hai So Let's Film The First 100 Grams Difficult But Will Go Through This Logic Behind You Are Point Convert Word Converter And Subscribe Appointed Subscribe Button Adhavwali Subscribe Now To Receive New Updates With U Note R O S Did Not Match With All The Statesman In Order To Convert What You R O S You Need To Be Id M Id To Field First Name First Subscribe You How To Convert Into Your Mind And Subscribe To That Some More Add Unit Converter To rs100 dozens of real matches swift world video are you how are you 9th a little choudhary society you just a quite amazed at how to do to connect with a souvenir volunteers remove hair and who is the president and lodge and f4 remove Your Ministry of course you need to know directly subscribe building subscribe and subscribe the Video then subscribe to the Page hai what we say in this is the match what is the date of birth support download but no veer awal subscribe to the Page if you liked The Video then subscribe to The Amazing Sunao The Most Endowed In This Award Address Jisko Bhi Water Retention Ali Awards And Have One Chaupat Porn Ki Hamne Hai To Isi If You Want And But Broad To This Technique Example Okay Head To This Word Is Hips Override Android convert into charge imposition of urinating to RO pleasant replacement subscribe not subscribed till phone ko app gram flour means you how to any point convert RO a feminine mist facility convert hate you are the join replacement The Video then subscribe to the Page if you liked The Video then subscribe to the two and 9th and 10th what is ever the minimum of all 20 character words is loot 10 top david this is not coming Share And subscribe The Amazing You Are Obscene Porn Vid Ko One Day Or Here Replacement Right This Obscene Singh The Element Available For Disposal 125 Who Want To Know That In Order To Replace And Unit Security To The Matrix And Don't No Matter Where You Want To RO A What Is That He Chaugi To Accusation How Many Operation In Flight In The World Is The Question Where To Go In For The Video Which Rs.1515 A Picture Of Science Maths Water It Is The Deathly And Twist Perfect Flight That Similarly Share All Sites For And Trick Height Sudhir Want To Listen What Is The Mean Equal To the simple subscribe tell em saying and one for age award to cigarette developed especially different lands for one for all 201 and land post word is anti jis button see sexual picture and dry air declaring hey son 2010 ok and know what they Did And The First Step Which Should First Sued Shoes Where Gone Toe Field First Column End Subscribe Toe In This Post's Alam And Difficult Toe Field First Development Poster Boys Additional Check Share Subscribe And Example You Are The Character Repeated-Repeated Subscribe Like Subscribe And Click on Share and Subscribe button Quadratic Office Phone is not a is this what is explanation it's ok meter imo ho agro and they need to no sc are also right in the middle and share subscribe and half of them channel subscribe will not doing what is The Largest Gland of Death and Subscribe Programming in the Time Since the Second Column Its Famous Starting with 20000 Match and Directly Copying Dresses Available in the Dragon Ali Abro Element But They Didn't Get Meaning of All Eyes on Top of All Cars and Want To Be Next Chief Advisor Guide And Subscribe Please Subscribe To Requirements Of Its Final What They Are Doing His Return More Is The Distance Withdrawn In Attacking Him Into Subscribe To Now Suhaag Much Special First Column Plus First Stop Post's Tall Money Will Withdraw From Class First Raw Agent Andher Going Through - - - * Subscribe To This Can Going Through - - - * Subscribe To This Can Going Through - - - * Subscribe To This Can Be Equal To Drops Of Lemon Juice And To Remove From Within That Will Do You Do Tomorrow Morning Hari Singh Bisht Very Super Girl Friend That And Are Request U MY AND SOM Specific to God of Boys and Videos Patient Seervi subscribe like subscribe comment and subscribe the Channel Please subscribe And subscribe The Amazing Videos A time for watching I will be back with another video Verizon Children and Tech Good bye tha
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
1,178
so lead code practice question so in this question i'm going in this video i'm going to cover uh the question called number of valid words for each puzzle so i'm going to explain the solution and explain this piece of code and also at the same time i'm going to cover the procedure we should follow in the real code interview so let's get started so remember in real code interview the first step is always try to understand the question and if you have any question to us please bring up the question don't be shy and also at the same time think about some ash cases so let's see this question so with respect to a given puzzle string a word is valid if both the following conditions are satisfied so word contains the first letter of puzzle and for each word in for each letter in the word that letter is in the puzzle so for example if the puzzle is a b c d e f g then the violet word are fist cabbage etc well invited words are b fed so this one is invalid that is because it doesn't include the a which is the first letter of the puzzle and for example best it is invalid that is because s is not in the puzzle so as in the word but it's not in the puzzle which doesn't satisfy the second condition to return an array of answer where answer i is the number of the words in the given wordless words that are valid with respect to the puzzle i so let's see the uh this um input so we have a list of the words we have the list of the puzzle we want to find how many words within the words array that could match the two of the condition for each of the puzzle so for example for puddle for puzzle one there is only one matched word for the two conditions about so let's see the constraints so it says that uh the words array is not going to be empty and the worst length is between 4 and 50. and the puzzle is not going to empty and also the puzzle the lens is equal to 7. so the so each puzzle has a fixed length which is seven and uh each word ij puzzle ij are english lowercase letters each puzzle i doesn't contain repeated characters so i think that works fine essentially we just so for each puzzle we go through each of the word to see whether the two conditions are matched the first condition is the word should contain the first letter of the puzzle and also the second condition is for each of the word uh for each of the letter within the word the letter should also contain the puzzle so the character set in the puzzle should be a super set of the words and also the first letter of the puzzle should be included in the word so that's a pretty uh clear estimation about the two conditions so based on the constraints i don't see any um uh any ash cases i mean that is worthwhile to consider so let's uh see how to solve this problem so after you're done understanding the question the next step is about for you to understand the solution sorry to find the solution and also discuss with the interior about some runtime analysis etc and also after that if you get an agreement you are okay to start doing some coding work so let's go through the this piece of code and at the same time i'm going to explain what the solution is so the general solution is for each of the puzzle we run a recursive function to enumerate all the combinations of the letters so each combination is represented by the bit so let's say for a it is the first base of the integer for b it is the second bit of the integer so we are going to mark the corresponding bit as one if the letter x exists in the puzzle in the combination and also for each word we also have a bit representation so for example for this one it is a map to integer one because a is mapped to the first bit of the integer and it doesn't really matter whether the letter exists whether the letter appears more than once because if it appear more than once we still just set the corresponding bit as one so let's see so for this piece of code we first define a bit frequency map so the key is a bit representation of the word and the corresponding value is the frequency of this kind of bit pattern appear in all of the words we go through each of the word we find the corresponding bit representation of the word it's like we for each letter we just move uh we just set the corresponding bit as one and then we put the bit representation of the word into the map if it already exists then we are going to get the original frequency and plus one if not exist then we are going to set it as one and then after that we need to initialize the contrary to be returned finally and then we will go through each of the puzzle we enumerate all the combinations uh all the subsets of each of the puzzles so and after we enable all the combinations or subsets then we are going to go through uh we are going to go through each of the subset to see if the subset contained is contained in a bit a frequency map if yes then you're going to get the frequency and on top of the counter otherwise we are going to get it to zero uh and let's go through the code which is enumerating all the subsets so for the puzzle um there are four parameters uh and there are four primary theories in the function so the first one is a puzzle string the second one is the index and the third one is uh like a time integer that they store that is you to that is used for storing uh then the temp results and the last one is the results which is all the subsets we are going to finally return uh to be used in the main function so it so for the recursion i usually define the exit so if the index is the length of the puzzle which means it arrives at the end of the string then you're going to add the time string into the result so if it if the index is the first one we need to definitely include it because the condition says the word should contain the first letter of the puzzle so otherwise if it is not the la the first one then there are two options whether to keep the corresponding letter or you just drop it so if we drop it so we keep the temp as uh as not changed if we choose to keep it then we need to set the corresponding bit and then add on top of the tab so that's essentially about this helper function which is a recursive function to enumerate all the subsets or other combinations of the puzzle string so overall the runtime would be let's see the runtime so for this one let's say if there are inwards and each word is of the length of m this part is going to be o and m let's see for this one so if the so for the puzzle because there are so the length of the puzzle is fixed which means they are at least at most because we definitely need to include the first letter of the puzzle so it leaves the rest of the combination as 2 to the power of 6 which is 64. so for each of the puzzle uh the subset can contain at most 64 uh different so for this one um i think it would be so like for this one it is going to be constantly because up to 64. and this one uh we need to so let's say they are let's let me put it down so let's say n words and uh m as every average length of the word then it is o n m but we definitely need to consider the puzzle so for the puzzle uh let's say there are let's say and let's say x puzzles and each puzzle is of the lens okay so the lens is fixed so since the lens is fixed then it is pretty much just the o and m plus x uh like we have x puzzles and the like this one is going to be constant because of the fixed lengths of the puzzle and also this one is going to be constant as well so overall the runtime is o and m plus x so that's it for uh this uh coding question so having if you had any question about the solution or about anything feel free to leave some comments below so if you like this video please help subscribe this channel i'll see you next time thanks for watching
Number of Valid Words for Each Puzzle
valid-palindrome-iii
With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied: * `word` contains the first letter of `puzzle`. * For each letter in `word`, that letter is in `puzzle`. * For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while * invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle). Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`. **Example 1:** **Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\] **Output:** \[1,1,3,2,4,0\] **Explanation:** 1 valid word for "aboveyz " : "aaaa " 1 valid word for "abrodyz " : "aaaa " 3 valid words for "abslute " : "aaaa ", "asas ", "able " 2 valid words for "absoryz " : "aaaa ", "asas " 4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access " There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'. **Example 2:** **Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\] **Output:** \[0,1,3,2,0\] **Constraints:** * `1 <= words.length <= 105` * `4 <= words[i].length <= 50` * `1 <= puzzles.length <= 104` * `puzzles[i].length == 7` * `words[i]` and `puzzles[i]` consist of lowercase English letters. * Each `puzzles[i]` does not contain repeated characters.
Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that.
String,Dynamic Programming
Hard
680
95
All Everyone Today In Solving Question Light Turn On The Question Unique Binary Search Tree Rated By Over 250 Million Professionals Pacific Given In Increased And Western Australia Unique Poisonous Trees Which Mention Notes Of Unique Values ​​To Trees Which Mention Notes Of Unique Values ​​To Trees Which Mention Notes Of Unique Values ​​To Monitor The Answer In This Will Basically Be Given When Ooo and your feet consider all notes for 2nd year to for all structural unit benefits not for any situation with different possible - history em different possible - history em different possible - history em structures after written test and in this case will find the right five different possibilities and for example of music and only one Possibility of - 1929 values and only one Possibility of - 1929 values and only one Possibility of - 1929 values one and left and right for internal selection liquid white notification no let's see how to solve this problem solve this alerts number returned at 9:00 am share and subscribe button more that Ajay Sen was the example etc different possible by vested interests Akshar solid CO2 service sorry physical every morning is 163 liquid form and attraction most of you mulk solid se notifications co for example for its annual return all different sectors possible with and 128 flat to now 10th route Bengaluru first so let's check the 12.5 and possible for the Factors Sun 12.5 and possible for the Factors Sun 12.5 and possible for the Factors Sun 12345 This Phone Numbers And Andar If You Have 6 7 8 Improve Three Note Morning To That You Remove Characters Function In New Password 1234 Admitted That You Make All Different Possible Structures With 1234 And Vitamin E Saw A Point For Its Chief Ministers Possible Without U 12834 Divide 615 Defense Sector Possible Key And Comment Kar IPS Management 355 Impossible Latest Solid Say Director Vinod Bhatt Vinod Gautam Different Possible Factory And Viewers Another Text Five Different Possible Night Sweet Dream So Any Combination Of Them Will Give Me Detours Of Having And Easy Quiet Muslims Serif Fonts Free Mode On The Root Notes Of One Will Be Having Any Month And Space Russia Tense 500 You Get Shift Latest Episode 215 * Phase Episode 215 * Phase Episode 215 * Phase Basically Take Different Possible Yad Root Note For Example Want Two And Three Day Water Pollution The Left Android Software For Example if you consider fruit not given point left doesn't have anything to be a little eternal for it's a prayer of all the values ​​from quote 9 is the road to the values ​​from quote 9 is the road to the values ​​from quote 9 is the road to the life but consisting of only one brought up in the rights of band setting of all The Best Setting For Free Leg Heavenly Callback Function And Passion Fruit Wait And Tell The Function Dharti Return Me All The Impossible Key Structures Ghrit 12328 And You Will Return Gaurav Singla At Is The Death Agree With Node And Values ​​In The And Death Agree With Node And Values ​​In The And Death Agree With Node And Values ​​In The And You Can Do The Impossible permission combination and vitamin a tree and accordingly this very easy oil video to record in spreading over to solve this knowledge computer coding for this will be coding in C plus to basically this life function in this an intense basically in the present there where to make All the difference between structure with the volume starting from 120 b id college function president start setting aside muslims let's see if function implemented okay so if function straight into values ​​in talent intersole into values ​​in talent intersole into values ​​in talent intersole reservoir is the president and win first chuckle the best condition because Whenever your writing record se function you for bribes condition and united states man na vavvvv first check weather condition services girna uno df attacked with all way smaller than or equal to right index se poison and led in this clearly printed synthetic number send you kiss vriddhi jatayu Written in the soul bells and Britain type effective back war twitter no dear internet confirmed value null because you will behave in a country and returned to the notification light condition and he is equal to in that case will be only having one month and the Value of but now will be equal to here oil and now in this case was doing his adopted and tractor not bhi vikas return typing master trainer quantity same creating neither dhyatri nor dhye dravya liked The Video then subscribe to the Page if you liked The Video then subscribe to the Subscribe Now to Receive New Updates Reviews and They Will Be Painting The Value of Root Note Gold and Taste Where to Find All Different Possible Trees Structure for the Africa and All Different Shifting Swiftly Created Another Factor in All This Time for Your Life Easier and Artists and Points Pari So in the Life What All Possibilities Sardarpur The Best You No Doubt Businessman Soul Valley Starting from a Little Time Will Be Launched Internationally accepted from calling function and will return me all the impossible twist porn and colleges in function for the rights of preserve 13010 I know all the different cream successful electronics and all different principles of this country in this tribe physically not that nation and like if you Consider them away from this and all of this incidence of a native and all different free mode of and it should taste Tubelight in rural life if we consist of all different possibilities of Delhi previous investigation of sitting inside for look for the rights prolifically for and addictive Verification for itself when considering this point 83154 experiment written examination was diverted home and what is not value sea business sweater also side viewers black assign the lift inside I don't see the factors point was left or right shift so writer of class 9th referee you know This web site rating of passengers of The Telegraph's Basically a Leaf's Tracking in the Left Supremo Width and Factories Continue Train Basically Both Modes of the Left Basically It's White and Doing a Time is the Central Point at Which Was Not in the Laptop Twitter And Ride Point To Be The Right Mode Arvind Sites Twitter In Hindi A Right Tractor Navansh Aadhe Ravi Pushya Natives And Sabko Dushmano Solution And Final Beatitude Sarvsuvidhayukt Special You Should Be Elevated As You Cold Help To Function If Possible To Value R Intellect Alarm Advocate All Difficulties And written so when writing request solution riders condition for the best condition celebrate their failures and more than 130 for everybody should not be returning a single word and in case it is not the case of different natives with sonu hydrate tilak hydrate mail per settings the root Valuable you all the function recovery and so left or right for 2nd semester loot taker consider all the impossible solution you push and instructed to decorate so lets you cold not be submitted on then good accept subscribe history question was mostly this record solution handed over vice President Airtel Time Hoga Its Recording Status S Be Happy And Subscribe My Channel Thank You For Watching How Are You On Karo
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
1,671
Hello viewers welcome to my video recording pregnant very important problem in this corner minimum number free mode to make mountaineering president so energy amazon forms of mountain structure galaxy wall mounted safe supposed to have elements like just one to three layer investment disappointing subscribe first you have Increasing and decreasing elements with this amount android is aware structure and see the example of mountain are net savvy good evening took 1583 ok [ 1583 ok [ 1583 ok knowledge mountain 12345 a for r favorite also mount etna related to increase and in it to decrease its Something Like This Morning How to Find the Number of Daily Missions to Make Amount and How to Solve This Problem for Programming Examples Please Give One Example of How to Make Too Much Mountain Means 16 in 2012 Too Much Example of Okay You Can Take 1631 Okay If Encounter Case You Have Lot Of Elements Of Will Have To Digital Audio Element Not Give Answer Sorry Finally By Human Nature Actually A Program I Have Subway Reaction Longest Increasing Subsequent Problem Night And What Is The Longest Increase In Subsequent Problem Solve It's Very Interesting DP Problem Language Problem Near Left Side Such Diet Laxative In The Longest Increasing Subsequent For This And Ravi Yadav And Modified To Find The Answer Okay So Suppose You Want To Find Out The Longest Increasing Subsequent Means You To Lotus In This Increase In Red Panda Sequence Las Continuously Increasing and following the strength of dietary this let's see hills builder be simply is African started this element turn on right in this element will just for long way since its inception friend become is let's build a fear and a guy he is and will be used To Build Answer Let's Go Step by Step Soldiers Went To Give Its Elements And One Female Died This Element Riots Were Traveling From This Site Will Find Storing Edit Step's Chief This Element Is Not Going Into River And Increasing Voyeurism Is It Directly To Leaders Previous Today's Survey Per Decreasing Value Laminated 2nd Taste One Is Not Going To Give Increase Invalid Accept Not At This Solitaire Building Amazon Bun Hair Oil So Let's Check The Element What This Element In The River Valley Boys Smaller Than One Previously Known In The Lives Of Length One Hair Pack Letters to the President Everett File What is the Longest Increasing Sequence Now You Can See All Jhal Tube Hour Ke Liye Draupadi Slim Jewelers Se Bhi Tattoo 2.5 Was Slim Jewelers Se Bhi Tattoo 2.5 Was Slim Jewelers Se Bhi Tattoo 2.5 Was Increasing Sequence Sweet Fuel Subsidy French To Difficult Step Latest Song Next Step Support You Have The Limits of what is the maximum length porn 25822 323 341 506 Video then subscribe to the Page if you liked The Video then subscribe to subscribe and hear the latest Normally Milk Amazon You Can Form A Jhari Lavai One Two Three Idiots Said Twitter Maximum Different From Ford There's No Element Which Decreasing Now In 10 Minutes Before And Smaller Resident In Simple Terms Will Have IF They Will Develop A Person Who Will Do Anything With Love And Acid Decreasing Sequence The Longest River In Increasing Its Elements Like This Cream And Lag Increase Must Subscribe To Channel Quantum Field Of Mountain Due Course Amount And Types Akshar Will Increase In Elements And Different Friend Like This And Will Have Decreasing Elements Later Late Se Like This Kshir Arrangement Mountain Subject To Find The Number Of Elementary Follow Swimming Elements To Find The Mountain Subscribe What Is Question And Decreasing Order To Build A Very Similar To The One And Only One Element In This Will Give Me To You Happy Birthday To You Tattoo Element Friend To A Greater Than One And lifted 6312 can element be length three two a similar to continue watching this print industry spot fine more you can have 5318 will give way with suresh pachauri 52122 decreasing and this line three withdrawal maximum possible length her laddu seaworld reception element and smaller Ones in right side udaan service everywhere hindi length 150 hundred element witch mauzaan in its own right side effects models for this you can bring to front click will have to sequence of two french tourists where built amazon computer solution jaswant simple travels agree to t&amp;c you alone C Element Number If Left Side CESC Is Element You Want To Find Out How To The Mountain Park That Garlic Genius Length Run OK Rate Three Elements 652 Answer From Center Examples Disfigure Mountain Structure Its 2151 Under 625 Six December Getting Selected From The Real Look King Khan Voted in favor of Elements with all rights reserved for SCS 610 Mountain Element Elements in OnePlus 6 Subscribe Form Others 1234 500 You For Element You Want Us For The Mountain Likes Option But You Need To Find What You Mean That You Will Not Give Element Humne Idli Elements of Length of the Total Seth - Phase Three Minimum Return Answer OK Simple Logic Is One More Thing Video then subscribe to The Amazing subscribe Video Subscribe to Right Side Per Lena Hai Vipin Chandra Left Hand Man Se Foreign Tourist Spot Drivers and You Will Not Find Out Why You Should Observe Add Buddha Valid for Example 333 Sick Schedules Appointment 6 - 5th Annual Fare Schedules Appointment 6 - 5th Annual Fare Schedules Appointment 6 - 5th Annual Fare Elements in the Amount S Letter from Winter Mountain Service Five Elements But That's Not an Answer What is Quora Answers in this question Is we limited they want To delete ok 2018 elements and you are able to find the mountains with five elements within you want to get three elements nor will keep on doing this for wall decorations and vegetables minimum subdued service three minimum sharp answer pimples want to tell no tales one Small things listed for the limit for elementary first element voice mail address one phate se swapna what is that in the research and limit it's only one elementary mid that you ok android system admin02 elements which consume the electoral reforms is to one phate note validation and first Begusarai Measurement Sweater Deposit Want Element Beach Point Mintu Mountain Subject Read Forming A Decrease In Fact Underworld Don Is And Valley Difficult Simply Absorbed In The Ultimate Choice Not Valid Soil Is Very Inspiring And Adding One False Cases Will Be Invalid Okay Various One On All This Process Will Be Invalid Deposit Single Elements Considered In The Recent Assembly Of Speech Therapy Only Increasing Or Decreasing Elements OK Let's Check Another Example Productions Post CCD Sensor Knowledge In Validation In One Single Element Make It Slightly Mountain's President Mountain Type Structure Near Mountain Type Chapter Complete Subha to take care of this question ok to tanwar your relations and lda sworn in as youth that sort by latest videos for kids in mind ok no latest bluetooth coding latest discuss how did for delayed you sure yasin approach how to build addition tried to shield And so will address a very simple but to approach the ones who aspire approach in this ocean log in protest of images for flood control in favor of that expert my simple will start to build as his Waterloo against force elements of land owner taken Course elements of length vansh will just want a guy next will go to the one cement se equal to one and ill this is equal to zero number two is not electronic waste oil limited decreases in this small in the villages market top one plate squeezed see the Solution of but not for increasing with boys market know you all elements of small world wide fennel 2 and you can take you to you all a sequence of 151 21 2012 and 2013 travels from 10216 1234 his travels all possible values ​​and when they went travels all possible values ​​and when they went travels all possible values ​​and when they went so Let's Use the Solution of Class Ninth Solution of Heavenly Travels from the First Indian Ventures Into Classes 6th to 12th for Increasing Sequence You Will Notice Youth Oneplus One Will Give You Two Presence Will Write to Here When You Travels Next Possible Element What Is The Element Events - Monitored And Six OK Se Loud Half Inch Plus Minus Giving You To Write Show This Person's Screws Desired You Will Be Able To Form A Sequence Of Two Elements OK Morning Office Will Oo Is Imperative For Years Traveling A 2012 Unknown Travels Jaipur To Again Ones Side Lieutenant 6 You Will Find Ads For Oneplus One Student So You Can Feel To The Nav Is Particular Oils For Cold This You Will Enter Into A Public Use The Amazing Length Students Took Place 39 Disputed 512 Builder Sequence And Planets Real Reap Jethwa And You Will Write Three Are Sun Now Its Service Three Morning Evening Temple Run To All Us Video Ko Approved Solution Just Give You For Any Particular Day For Relief From More Than 120 People Is The Element The Example Of The World Free For You Already Know The Same To You The Giver 128 Be Elements 6560 Twitter Sequence Of Events In 10530's Big Simple Approach Know They Are Just Previous Builder Complete Address For Two Years Old Values ​​That You Will Run For Two Years Old Values ​​That You Will Run For Two Years Old Values ​​That You Will Run From 03 For Manure Is Equal To Fight with travels from jack 1202 quality 416 seven smaller than two-thirds initial put in it two-thirds initial put in it two-thirds initial put in it shareef oneplus anil add oneplus one plus one two soles to complete duty wash body basis of examples for IAS officers club increasing incidents from one to three element 3D of this particular Clerk When You Have Not Even A Single Elements Of Fire Wind Water And The Loot And Laws And How Do You Do When Log In Relations Will Not Used To Follow Us At River During Night They Can Do Anything For Building Dad New Delhi Can't Do Anything On E Will Spread Galaxy How To Visit In When Log In Temperate Willam 5th Position But They Want To Do Particular Element In Village Scene Example Sleep State Building Balance Reviews Helper To Helper Okay Let's Have Helped Not Doing Push Elements In The Help Of Login First Element With The help of elements are always two elements in increasing order place one will give you two loot one ok Fri 28 that Bigg Boss instead of two it's better to have smaller elements mute want awareness increasing vegetables sylenth1 Again with secretary Vikram End opposition over 900 a message elements name for biscuit the longest increasing subject 1956 elements length inference limit this point sweet push file ok wear always storing from palace premises 12:00 storing from palace premises 12:00 storing from palace premises 12:00 limits in increasing order request you want to build a long weight increase in subsequent To speed milungi suna will now they want to see the element which will see you will not now vaishnavi push two in help are so way you too come tourist come here right after one will push two years will remove it sudhir one two three Three To Remove The Last Element Last Elementum I One Rate Early In The Morning Come One Fruit Commander Force Se Limit Positive One Which Can Skip Intends Doing Should Be Done Wrong Action During Subsequent Edits Of Length Results Of Land C&amp;E Say Corresponded Results Of Land C&amp;E Say Corresponded Results Of Land C&amp;E Say Corresponded Value Subjects Will Address for advice of innocent voters will decide the growth and spread this time its findings of especially signs and opposition and values ​​and signs and opposition and values ​​and signs and opposition and values ​​and research center in search of log in solar system unit certificate in the preparation and addictive and everyone sued over and over again without giving suggestion Dahej Saare Showoff Basawat Solution Needs And Aspirations Are So How Bingle Gets That You Can Modify The Code Of Celebs Who Can Be Seen That Are Similarly You Can Be Reduced To 100 During Subsequent Just Reverse This And Apply Should Speed Up Leather Channel Like This Is The Meaning Of The Word Meaning That Common First Vihar Rome Fine * Are Increasing Subsequent Edits During Subsequent Special Fine * Are Increasing Subsequent Edits During Subsequent Special Fine * Are Increasing Subsequent Edits During Subsequent Special Watching Our Lives Are In This Thing But And Advice Return Gift Hui And Also Withdraw Into This Earth As Discussed Key Building Tours OK Adventure Half Buddha Website Politics And They Can Find Out The Minimum Number Of Movements In Order For Building May Jhuke Never Wrong And Change According Leharen And K News MLA Saare Khol Rate Just Reverse The Are Ones And Reverse Back Again You Can You Same Code For Adult And Will Give Answer Cracked Heels On Some Medium Day Two Times It's Okay 9th That Finding Report On You From All Of Them This Increasing Difficulty And Decreasing Sequence Facebook User Guide To One Se Sure Vansh And What You Are Doing A Good Job Increasing And Decreasing Elements Of Chronic Cases Including Her Elements Website White Mountain Relative 123 Six And 30 Sign In Forensic Must Aircel Will Also Give Lens For You Really Are Always Be Length 1437 Birthday Settings Length Of Solid Co Share Including Elements Two Times They Want To Surprise One Feels Proud In the things from which is the length of the indirect speech 125 minimum number of relations rate vision document and do n't know how to delete or remove your photos from social sites for boys new haven of clans game set minimum chanod answer ok Na Amaze Optimal Function To Build A Code This Deals In Different Problems Which Will Be Amazed Important Problem Telegraph Ne Suicide Note Solution Of Math Solution Which Features You Are Simply Too For Lips To Lips And What Do You Know Element The Video then subscribe to the Page if you liked The Video then subscribe to query using mahal par and celebration ka first element and where traveling from the if there is one to one element and aware offers for checking of management system greater noida the Last Element Simply This Elva Edison Element 1839 I Want To See The Question Set This Reminder Running Fixed Deposit Element Not Relevant To Give The Benefit Of The Position Of To Play Share and subscribe the Video then subscribe to the Page if you liked The Video then subscribe and subscribe this Video give do question result declare withdrawal step taken meaning of moonlight dreams and the is from middle wise element phantom wellington new to delhi to family to make a call to subscribe and solid liquid is loot working Let Soe Disturb and Solution Minister of Law and Solution Optimal Censor the Tweet Let's See What Time Complexity of Dreams Were in Place of Modern Life in this World Such Natives Are Very Bed Time Complexity of Just One 14% 16 Co for Login Solution click this nut 14% 16 Co for Login Solution click this nut 14% 16 Co for Login Solution click this nut thank you
Minimum Number of Removals to Make Mountain Array
the-most-recent-three-orders
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given an integer array `nums`​​​, return _the **minimum** number of elements to remove to make_ `nums_​​​_` _a **mountain array**._ **Example 1:** **Input:** nums = \[1,3,1\] **Output:** 0 **Explanation:** The array itself is a mountain array so we do not need to remove any elements. **Example 2:** **Input:** nums = \[2,1,1,5,6,2,3,1\] **Output:** 3 **Explanation:** One solution is to remove the elements at indices 0, 1, and 5, making the array nums = \[1,5,6,3,1\]. **Constraints:** * `3 <= nums.length <= 1000` * `1 <= nums[i] <= 109` * It is guaranteed that you can make a mountain array out of `nums`.
null
Database
Medium
1688
338
hello and welcome today we're doing a question from leak code called Counting bits it's an easy we're going to jump right into it given an integer n return an array answer of length n plus one such that for each I and I is going to be in the range of 0 and N answer of I is the number of ones in the binary representation of I so example one we have n equaling 2 so we're returning an array of length three and it's going to range from 0 to n so it's going to be 0 1 2 and it's representing the number of ones we have of those indices so in index0 we're representing number zero and zero in binary has zero ones one has just one and two has one as well what about five so of course the first three numbers will stay the same 0 1 one and three has two 1es four has one and five has two ones now a followup it's very easy to come up with a solution with a runtime of n log n can you do it in linear o of N and possibly in a single pass and can we do it without any built-in function okay yes without any built-in function okay yes without any built-in function okay yes so first what is the n log n solution the nlog N approach well that would be going through every single n that we have every single number and converting that number into binary we can do that in log base 2 of n time because again we're converting into binary and we would just Loop through counting the number ones we have in that binary representation to get our final answer we're going to do this for n numbers so our time complexity would be n log n but we want to do better so what we're going to do is we're going to be using dynamic programming to build up our answer okay so I want to do better than nlog and time and potentially do this in a single pass what I'm going to do is make use of dynamic programming so if I had four the binary representation of four is 1 0 to get to five all I'm going to do is add 1 one to that right so my binary representation for five is 1 and I have two ones instead of the one I had in four what about six in binary is 1 0 and this also has two ones the same as five so our logic sort of breaks down here we can't just add one more one as we increase our numbers but is there something else that we can spot here and remember we're in binary so we're building numbers off of each other so there definitely should be some sort of pattern so what I'm going to do is I'm going to go ahead and write down all the numbers from 0 to 20 in binary and the number of ones that we have there just to see if we notice anything so all the numbers in binary are written over here we have 0 to 20 they're binary representations and the number of ones that we have now to start off the first number is going to be zero so it's all zeros and we have zero ones what about one is going to have a singular one in the one's digit and what about two well two also just has the one because all we did is we took what we had in one and shifted it over by a digit right this is because we are in binary so every time we have a two multiplier every time we double we just take our numbers and we shift this is the same as say being in base 10 going from 10 to 100 it's still that one that we have that's been shifted and it doesn't matter what number we use if we have 53 if we do a 10 multiplier it would go to 53 0 so the same digits just shifted over and in base two whenever we do a two multiplier on any number we'll see the same pattern happening in three we have two ones we have 1 and when we multiply 3 by two we get six right so we have 1 Z for six also just 2 1es doesn't matter what number we look at this will always hold true for seven for example we have 3 1es over here if I multiply this by 24 it's still the 3 ones with an added zero at the end so it's still three zeros what this means is that any number that's been doubled will have the same number of ones as that number half so that basically means any even number that we see we know how to get the number of ones for it so for two we would just look at one because 2id two is 1 and it would have the same number of ones and same with four and 8 same number of ones 8 and 16 same number of ones we look at 10 and five same number of ones again it's just all shifted so we know how to do all the evens what about the odds well for the odds all we have to do is add one all the evens end in zero and all the odds end in one because all we're doing is we're taking that previous number and adding one to it so we had Zer ones and now we have one that last bit that was a zero in two because remember we shift it over so we shift it over and add a zero we're changing that zero to a one for the odds so to go from 2 to three of course we shifted over one when we got went from one to two we're just changing this to be a one so instead of 1 Zer we're going to have two same with six and 7even right it was 1 0 7 is just 1 so it has 3 1es instead of two and if we look at 10 and 11 the same thing holds true so what we're going to do is for our even numbers we're going to check the number of ones in our numbers divided by two and for our odds we're going to check the number before us and just add one to that so to code all of this up the first thing I'm going to do is initialize a result array which is going to have a zero for that first element and now I'm going to Loop through so for I in range 1 2 n + 1 because we I in range 1 2 n + 1 because we I in range 1 2 n + 1 because we already covered that zero with index we want to start from one and we want to go to n + 1 I'm going to append to n + 1 I'm going to append to n + 1 I'm going to append to result what the index haved has so result of I / 2 and if this is an even result of I / 2 and if this is an even result of I / 2 and if this is an even I'm going to add zero ones to that I'm just going to copy paste whatever I have in that resulting number over there but if it's odd I'm going to add a one so all I need to do is check if I am an even or odd index so I'm going to do IOD 2 and whatever I get from here is what I'm going to append to result at the end all I have to do is return result so let's go ahead and run this code it's accepted and now we can go ahead and submit this and it is accepted as well so before leaving let's just run through a super quick example just to see how this is actually going to work say n = 5 what are we going to do well say n = 5 what are we going to do well say n = 5 what are we going to do well first our result is just going to hold a zero now we go in this Loop over here so I is now going to be one result. append I / 2 so that's going one result. append I / 2 so that's going one result. append I / 2 so that's going to be zero so I'm going to check what I have at the zeroth index which is zero and I'm going to add whether or not I am even or odd so I is 1 which is odd so 1 mod 2 what is the remainder I get when I divide Myself by two that's one so 0 + 1 divide Myself by two that's one so 0 + 1 divide Myself by two that's one so 0 + 1 is going to be one and I append that to my result so I append one over here which is true right one has just the one now I'm back in this Loop and I is now two well what is 2 / 2 that is one now two well what is 2 / 2 that is one now two well what is 2 / 2 that is one so I look over here and I have one over here now I want to add what this is so 2 mod 2 is going to be zero so 1 plus 0 is 1 and I pend to result one now I go to three 3 ided 2 and remember this is integer division so that is going to be one I look over here so that is 1 plus what is 3 mod 2 the remainder I get when I divide 3 by two is 1 so it's going to be 1 + 1 which is 2 and I go ahead and 1 + 1 which is 2 and I go ahead and 1 + 1 which is 2 and I go ahead and upend that and you can see that we are just building this out once I get to four I see what was in index two and that's the one over here and I'm even so I'm going to be adding zero so four also has 1 and five we look at 5 divide by two so that's going to be two and now I'm just going to add one to that so that is going to be two as well and finally I will return this resulting array and it's exactly what we expect so we just went ahead and solved counting bits if you have any questions whatsoever let me know down below if you like this video like And subscribe and as always I will see you in the next one
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
688
hello everyone welcome back here is Vanessa and today we are going to unravel fascinating problem the Knight probability in chessboard so this problem is a medium level uh problem and uh but our trusty pattern by our side we can concur it together so let me lay out the problem for you we have a night starting at n by n uh chessboard and the Knight has to make exactly e moves so each time choosing one of eight possible moves uniformly randomly and our job well we have to calculate the probability that our brave knight will remain on the board after key move so if you have played chess you know that Knight could make eight possible moves however not all moves are safe some may lead to night falling of the birth so leading to its untimely demise so it cannot fall so we want to avoid it and hence we will calculate the safe probability and our Battlefield today will be fighting so I'm going to use a power of dynamic programming to solve this problem uh Dynamic probleming is a powerful technique for solving optimization Problems by breaking them down into simpler sub problems this way we can avoid redundant computation and make our code more efficient so firstly let's yeah I think how we can solve it so we have a class solution and Knight probability and in night probability we receive four parameters so the board size and the key moves and the initial row and initial Coleman position of our Knight and I will start by defining the Knight possible moves and 3D dynamic programming RSO DP with I K and J so those will hold the probabilities of the Knight being at a particular cell JK and after uh eh moves so next we will set up our base case in dynamic programming Table after zero steps if the Knight starts on the board it's still on the board so the probability will be 1 and now is the fun part we will iterate over there this DP table and for each cell calculate the probability of the night landing uh there from each of its possible previous position and we take the average of this probabilities as each move is equally likely and finally we will sum up the probabilities of all cells after the key steps and this will be our result so let's try to implement it so move will be opposable Musso one two one minus one two minus 1 minus one minus two one okay and DP will be zero four in range of N and four in range n and four in range e plus one and DP 0 row column will be one and four step in range from one to key one or Row in range and four column in range and as well and four uh direction of column and row move a previous row previous column will be error minus Direction and direction of column so if zero previous and n and zero as then yeah a previous column and so in this range of board DP step row column plus DP previous step and previous row previous column divided 8 and total probability will be zero and four row in range of abort or C in range of n and total probability plus DP key RC so we count probability and finally we return total probability so this is our implementation so let's run it and see if it's working for a given test case yeah with and being placed here so rows 0 column 0 board and three key two okay so yeah it's working with uh DB so all good and yeah so let's run it also for unsynthesis cases to verify if it's working hopefully it will pass the time limit because I don't know so yeah we successfully uh finished 54th day of daily Korean Challenge and yeah our implementation bit 21 with respect to runtime and 60 with respect to members so it's memory efficient and yep uh good working implementation so for example here is 200 milliseconds and we got 300 milliseconds but it's our first uh ad hoc implementation with DP but yep all working so uh really good so uh perfect so this is how we solve the night Journey with dynamic programming and it can be a little tricky to wrap your head around initially but with practice you will be able to use it to solve a wide range of complex array problem and remember practice is a key so I hope you enjoyed solving this problem with me if you did don't forget to hit the like button and subscribe to the channel for more exciting coding Adventure uh leave a comment below if you have any question or thoughts about this problem I always enjoy reading your feedback and until next time keep coating keep practicing happy coding see you next time
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
116
hey everyone in this video we are going to solve the populating next right pointer in each node only it could what the question says is we are given a balanced binary tree a perfect binary tree which is which means it's perfectly balanced every node other than the leaf nodes have exactly two childrens and what we need to do we need to point the next pointer to its next right note What will what does that mean so the node to its right side so in case of root Node 1 there's nothing to its right side so it's pointing to null in case of node 2 there is node 3 on its right side so next pointer will is pointing to node three in case of 4 There is five one is red side in case of five it's six on its right side in case of 6 it's 7 on its right side and in case of seven there's nothing on its right side so its next pointer is pointing to null so this is the question let's see how we can do it so the first solution that may come to our mind is to use some sort of a level audit reversal so what we can do we can Traverse each so we can Traverse this binary level by level that means for first we'll go to the first level one there's nothing to it so one will point to just null once next pointer will point just to null similarly for the next level we will have two and three so what we can do we can point two's next pointer to 3 and since nothing left nothing exists after three we can simply point three is next pointer to null similarly we can do for four five six seven as well so the time complexity for this one will be o of N and the space complexity will also be U of n so we can use this approach to solve this particular question but this another way to solve this question as well in which the time will be o of n but the space will be four of one let's see how we can do that so we are not using any level order travels so we are just using uh so we are just doing a normal BFS so what we can do here so we know for root note it uh its next pointer will always point to null as there's nothing right to it but for two we can simply uh Point two's next pointer to root dot child if we are at this root node 1. what we can simply do we can simply write root dot left dot next to root dot right by doing so we'll can we can simply connect two's next pointer to three similarly for four we can if we are at node two we can simply use uh two dot left which is 4 dot next to root dot right that is five so by doing so we can connect 2 to 3 and 4 to 5 but the challenge will come when we come to node 5 and we need to connect it to node 6. because we are at this particular node 2 and it does not have access to this note 6. this might seem tricky but solution is quite simple remember we have already connected 2's next pointer to three so to connect five to six all we have to do is to move uh to the third node so the next of node two what do I mean by that so we can simply point so we can simply Point five's next pointer to twos dot next dot left what I mean so if the next for the root exists so if in this case yes it does two's next is 3 to 2.2 is Right node two threes left note 2.2 is Right node two threes left note 2.2 is Right node two threes left note to connect the next pointer what we can do we can write a root Dot right dot next so here we are connecting the fifth node and we need to connect it to node 6. how we can get up to node 6 we can do root which is to dot next now we come to three and then it's left child six so by doing so what we will be able to do we'll be able to connect this five node to node 6. so to connect this what we did we are at the parent so that is the main thing to remember we are at the node 2 and to connect its live Its Right child next pointer to six First Step was to choose next pointer so two's next was three and three is left for six by doing so we Simply Connected five next to six so let's try around this solution once and you will get it clearly so let's try on this our algorithm so we are at the root node one and we don't need to do anything here so because it's the root note and here it will just point to null now we need to use two pointers here let's say we have two pointers one is current which is pointing to our root node and another is next pointer which is pointing to its left child root current dot left now we need to apply this algorithm to connect all the next pointers in this particular tree so to do so first start with the left side so root dot left dot next will point to root dot right so current here root is our current so current dot left dot next so 2's next will point to current dot right by doing so we just connected two next twos next pointer to three now we need to do the same thing for the right node but remember here root dot next we need to point it to root dot next but in this particular case root dot next does not exist so before applying this second algorithm the second line of code we first need to check if next exists or not in check if next exists or not in check if next exists or not in this case it doesn't so we will not do anything and we'll just move forward now once we are done with this write note as well what we need to do we need to swap this current and next pointer so now this current pointer will point to where next was pointing and next will point to its current or left so once we are done what we are doing we are moving current pointer to next pointer and next point to two current dot left cool so now we are at the last level the third level now we need to apply the same algorithm here as well so first for the left part so current dot left dot next so current is 2 left its left is 4 so current dot left dot next it will point to current dot right is 5. by doing so we just connect it fourth next pointer to note 5. now we need to do the same thing for the right channel as well and in this case root dot next does exist so root dot next dot right which is Fifth and right it will point to root dot next dot left remember this 2 doesn't have direct access to the sixth pointer but we have already connected to the next pointer to three so we can use this previous connection to connect Its Right child to it through the respective next Point next node so applying this algorithm what we can do root dot next root dot write dot next it will point to root dot next which is three dot left so by doing so we just connect it pipes next pointer to node 6. now so there are still nodes remaining uh so what we will do we'll just move the current pointer to its next current.next current pointer to its next current.next current pointer to its next current.next so we'll just move current equal to current dot next now current will come to its next pointer so it will come to 3 so here next will also point to 6 which is current dot left the current is pointing to current dot next and next is pointing to current dot left okay now we are at the node 3 now we need to apply the same thing these two lines of code for this particular node so root dot left dot next so root is 3 it's left is six its next will be pointing to root dot right which is seven so here we connected six to seven now we need to apply the second algorithm but remember its next does not exist so root dot next does not exist here so will not do anything and keep the next pointer will simply apply to null so this was the solution which will run in time of O of n and space of one so let's see how we can do it in code okay so first we'll need our two pointers first our current pointer the current pointer will be pointing to root and next we'll need our next pointer so next pointer next it first will check if root does exist or not if the root does exist then only we'll pick its left side because remember the next always point to Roots left child else it will be null next we'll run a while loop and it will run till either a current node exist or an and our next node axis both exist so inside this while loop what we'll do first connect the left child's next pointer to root dot right so our same algorithm that we discussed in drawing explanation current dot left dot next 12.2 12.2 12.2 current dot right now we'll check if current dot next exists or not because now we need to point now we need to do the same thing for the right node so to do so current dot write dot next it will point to current dot next dot left right now once we are done with this particular node we'll just move one step forward which is current equal to current dot next now if the current does not exist the current dot next does not exist so if current dot so now if current does not exist we'll simply move both of our pointers so current will point to next and next we'll point to current dot left and at the end we'll just return root so if we run the solution yes it's working let's submit it yeah it's working so that was it for this video thank you for watching
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
109
hello guys welcome to another video in the series of coding today we are going to do the problem which is called sorted linked list to bst so you're given a singly link list you have to convert it to balanced binary search tree which has the same data value so this is the linked list that is given you have to convert it to this binary search tree okay let's see what is the properties of the linked list and the value research that are going to be useful here so let's say you are given a linked list which is 1 2 3 4 5 6 7 8 so when you convert this link list to a binary search stream in a binary search tree the properties are okay first of all um whatever node is there right on the left of it all values should be always less than the node right and on the right of it all the children of it should be greater than node this is the property of binary search tree okay this property is going to be very useful for us to solve this question it is given to us that the linked list is sorted in ascending order so first of all let us start creating the binary search tree okay we have a node we have to first of all create the binary search tree so this is our linked list what will be the first value of the binary thirsty it will be the middle value of this linked list right so it is 4 currently so first value is 4 let me also write the indices so we have a starting index we have an ending index and we have a middle index okay so middle value is 4 now we have to give the left child of 4 now what values can be placed on the left of 4 all the values less than 4 can only be placed on the left of 4. that is a property of binary search tree right so all values on left of 4 can only be placed uh as a left children of 4 so there are 3 values 1 2 3 all the three values should come here okay they cannot come on the right side of 4 okay so all the 3 nodes one two three should come on the left of four now let's fill the value here what will come just on the left of four right so first of all since i have shifted my search space now i am finding the left child of four what is my new uh start end and mid pointer let me just change the value so the node 4 is gone right so the node 4 is gone okay now the starting pointer is 1 ending pointer is 3 because values left of 4 should be less than 4 so starting value is 1 ending value is 3 what is the mid value is 2 so 2 will come here whatever is the mid value will come here ok so the mid value is currently 2 so 2 i have placed ok now i have to find the left child of 2 so what will come on the left of 2 anything less than 2 will only come on the left of 2 right anything less than 2 so i will again change my um starting pointer end pointer and mid value will be just the middle of starting and n values so now the mid value is one so i will place one okay now this is placed now let me place the left and right child of one do they exist they don't because you see on the left side of one when you shift your pointer when you move your pointer what will happen the starting value is going to remain the same but your ending value will go out of bounds ending value will become minus 1 starting value will still remain the zeroth index right so in this case you can see that there is no node possible so because of this one does not have a left check similarly it will not have a right hand because if you see a right child of one the starting value will come here the ending value will remain same start again becomes greater than n or what does this mean is if you want to give a right child to one right that should be greater than one okay because it's on the right of one but it's on the left of two so it should be less than two it should satisfy both these conditions now there is no node possible which is greater than 1 and less than 2 right there is no such integer possible which is greater than 1 and less than 2 at the same time so because of this reason one does not have a right child okay one does not have a right child so now we have uh finished giving the values of children of one both are null right one does not have any left or right both of them are none okay that's it now let's come back to this node 2 now once we come back to this node 2 we are again at our point where we were here right now we have to find the right child of 2 okay so first let me mark the initial value so initially when we were inside this function call when 2 was the mid value the starting value was 1 and the ending value was 3 okay now if you have to find the right child of 2 it has to be something which is greater than 2 but since it is on the left of 4 it has to be something which is less than 4 right so in this case i will shift my pointers again if it has to be greater than 2 the starting value will also be on the right side of 2 right and the ending value is also on the right side of 2 so the mid value is also 3 so this is your node that is start and as well as the midpointer so its value is 3 so the node which is greater than 2 and less than 4 is 3 right so i will mark 3 here ok i know it has become very messy but let us continue with this so we have the values now okay so in this case we have place 3 to be the right child of 2 okay because it is greater than 2 but it is less than 4 it is satisfying both the condition now let us come back to the beginning now in the beginning we had gone to the search space right because we wanted to find what are the children of 4 right so now we have exhausted we have filled all these nodes right we have given values to all these nodes now we are on the right side of 4 to find out the right children of 4 so what is your starting value is the starting value is see when 4 was the mid right next time when you have to move the starting value it will be mid plus 1 right that will become your starting value so we have to note this so your starting value is at 5 and your ending value is at 7 so what will be your mid will be 6 so we will place 6 here and now we will continue we have to find the left child of 6 how do we find the left child of 6 should be less than 6 but it should be greater than 4 because it is on the right side of 4 right so which is the node that is satisfying both these conditions it is the node 5 right so because of which 5 will be the left child of 6 and when you do this that will be your pointers so see currently your pointers are here but if you have to find the left child of 6 so you will shift your end pointer you will make your end point towards the left of 6 right you will go towards the left of 6 so your starting and end pointers and mid pointers all will point towards 5 and you will place phi here right so that is a simple logic now we have to just fill one last value we have filled the value 5 we have filled the value 6 on the right side of 6 when you go you will shift the pointers all starting and in mid will point at 7 and you will fill 7. so 7 will be the right child of 6 because it is greater than 6 right so this is how we are going to solve the problem now let's code it so uh let's code this now the code is very simple so first thing you have to do is you have to convert it to a vector so that easily we can keep the indexes so we have the link list we can just keep on doing head is equal to heads next value right so that we keep getting the node next node and meanwhile we can keep on pushing the given nodes in our given vector so this will ensure that we have the linked list converted to vector because it's easier to have indices in vector and i'll give a variable count to keep a count of the number of nodes i have my start value and end value start value is 0 and what does my end value is count minus 1 count is the number of nodes so the last index will be count minus 1. now i can create a function i can call it let's say i call it bst right so i'm going to return whatever value this function returns i am going to pass it three things i am going to pass it my vector i am going to pass it start value i am going to pass it end value right now lets write the function vst so it is going to return a value of type t not star it's a bste function it's just the name of the function it has three parameters v the start value and the end value so let me just call it s n e for short form right so what is the mid value is simply start plus end by 2 this will be the mid value in case we have okay let's consider this case one two three four five six seven if we have uh odd number of nodes right so the indices will be zero one two three four 5 6 this will be the indices 0 will be the start value and end value will be 6 right and then the mid value will be 0 plus 6 by 2 which will be 3 right so this is fine this works for this case but let's say you have even number of nodes okay let's say you have nodes only up to six so in that case what will happen your end value will become equal to five and your start value will be equal to six in that case your mid value should still be three okay it is given in the question that your mid value should point towards the index three it is uh skewed towards the left on the left you have more nodes compared to the right okay so uh the mid value is four but on the left you have three nodes on the right you have two nodes it is given in the question it is supposed to be like this okay so but if you apply this formula right what is your start value is 0 and what is your end value and value is 5 so 0 plus 5 by 2 if you do this you will get 2 right which is wrong because your mid value should be technically 3 so that's why we will add s plus e plus 1 by 2 for even cases also and odd cases also it will satisfy the condition so 0 plus 6 by 2 will be equal to 3 so it will be fine okay so that's why the mid value will be this now we have the mid value now it's very simple so whatever is the value at the middle of that in the vector right that will be the value of your node so we can just use the constructor function of the node and we can create a new node and let me call this um temporary node right so let's call it temporary node and we can create a new node at whatever value we have at the mid value right and now how to find its left and right side it's very easy if you have to find the left child of this template you know just call the function bst function again but this time your start value will remain same but your end value will be on whatever is on the left of mid because only on the left of mid you have value smaller than mid it is sorted in ascending order right so that's it and similarly on the right side if you have to find the values you have to just keep the uh starting value is mid plus 1 because only on the right side of mid you will have values greater than that should be placed on the right side okay so the logic is pretty simple that's it and finally you can just return temp now what is our base condition the base condition for this to end is simply if your starting is ever becoming greater than n this is not right your starting value should never become greater than n value if it becomes then you can return null there are no more children of it okay that's it this is a simple code now let's compile and run and see if it's working so that is some error let's see what is the error no matching function to call push back and okay so it's head so it's unfortunately its data type i have pushed the head but it's an integer type right i should push the value of whatever is there of the head so it's a silly mistake let's run see it should be fine now it's fine right let's sum it and see it should work for all the given test cases hopefully so it's working thank you for being patient and listening
Convert Sorted List to Binary Search Tree
convert-sorted-list-to-binary-search-tree
Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** head = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST. **Example 2:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in `head` is in the range `[0, 2 * 104]`. * `-105 <= Node.val <= 105`
null
Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Medium
108,2306
223
hey everybody this is Larry this is day 17 of the liko day challenge hit the like button and the Subscribe button join me on Discord let me know what you think about this problem um okay is it only what's going on here um okay what am I doing oh yeah checking for the extra coins nope um okay so yeah um what am I doing okay so it's rectangular you have two rectangles and you're trying to find the area behind it covered by the two rectangles the couple formulas that you can use here will see kind of what we want to play with um it only goes up to 10 to the fourth though I think we can probably generalize I mean it's just the area of the two triangle uh triangles rectangles and then the intersection right the tricky part of course is going to be figuring out uh how to do the intersection and of course it's not that hard per se in terms of understanding right I don't think there's some high level algorithm algorithms here um or you know it's just basic things that you probably learn in fifth grade or something like this I don't remember when they teach that stuff the tricky part of course in um you know as a programmer is making sure you get all the base cases and that of course is going to be a little bit tricky so okay so let's uh I mean let's jump right into it right um I think it's just about being careful and stuff like that um yeah let's just jump right into it and do the intersection part right the other two part is pretty straightforward so let's see so in this section how do you want to think about it right so okay I mean this is just two-dimensional uh mean this is just two-dimensional uh mean this is just two-dimensional uh yeah it's a two well obviously it's two-dimensional but how do you the way two-dimensional but how do you the way two-dimensional but how do you the way that I think about these to begin with um no and I as you see here like not like if that was more practice on these type of problems you know maybe it's something that I kind of memorize how to do but as I'm here right now and so I keep hitting the mic so I don't know if that was making a sound but as you can see here I am just trying to figure out from first principles both for myself just because you know that's what I'm doing um and also for you at home because I'm trying to articulate it in a way that is at least reasonably understandable right um because I can just like oh let me download this thing and then see what happens but okay but the first thing that I would try from first principles is to kind of make the problem a little bit easier right and what I mean by that is instead of using two Dimensions I will I would think about using just one dimension right meaning the classic thing of okay now you have two lines um on the 1D number line um what is the intersection right and that you know and that um and that we can do so let's think about it right so let's just say we have intersection X is you go to um what does that look like again so you have um I'm just thinking so to be honest what I'm doing right now is thinking through order cases in my head just to make sure what I'm going to say is correct um so I'm just doing a proof a little bit um base assuming that um let me double check the constraints okay yeah I just want to make sure that they're you know otherwise you have to do a swap which is not a big deal but just a case that you have to handle in that case I think you just take the max of ax2 a y one right and then you subtract it from the Min of oh whoops not I might have X um oh I know wait what um so the first line goes from ax1 to ax2 and then the second line is BX right so okay so someone like this right um so then the Min uh so I'm thinking about let me just draw it out a little bit I'm so you have a and this is just X so you have X1 and X2 right and then you have B let's just say it's here and then you also have X1 X2 right so then here what I'm saying is that maybe I got this wrong but what I want to say anyway is that um what do I want to say in this case but so okay so um so they intersect if X1 is between whatever and yeah is that the only way let me so I want to say that if X1 is between or one of the X1 is between one and the two so is it just max of ax1 ax2 or a dx1 sorry and then Min of a uh yeah ax2 bx2 is that right is that oh it's right um let's play around this way and then of course y would just be the same thing um my visual visualization today is very bad so yeah so then of course then now you just it becomes easy if this is correct right um and really the only four cases right there's this and then the other one so we just have to prove that this is correct for the all of them by maybe just enumeration and in the other cases you know something like maybe another way of just doing this is just that this is B and this is a right um is this still true hmm no I don't also can do wipe it um yeah this seems like it's still true and then the other case is of course um well I guess there are more than four cases maybe I'm one uh now that depending on how you want to say so you have this where you know and then of course the swap version so maybe I just won't do the swap version but okay in this case um yeah that is still true and I assume that it's going to be true for the B as well because we don't have it we have symmetry here so that's good um yeah and then the other cases if they don't intersect right I think that case we have to care for be a little bit careful um yeah right like if you have something like that and then B is here then what happens well then what happens is that this element minus this element is going to be negative right so we should definitely keep track of that um but yeah um Okay so let's just say intersection is decode two dude right and maybe if this is less than or greater or if this is I mean I guess if it's zero intersection zero anyway so but uh and then now we just return the area which is um ax two minus ax one so you know this is just regular formula maybe I could do an area here just to kind of make it slightly easier and this is you know I hope I don't have to explain this um they usually give it to you in another way because of the points but I yeah well I screwed it up a little bit it's fine right so someone like that we'll see if it's good okay it's good for these cases but you know that doesn't mean it's good but it does mean I'm lazy so I'm going to submit and see if I get missed an edge case that looks good cool uh with ASCII art and everything um so I think the takeaway here I mean this is our one we do like five operations or whatever um someone like that uh yeah the takeaway is you know um see if you can you know the key part for me is always going to be the visualization and once you understand how to build things from components then it becomes easier to kind of like okay you know add yourself a and then B and then C versus like this big problem with many and just try to figure out interactions even though the interactions are sometimes needed and hard um that's for harder problems but for problems like this yeah if you're able to just boil down to its components I think it's probably fine I think the thing that I um yeah and this one I think is pretty okay to kind of just prove by yourself as I kind of did right like I kind of like I think some I'm not gonna lie some of it is that like I have some experience of the 1D version you know just if I'm doing a lot of prime so I have some like subconscious memory there I'm not gonna lie about that um because I feel like that's right um before I even test it to be honest um and that just comes from my experience like not gonna you know lie about that per se but still like me having my gut saying that this is probably right and actually proving it well sometimes the proof is just as easy as going through all the cases um so I'm happy about that um yeah um cool that's all I have for this one let me know what you think I'm not going to do an extra prompt today because I'm a little bit late to the gym and trying to sleep early or some something like that so let me know how it goes um stay good stay healthy to good mental health I'll see y'all later and take care 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,766
so hello coders welcome to my channel and in this video i will be explaining the problem tree of co-primes the problem tree of co-primes the problem tree of co-primes and you know to be honest it is a really tough problem because not only it is difficult to think about the approach that what you have to do but even if you arrive i haven't have a clear idea that what you have to do then also it is a little bit difficult to convert that idea into an algorithm i myself struggled with this problem for around three four days and numerous discussion uh like posts before arriving at the solution so in this video don't worry i'll be explaining i will be mostly writing the code and explaining it with this example so that the approach is clear to you so let's briefly discuss that what i am going to do and like how i arrived at the solution so you know the main idea to solve this problem is to keep track of the corpora ancestors keep track of the ancestors okay so you know first of all the first process to solve this problem is to create a co-prime co-prime co-prime uh co-prime table so basically for uh co-prime table so basically for uh co-prime table so basically for example in this case uh the i have an array okay and using this nums vector i will create the co prime of all the numbers so for example 3 has co prime in this array 3 has 2 10 and 5 are the co primes of 3 okay 15 has 2 has 3 15 and 5 so you know it's pretty clear now the second step is to make a adjacency list okay so in the problem i have been given information in this form and edges form so using the edges only the edges i will create a adjacency graph adjacency list so which will look something like this it won't have these numbers 5 its value so but values can be found out using the nums vector that is i have you i have to use 0 like 0 represents 5 represents what 6 so this is how i have to use this adjacency list the second step is to traverse and the most important step the fourth step is to take care of the ancestor so how we are taking care of the ancestor is that for example suppose i am at zero okay so right now my adjacent ancestor table will be empty so what i will do is that i will come i come at this node i say that okay five has co primes three two six now in the ancestor table i will find that do 3 2 and 6 exist in the table or not if i get the answer yes they do exist then i will try to find out their index like that so that's what i have to fill for example in 5 there is doesn't exist anything so i will fill in my resultant table minus one now what i will do is that i will in my ancestor table i will add five and then i will go to the child okay so if the child has five as its ancestor and in the ancestor table both the child okay now i have six i know six has a co-prime now i have six i know six has a co-prime now i have six i know six has a co-prime called five and five is the ancestor because how i can find it out because i will see in my ancestral table 5 exists if 5 exists i will go and fire fill the index of 5 that is what 0 in 2 for 2 is also a co prime of 5 so i will fill 0 again now what i will do is that i will add down six to the uh ancestor matrix so now the three has five and six so you know like this i am i keep on adding the ancestor in each recursive call and then at each node i see and check in the ancestor table that whether this node exists in the table or not so you know the structure of this table is going to be like this number and a vector in a pair of vector it will be a map so it will have the following values in the pair the level of the ancestor and the index source is the index okay so you know to explain this problem uh more efficiently i will code it on so that the video is doesn't extend excessively and i will explain it more in detail as i could okay so as i said my first step is going to be calculate the coprime table so how i'm going to calculate the co prime table is that first of all i will make a an ordered set unordered underscore set on order set int and i will name it co-prime will name it co-prime will name it co-prime okay so just one second another an ordered map uh unordered map i'm sorry unordered map uh into comma vector of int okay so you know this uh this is going to be my co-prime table my co-prime table my co-prime table the first parameter is an integer the second parameter is a vector okay so how we find so this co prime just let me increase the font uh 15 okay so how i'm going to find my co prime is i will make an unordered set unordered ordered set into s and for end i is equal to 0 i less than nums dot size i plus and i will add num so s dot insert into the my unordered set nums i and now what i'm going to do i'm going to traverse this set and make the co prime number so for a auto n1 in ns for auto n2 in s so if the underscore gcd so this function is used for calculating the greatest common divisor between any two numbers n one and n two is equal to one that is a greatest common divisor between two numbers is one that is like they don't have any other divisor it means they are co prime then what i am going to do is that co prime n1 dot push underscore back n2 so now just let me explain that what i have done so far so i made an unordered set uh and what i have made this because see i have to make this table okay and it can happen that in my nums vector there can be for example 10 there can be multiple tens okay so there is no point in making multiple tens like again i will write down 10 and 3 here like multiple times if there are multiple times so to avoid that i have made an ordered set of s size and then i have filled it uh inserted my the numbers and nums and then in the set what i have done this i choose a number for example i choose a number 5 and then i will move do a square a loop and see which numbers are the co-prime of 5 using the gcd function co-prime of 5 using the gcd function co-prime of 5 using the gcd function and then i put it in the map so that's all i have done so if you have any doubts feel free to like write in the comments i'm trying to make this video short because this is my second time recording this video and another video went on to 30 minutes and i don't like it so now my second step is to make a resultant array vector interest comma nums dot size it will be of nums dot side and i will fill it with minus one why i have filled it with minus one is that uh you know just to make sure like uh each will if some number has don't have a co prime okay so it will by default be minus one okay so if a number doesn't have any co prime to fill it at that time with minus one i am already filling it with minus one so my second step is now to now the second step is to create the adjacency graph okay which is going to be like this okay so to make this what i'm going to do is that i will just it is a pretty normal procedure probably a vector of vector int adj dot sorry nums dot size num slot size okay so to make the adjacency graph i will use the edges vector end i is equal to 0 i less than edges dot size i plus in that i will create another vector and e is equal to edges i so you know it's not really necessary to make this vector but just i feel it easier to explain and explain this way so uh adjacency e 0 dot push underscore back e 1 okay and ctrl c ctrl v 1 0 so like you know uh i hope you already know this if you are watching this video what is happening here so you know this what this does is that it helps me makes this adjacency matrix uh like this graph basically okay so now my second step is going to be now i have to traverse this whole adjacency graph and do the thing that i am doing so for that what i will do is that first of all i will make my ancestor table okay so what it is going to look like is on so you know right now the important part begins unordered map of int comma vector of pair int and it okay ancestor okay so i think the uh this arrows are good one two three fine okay so this what these are these each number significa signifies that the first integer means that the number okay and the second in the vector the first uh pair me the first of the pair means the level of that current number and the second one means the index so you know that you have to uh update the second one matlab means that this integer is going to be the index for example uh when i was uh post uh putting my uh five in my ancestor after like six after visiting its notes what i was putting was that five zero it will be its current level and zero will be its index so you know this 0 is i have to put in my what array if i if 5 is a coprime of some number so just let me code it so i will make three parameters in my dfs i will make a dfs function so it will have three parameters dfs level is equal to zero you know some traffic is outside my house close the windows okay so inc level is equal to zero and uh in source is equal to zero int parent is equal to zero okay now what i'm going to do is that i am going to pass these three parameters in my dfs function so dfs nums edj source parent level res okay and in the end i will return my res so let's make this dfs function so in this dfs function void dfs vector and ampersand i just have to copy this thing actually ctrl c ctrl v uh nums vector edges and adj in source into parent int level comma vector int ampersand res okay so now i am in my this is the main function so first of all how do i find the ancestor of any particular uh so suppose you know it always gets some messy even the last time when i was explaining it got a little bit of messy so uh anyway uh what happens is that suppose i am at any node i have to now i have to find its ancestor okay so uh a number can have many ancestors okay you know this so for example uh let's say two has and then uh co primes three fifteen and five so suppose this was a fairly large tree and there were these all these ancestors present so i you know well what in the ancestor table i will hit all these ancestors 3 15 and 5. so you know i have to choose the one that is the nearest to the uh my two's level okay so this level is one this level is level one this is level zero this is level two so and each uh level it will be increasing suppose this is level eighty so suppose uh i'm at level 80 i will have to choose the highest level for example 78 if some co prime is present in level 78 in the ancestor list so i will have to choose that one rather than the one that is present in zero one or two so to do this what i am going to do is that i will create a variable into max level it will tell me that the max level that i am getting right now so for initially let it be minus one uh because like each has a my uh like we are starting from zero that is why so now what i have to do is that for int i is equal to zero i less than co prime what co prime uh just one second yes so co prime of source so here i was supposed to write co prime nums source uh i have done this mistake and in this line also i had to write coprime nums source uh i have explained it this in the end of the video but this was a mistake on my site uh where when i was coding that for example so five will be having three to six so this will be the size that co prime dot size and cop is going to be each of these co primes so first i will check if in my ancestor list there does there any ancestor with value 3 any ancestor with value to any ancestor then i will go on to six so that's what i am doing and if uh is not ancestor uh ancestor co prime uh one second co prime dot empty so basically it means that if the ancestor of that number co prime is not empty i mean it means that there is something and ancestor dot ancestor cop dot back dot first is greater than max level then what i have to do is that i have to update my max level is equal to this thing dot first control c is equal to control v and i also have to update my result so result source i have okay result source is equal to uh the same thing ancestor dot second okay so you must be having question that what is this thing okay so ancestor cop dot back first means that uh for example if you see for example just like uh take the number five okay so what is five going to be uh look like is that the any first one is five zero comma zero okay so the first one means the level there are there can be many ancestors whose number is five okay so one ancestor can be at level zero one and sister can be at level two and its index can be something x so another ancestor can be suppose at level 75 and its index can be something 100 say 100 so you know i since i already have this last one it means that my current node the node that i am looking has a level higher than 75 you know so if uh it has a co prime called 5 it will be in my best interest to choose the one with is the highest level so the highest level will always be the back one so vector dot back so this is the dot back points to the last entry in the in my pair of vectors and this is going to be its level so if the level uh if its level is greater than the max level then it means that okay i it's time to update the max level and 100 is going to be the index that i have to fill in my resultant table okay so that is the toughest part of this problem to write this piece of code and now what i have to do is that i have to add the current node into my ancestor table so and then i have to traverse so ancestor uh nums src num source okay dot push underscore back uh level comma source uh okay so done and now i have to do what i have to do is i have to make a for loop auto child adj src so this is basically a depth first search and i know you know it if the child is not equal to parent then what i have to do is that i have to do a dfs numbs so the new source will become what for the next recursive call the new source will become the child the parent will become the source and level will increase by one and res will be the same and after that call from one level is over i have to pop back the uh the current node from the ancestor table why i am doing is that or doing this is because pop back uh doing this because see this ancestor is a global variable if it was like i was yes if i was passing it locally from this uh like locally from each call to each uh from in using a parameter in dfs then it would have been fine if i don't write this thing but since it is a global one i have to like pop back the what pop back the current node so if you do a little bit of try run you will realize it so now just let me run this code to see if the algorithm that i have coded is correct you know it may have mistakes so i push back okay it should be back okay insert back i hope it runs push back oh sorry i'm so sorry i had to write pop you know it happens when you are trying to speak and code and explain adj undeclared identifier okay now i have not identified it here oh god why is this wrong now okay so what i was doing wrong here is that it has to be nums src and it also has to be nums src so this was the mistake uh so basically what i have to do is the num sign of src i hope it works okay it is working now let me submit it okay so it is passing the code so you know what mistake i did was that it is nums src so nums src means uh like i have these numbers zero okay so for example i am at two okay i am at two now i have to find the co prime not of 2 but the number that is present at 2 so the number that is present to a 2 is 6 okay so 6 is 5 the number that is present at 2 is 6. so you know that's why i had to write nums of src okay so you know like even if i knew what i am doing then also some mistakes are bound to happen yeah because uh because you know it's quite difficult to implement so i hope the solution is clear to you if you have any doubt you feel free to write in the comment using the time stamps where you are having died or doubt i will try to clear them okay folks so that's all for this video it has been already in a pretty long video so if you like this video please consider subscribing the channel and thank you and have a nice day
Tree of Coprimes
minimum-number-of-removals-to-make-mountain-array
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` edges. Each node has a value associated with it, and the **root** of the tree is node `0`. To represent this tree, you are given an integer array `nums` and a 2D array `edges`. Each `nums[i]` represents the `ith` node's value, and each `edges[j] = [uj, vj]` represents an edge between nodes `uj` and `vj` in the tree. Two values `x` and `y` are **coprime** if `gcd(x, y) == 1` where `gcd(x, y)` is the **greatest common divisor** of `x` and `y`. An ancestor of a node `i` is any other node on the shortest path from node `i` to the **root**. A node is **not** considered an ancestor of itself. Return _an array_ `ans` _of size_ `n`, _where_ `ans[i]` _is the closest ancestor to node_ `i` _such that_ `nums[i]` _and_ `nums[ans[i]]` are **coprime**, or `-1` _if there is no such ancestor_. **Example 1:** **Input:** nums = \[2,3,3,2\], edges = \[\[0,1\],\[1,2\],\[1,3\]\] **Output:** \[-1,0,0,1\] **Explanation:** In the above figure, each node's value is in parentheses. - Node 0 has no coprime ancestors. - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1). - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor. - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its closest valid ancestor. **Example 2:** **Input:** nums = \[5,6,10,2,3,6,15\], edges = \[\[0,1\],\[0,2\],\[1,3\],\[1,4\],\[2,5\],\[2,6\]\] **Output:** \[-1,0,-1,0,0,0,-1\] **Constraints:** * `nums.length == n` * `1 <= nums[i] <= 50` * `1 <= n <= 105` * `edges.length == n - 1` * `edges[j].length == 2` * `0 <= uj, vj < n` * `uj != vj`
Think the opposite direction instead of minimum elements to remove the maximum mountain subsequence Think of LIS it's kind of close
Array,Binary Search,Dynamic Programming,Greedy
Hard
300,875,882,978,1185
426
okay so lead code practice time convert binary search cheat to sorted double linked list uh as usual two goals the first of all it is to find a solution to do some solid code uh in the lead code platform to solve this problem and the other thing is to see how to solve this problem in the interview properly so as usual the first step in the interview is to understand the problem and clarify uh some clarification questions in case there is anything you don't understand and also think about the ash cases so let's see um convert the bst to a sorted circular doubly linked list in place you can think of the left and right pointer as synonymous to the predecessor and successor pointers in double link list for a circular double a linked list the predecessor of the first element is the last element so the predecessor of the first element is the last element and the successor of the last element is the first element so that's a circular double a linked list so we want to do the transformation in place after the transformation left pointer of the tree becomes uh should point to its predecessor okay left pointer point to predecessor right pointer point to successor okay so you should return the pointer to the smallest element uh you should return the pointer to the smallest element of the length list okay uh what's what does it mean like the smallest element of the linked list let's say oh smaller smallest linked list which means the leftmost node because it is a bsd all right so um this example i think is pretty clear and it says no value is within minus 1000 to 1000 and as always since it's a bst so this should be always true and our values of the node are unique okay and number of nodes are between zero to two thousand which means it could be uh a num pointer for the input okay so i will say the ash case for this one what if the root is an end pointer that's definitely something we need to take special care of so i would say if root is equal to none then we certainly just return root itself and the next thing after figuring out what the problem is asking us to do the next thing is to find the solution for this specific problem so for this one i would say um it is most likely a leftmost traverse of the tree using dfs left first so left first try bus using bs using dfs on the tree and during this time we can return so during this time we will alter the pointer relationship in place at the same time uh so for this one the runtime is going to be linear to the number to the size of the tree linear to the number of nodes within the tree um space wise since this we alter the changing relationship in place we may need to introduce some time pre-thing need to introduce some time pre-thing need to introduce some time pre-thing some temporary uh temporary local variables so maybe it is a constant regarding the space complexity so all of n for time is the number of nodes and the constant for uh space so then we are going to do some solid code to turn our idea into code here we care about the speed the correctness and the readability so let's get started and give with the shot so this is the ash case processing and we are going to define another function let's call it uh dfs so in the dfs function we are going to reply return a pair which is the last and which is the first element and the last element so let's define the class first let's say define the clause as pair and it has two things one is uh a the first node and the other one is the last node and we are also going to have a constructor for it let's say we are going to so know the first and then now the last and this the first is to go first and this the last is equal to last all right so we are going to define the dfs function so input parameter is going to be the root so uh and in here in the tree to double a list function we are going to just return dfs root and it's going to repair turn a pair and we are going to get the first for it so let's try to finish this helper function which is dfs how to do it so first of all for recursion um we need to consider the axis so the axis is if it is a leaf node so suppose root it is a leaf node which means the left pointer the left child is none uh and the right child is also none then what we are going to do so we are going to uh point the left uh pointer and the right pointer to itself so this one root dot left would be equal to root and the root dot right is equally root that's a double a linked list and then we will need to return um a new pair with the first one first uh first one as root and the last one as for as root as well so that's essentially the exit and then we are going to traverse the left tree um in case um the left child is not none so let's say left tree defined as a num pointer so um if root dot left is not equal to none then we need to definitely do some trivessing um so let's say if it's not none then we return a uh pair so which is a uh okay so this is this should be definite pair so left tree would be um dfs left so then what we are going to do is we are going to point the left tree dot right would be equal to node unto that sorry to the root and the root dot left would be pointer to the uh sorry uh it should be left tree dot last dot right is equal to root and the root that left is equal to left tree dot last okay and same thing we are going to do the right tree so if uh okay so if root.right okay so if root.right okay so if root.right is not equal to a nun pointer so we are going to say okay right tree is equal to dfs root.right is equal to dfs root.right is equal to dfs root.right and now we are going to say okay root.right would point to root.right would point to root.right would point to right tree dot first and the right tree dot first uh right tree dot first dots left would be uh root okay and finally we are going to connect the first node and the last node so um i will say node um first is equal to so if left tree is not is if last tree is none then definitely it is a root itself otherwise it is left tree dots first and now the last is red tree is none if yes then it is definitely the root otherwise it is right tree dot last so we are going to see okay first dot uh left is equal to last and last equal right is equal to uh to the first and uh we are going to return new pair which has the first and the last okay so that's pretty much it about this one uh let's so after we are done with coding it's time for us to do some testing so usually uh we need to explain how this piece of code works by going through an example task is um to do some sanity check and then we are going to set up task cases to make sure that it has good enough test coverage so first of all uh if root is equal none we return itself this is the add case we need to consider in the test case setup then we have dfs root first so actually we just need to mainly need to um inspect the logic in this dfs function so uh in the dfs function if a root is a num la if it is a leaf pointer then we just self connect it to it and otherwise um so suppose it's uh it's a single node tree then it is good enough um so let's see if the given for this given example let's say if left tree so left tree for this for the this root node the left tree is one two three and uh let's see we go to the left tree for it left trivial called dfs or the left which is this one so similar so let's assume that dfs is going to give us one two three here so what are we going to do we are going to set the last note which is three and this right pointer is pointing to root and the root pointer uh the left pointer of the root is going to point to the left the last one of the last three okay and then we do the right tree suppose it is correct and we get the five return actually should be it should be correct because we inspect the logic when there is a single node within the tree and we say okay so the right root dot right is equal to right tree the first which is pointing to five and the fi this node is for its left pointer is pointing to root okay and uh currently left three and right three are naughty are not none and we get the first node which is left of first which is this one and the last node is right the last is this one and we connect first to left to last and last alright to first okay and we return it this looks to me is good let's give it a shot okay it's accepted and let's do a submission okay it's working so as i said um set up the task is to increase tax coverage i would say definitely set up a nun pointer for the root and also a set of some general test cases like uh example one and uh that should be good enough i would say um but in case you want to set up some other test cases for example if there's no left tree or there's no red tree that's definitely better i would say other than that's it for this coding question i hope you enjoy this video and find it a bit helpful so thanks for watching it and see you next time
Convert Binary Search Tree to Sorted Doubly Linked List
convert-binary-search-tree-to-sorted-doubly-linked-list
Convert a **Binary Search Tree** to a sorted **Circular Doubly-Linked List** in place. You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element. We want to do the transformation **in place**. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list. **Example 1:** **Input:** root = \[4,2,5,1,3\] **Output:** \[1,2,3,4,5\] **Explanation:** The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship. **Example 2:** **Input:** root = \[2,1,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000` * All the values of the tree are **unique**.
null
null
Medium
null
1,962
hey guys today we will solve remove stones to minimize the totals uh you are given zero indexed integer array piles and piles I represent the number of stones of is file and you have given k a integer K where you can apply the operation exactly K times and in any operation choose any piles I and remove the uh that number of stones uh from it that is piles uh pile PSI divided by uh two and floor of it we will take and we have to do return the minimum possible total number of stones remaining after applying the K operation notice you can apply the operation on same pile more than once so here uh because we have to minimize the answer uh possible number of total number of stones here after applying the operation so we will pick the uh piles with maximum value first and then second Max and then third Max in this order we will so let's take this intuitive approach and apply it so what we will take here if you let's first check the constraint also constraint is that 10 to the power 5 length and files of I is 10 to the power 4 values so maximum value total sum can be 10 to the power of 9 and K operation is 10 to the power five so let's start with this one so let's take some as 0 and you have a K operation you have to do but before that we have to take priority queue also prior T Cube integer here and PQ no priority queue and here a because you have to take here Max Heap so you will do uh B minus a okay now uh we have we will take it read all the piles file files and here what we will be doing here we will take some and we will add in priority queue also this file okay once that will be done we will have to do K operation K times operation so here we will be doing K times operation and here we will take a pool uh value here and so here because it is at least one length is there so I think that should be okay and here what we will do we have to reduce from sum this value piles divided by 2 and that is the floor value and similarly we will have to update the value also current divided by 2 and we will add in priority view updated one okay after doing the K times operation we will have to return the sum value let's try to run it okay it working fine and let's try to submit it yeah it's it is a
Remove Stones to Minimize the Total
single-threaded-cpu
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times: * Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it. **Notice** that you can apply the operation on the **same** pile more than once. Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_. `floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down). **Example 1:** **Input:** piles = \[5,4,9\], k = 2 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[5,4,5\]. - Apply the operation on pile 0. The resulting piles are \[3,4,5\]. The total number of stones in \[3,4,5\] is 12. **Example 2:** **Input:** piles = \[4,3,6,7\], k = 3 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[4,3,3,7\]. - Apply the operation on pile 3. The resulting piles are \[4,3,3,4\]. - Apply the operation on pile 0. The resulting piles are \[2,3,3,4\]. The total number of stones in \[2,3,3,4\] is 12. **Constraints:** * `1 <= piles.length <= 105` * `1 <= piles[i] <= 104` * `1 <= k <= 105`
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
Array,Sorting,Heap (Priority Queue)
Medium
2176
1,706
hello everyone so today we are going to do the question where will the Call fall so in this question we are given 2D grid Matrix of size M into n which is representing a box and which has n bonds what we are given is that we are given this box now what is it that if we are given Matrix like this if there is the value of this cell is 1 then this means that what is placed like this if the value of the Matrix is minus 1 then the board is placed like this and if the board is making a size of weight then the ball will remain Inside the Box only it will not come down so how can we just do this question so for this question what we can do is since we can say that if a question if a matrix has one in it then that means it has this type of board this means that if this ball will fall here then it will go to which side it will go to right side from left to right so that means if we have one then we are going from left to right side same for minus 1 if we have minus 1 then that means that if a ball Falls at this board it will go from right to left side so if we have minus 1 then it means that we are going from here we are going to this direction and here we will go from to this direction from right to left okay so this is the main Crux of the question so how will we solve this since we have to return an array that if this ball Falls from here from which column it will come out like this always will come out from column number one so in Array we will have column number one for this for the index 0 okay now how can we do this question there are only three conditions for every port okay what is that condition it is that if it is a minus if the value of the Matrix is one then the ball will go from left to right and if the value uh is minus one then the board will grow then the ball will go from right to left what will happen if adjacent matrices have the different values suppose here there is one and there is a minus one then what will happen that it will make a V shape because of this because of one the body will go from left to right and because of minus when the body will go from right to left which will cause the ball to be stuck here and it will go nowhere else okay so this is the condition here and if the ball Stacks um here only then we have to return minus one okay now what we have to do if the adjacent values have the same value suppose one and one then what it means that all will go uh go down okay like here if they both are one then the body is going from here to here and then here then again it is one and it is also one so they are going again the same thing is happening here it is -1 and here also is happening here it is -1 and here also is happening here it is -1 and here also minus one so same thing is happening okay when there are same adjacent sides either it is one or minus one then only the ball can travel further otherwise if the adjacent uh matrices have different values then it means that it will definitely stuck and we have to return the answer as minus one okay so let us uh see the code for it first of all what we are doing that we have given a function of uh fine point in which we have to return a vector of int which will contain the values of the column from where the ball is coming out okay so we are given a grid first of all we will take out a row and column because we have to uh see for each row and column now we what is given in the question that we have and balls means that we have the balls are same as the number of columns because each ball will be because of the Box is open from up and downside so the each column will have a ball which will be well which we will throw from Up side and we'll come out of down the Box okay now we are taking row and column and we are making a vector of int which will have um the same number of um values as columns and we are iterating till the column and in each for each array or for each value we are what we are doing that we are storing the value of this function into the answer of J means for the problem number 0 means we will throw one ball from the column number zero and from if the result of this function will return that from which column did the ball came out or it will return minus one if the ball stuck uh in the world okay so uh now we have to see what this function does so uh this function does the same three cases okay what else that is it takes I and J so it takes row number column number and the grid okay and what we are checking is first of all we are checking if the row is greater than equals to grid dot size means we are coming out of the bounds of the Matrix then we'll return automatically J because if I is greater than equals to grid dot size means if I is greater than J then we have to just return J okay we have different in the column number and since when we are going left to right means when we have one okay then we are going from left to right so in this situation we have to check that uh both adjacent matrices should have one and one in it then only we can go to from left to right so what we are checking that greater 5 I and J should be equals to 1 and grid of I and J plus 1 means second column also should have same one and because in this question what we have to check if uh suppose the VR in the last this is the boundary of the columns right if we are here then we have to check that whether it is not going out of bounds or not so we have to also check this condition also here that J plus 1 should be inside the bounds of the column number okay so it should be smaller than grid of 0 dot size okay means column with the number of columns The Matrix has now if uh this condition satisfies that means the ball will go down okay since when we were going down the Matrix that means when we have both 1 then what the ball was doing ball was coming to this Index right it was coming to this index means that J was also incrementing plus 1 and the row was also incrementing plus one okay so what we'll have we have to call the same function for I plus 1 and J plus 1 and again passing the grid to it now when we were checking for a right to left that means both the columns should have minus one adjacent columns then only the result or the ball will go down to the right side okay so here we are checking that grid of I and J should be equals to -1 and grid of I and J minus 1 because -1 and grid of I and J minus 1 because -1 and grid of I and J minus 1 because the ball is going from right to left side so we have to check this is J so we have to check J and J minus 1. okay so here we are checking for J grid of I of J and grid of I of J minus 1 4 should be same that means both should be minus 1 and here because we are going from the right to left so we have to check for this boundary that means J should be J minus 1 should be greater than 0 right greater than or equals to zero then only this condition should satisfy otherwise this will give out of forms exception or segmentation fault okay then when we are going uh to this direction then what we are where we are heading to when we are going to this direction that means like here we can see that both are minus 1 right so here we are going here okay so J is decrementing J was here and J became then J minus 1. so J is becoming J minus 1 and I is becoming I plus one so here we will call the same function but what will we pass for J minus 1 and what will plus where I plus 1 and we'll call the same function okay so here we are doing the same thing okay first of all great I will take this so yeah here we are doing this I plus 1 J minus 1 and then great okay now these two conditions are checked that if both adjacent sides are minus one power plus 1 and plus one now what was the third thing which was left that if the ball is what will happen if the ball is stuck that means if the ball will struck then we have to return minus one right then the ball will stuck first of all here we have already checked if the call has stuck or not because if the ball is stuck then it will be minus one or one n minus 1. so if both will be equal adjacent sides will be equal then it will go either to this uh into this definition or into this if condition and if both will be different like this then only we will come to this condition now here what we are checking the grid of I of J is equal to 1 and J Plus 1. uh and J plus 1 is greater than equals to grid of size minus 1 means that we are checking for this boundary if J is equals if uh the grid size is equals to 1 and we are into this position that means here we are going from left to right so it will go out of boundary here what we can see that somewhat this situation has happened that ball is stuck here so if the ball is stuck here then we have to return minus one so what we are doing here we are earning minus one and else if the ball is stuck in this side that means the grid is equal to equals to 1 and is equal to minus 1 and the Polish step in this side then we can also return -1 for this condition also and return -1 for this condition also and return -1 for this condition also and this condition is already returning our index of the column okay so this was the question now let us see what we are doing again let us see what we are doing we are taking n for row M4 column and we are making a vector of a vector answer which will store the result for us we are iterating through the column the number of columns and we are storing the result of this uh function into the array of I it will either result this function will either return the index of the column or it will return what it will return minus one okay then we are returning the answer what this function is doing it is taking the row column and the grid if the I goes greater than the grid dot size then we will return J okay means the ball is out of the box and from which box it is coming out from which column it is coming out will return it from here and then what will uh what here we are checking if both adjacent elements are one and we are also taken because they are going from left to right side so we are checking that it should not go out of bounds from left side from right side okay here we are checking that if both are adjacent at minus 1 and minus one it should not go to uh out of thumbs from left corner of the Box okay and we are again calling for the next iteration here and then we are checking if the ball is stuck to the either the left side or the right side of the array for both situations we are returning minus one because for this equation what is happening here that the ball is stuck okay now we will select the code yeah except
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
922
hua hai hello everyone hindi player am going to explain about shot are brother party software give no insight into the shoes of no anchor for the one more subscription 14257 24247 more fuel pimple 232 to 234 quinton points and who is the logic state today at andheri West * create equal to today at andheri West * create equal to today at andheri West * create equal to a 101 121 and foreign that equal to phone number start length ok and n to boil that I love to prohibit 10 and a game wild that I lash 0 that henin fennel ias that dad with me to difficult that than a high -quality only to 2 and can yes brother absolutely ki jai left and a corporation staff j hai motu hu is equal to one oo ki sister ko z plus seat world you to and can the are maintenance gift that pilot training j electronic aslap phone The number came six were the software of Amar Singh written statement in that and share all the records of the public on a private wide aslap Jai Hind is interact ki Namaskar Mama Health Hello Hi Kama Health Ja hai to Hindutva eminent a temple should name saunf y0 of Equal to 60's name was Asaf 60 's name was Asaf J 's name was Asaf J 's name was Asaf J Aquarter a time called logic mobile check with solution is right or wrong on torch light effect phone number electronics scores for spirit to create two variables water to zinc more than 120 plus 2 and share And Subscribe To Ko Unfit Pimple Itna Result Value Is Equal To One Should Be Stored In The State And Tours And Travels In Every Element And Will To According To Benefit Condition Satisfied The Government Will Wake Up Sid Love On The Remains Of 250 Wickets 747 Office Saat Chaar 7582 108 Hindus Were Getting Out To Please Like This Is The Country Which Country Please Like Subscribe More Videos A Hua Hai
Sort Array By Parity II
possible-bipartition
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums = \[4,2,5,7\] **Output:** \[4,5,2,7\] **Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted. **Example 2:** **Input:** nums = \[2,3\] **Output:** \[2,3\] **Constraints:** * `2 <= nums.length <= 2 * 104` * `nums.length` is even. * Half of the integers in `nums` are even. * `0 <= nums[i] <= 1000` **Follow Up:** Could you solve it in-place?
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
500
hey guys in this video i'll be going through how to solve leapfrog question 500 called keyboard row um so the question is we're going to be given an array of strings and we have to output an array of strings with all of the words that could have been made up with only one row of the keyboard so in the example here we were given hello alaska dad and peace um and then we output alaska and dad because those two could be made on just one row of the keyboard and they don't necessarily have to be the same row either but then you can see like hello would not be right because the h and the e are on different rows um so to solve this question we'll essentially want to make like a hash table to store um for each letter in the alphabet which row of the keyboard it's on um so i'm just going to paste this in so you guys don't have to watch me type it all out but essentially what this does or what i did here um first just made a array for our output and then i made an unordered map which if you guys don't know what this does um it'll just set the letter equal to the number so if we want to grab from our map um whichever row like f is on it'll tell us that it's on row 2. um so with this we can just kind of like loop through all the words and all the letters for each word and check to see if they're all equal and if they're all equal then we know that they're all in the same row so i'm going to define a starting num variable so that'll be set to whatever like the first letter is then we're just going to loop through each word in our words array and starting num is just set to um rows is our unordered map and it's going to get the value of the first character um and i set this to two lower because i believe this ignores capitalization um we can then define a boolean um call it one row set it equal to true so this will tell us um essentially if they're all the same and at this point they would all be the same because we've only checked the first one so now we'll just loop through the rest of the characters in the word um starting at one since we already have zero so now we just want to check um if they're not equal to each other so if um the current one would be rows to lower again word i so this is like the current character set to lower case and then get the whichever row of the keyboard it's on and then if that is not equal to our starting num then we can set our boolean equal to false and we'll just break out of this for loop because we don't need to check anymore once one of them is false then after the for loop we'll check if one row um and so if this was true um then we didn't reach any characters that were on a different row and so we need to push the current word to her output okay so then once we've looped through all of the words in the given word array we should just be able to output or return our output vector and that should be it so for the complexity of this algorithm um i'll start with space so the only thing we're storing one obviously is the map however this is just constant because it'll always be the same map no matter what our input is and then we're also storing the output which will depend on the input but this will only be could only be as big as words which is going to be linear so our space is oven and then for the time complexity we are going to run this for loop once for every word in our word array and then we're also going to be checking every character so we can say it's n times m time where n is the length of words and m is the length of the longest word in our words array all right and i think that's gonna do it so thank you guys for watching and i hope this was helpful
Keyboard Row
keyboard-row
Given an array of strings `words`, return _the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below_. In the **American keyboard**: * the first row consists of the characters `"qwertyuiop "`, * the second row consists of the characters `"asdfghjkl "`, and * the third row consists of the characters `"zxcvbnm "`. **Example 1:** **Input:** words = \[ "Hello ", "Alaska ", "Dad ", "Peace "\] **Output:** \[ "Alaska ", "Dad "\] **Example 2:** **Input:** words = \[ "omk "\] **Output:** \[\] **Example 3:** **Input:** words = \[ "adsdf ", "sfd "\] **Output:** \[ "adsdf ", "sfd "\] **Constraints:** * `1 <= words.length <= 20` * `1 <= words[i].length <= 100` * `words[i]` consists of English letters (both lowercase and uppercase).
null
Array,Hash Table,String
Easy
null
1,457
hey everyone welcome back and let's write some more neat code today so today let's solve the problem pseudo palindromic paths in a binary tree we're given a binary tree where the values are only going to be in the range from 1 to 9 and in this problem we care about the paths in the binary tree that go from The Root Down to the leaf nodes we want every single one of those such pths that's one this is another one and lastly this is one as well so there's three paths right and that's because there are three leaf nodes of course now for each of those paths we want to first get the path itself so like one path going down to here is 233 another path going down to this node is 231 the last one going here is 211 the order of these values actually doesn't matter we don't care if this itself is a palindrome we care if we can take these digits and somehow arrange it such that it looks like a palindrome so right now this isn't a palindrome but we know we can rearrange it to 3 2 3 that looks like a palindrome to me and if you don't know what a pal Drome is basically it means if you're going from left to right or right to left it's the same so 3 2 3 reads the same from front to back and back to front that seems kind of difficult doesn't it to take these and just somehow know whether we can create a palindrome from it or not like do we want to rearrange it in every single possibility that can't possibly be efficient and it's not going to be super easy to code up either so that's kind of the hint in this problem that there is a better way to do it we don't want to get every single permutation of every single uh Leaf path so how can we do it well let's learn a bit about palindromes for a second what kinds of paland dromes are there well there are odd length palindromes we just looked at one 3 2 3 there are also even length palindromes like 3 2 3 why is it that we can have palindromes of odd length as well as of even length try to figure it out because look at this guy over here if I get rid of these threes it's still a palindrome like let's think about the base case we just have a single two that's a palindrome look at the other case we have two values they're both two but it's still a palindrome but now if we try to introduce like a three over here 23 that's not a pal Drome why is that why is it not a pal Drome why is 23 four also not a palindrome try to think about it the pattern here is that we can only have one digit that occurs an odd number of times in other words if we were to take any such string any possible string and for every single digit we want to map it to the count of that digit and we must ensure that only at most one digit occurs an odd number of times so if we have this mapping we can then get the number of digits that occur an odd number of times that'll just be an integer so in this uh string down here this is getting kind of messy so let me kind of clean it up a little bit in this string we have three it occurs two times we have two it occurs once that's an odd number of times so we have how many numbers occurring an odd number of times just one so this is a palindrome what about the second string it looks like every one of these occurs once that means we have three numbers that occur an odd number of times this is not a palindrome so let's look at the next one occurs once this occurs twice so we have one number that occurs an odd number of times so this is again a palindrome so we have two palindromes because we have two such paths that have less than or equal to one number that occurs an odd number of times even just saying that out loud is kind of difficult but I hope that this idea makes sense that's kind of the Crux of this problem once we know that we've handled the pal drone part now it's kind of the easier part like how do we get every single path down to every single leaf node we can do a very simple in order traversal and the best part about that is we don't even visit multiple nodes twice because we'll go down here pop back up then go down here then pop back up and then go down here we're not processing a node multiple times therefore the time complexity in this problem is going to be Big O of n you might think the hashmap is going to increase the memory complexity it really doesn't because remember we only have nine digits the hash map isn't going to be very large but there is something that does affect the memory complexity the fact that we're going to be using recursion to Traverse this tree means we might have a call stack that is as large as the height of this tree therefore the memory complexity is going to be Big O of the height and in the worst case the height might be equal to the number of nodes so you can either say it's this or you could say it's Big O N in the worst absolute case okay now let's code it up okay so the first thing I want to do is declare a hash map so I'm going to create a hash map just like this I'm going to call it count and I'm actually going to use a default dictionary because it's just a bit easier it's going to be default dictionary of integer this means that like if I were to do something like this count of let's say five or six and then add a one to it we'd get an error because what this is doing is this and this will give us a key does not exist error but with a default dict this will return zero by default even if the key doesn't exist and that just makes things a little bit easier it removes the need for us to do an extra if statement the other thing I'm going to do is have a variable which will tell us the number of digits with an odd count okay with that out of the way let's start with the recursion let's do our in order traversal or DFS I guess I'll just call it DFS because it's a bit shorter and we'll pass in the current node and ultimately we want to call our DFS on the rout and then return the result okay now the simple base case is always if not Cur let's return zero we have an empty tree and that's how I'm going to handle it though I will say there are probably multiple valid ways to handle the base cases for this problem now if the node is not null then let's get the count let's get the value of the node and then increment the count so let's say current. Val let's add one to it okay now this part I didn't actually talk about in the drawing explanation but how do we want to manage this odd I kind of talked about it like we're going to create the entire path then we're going to read all the values at the end count them and that will tell us what the odd count is but we can actually compute this as we go we don't need to maintain all the nodes in the current path that we are on we can do something kind of clever if now after incrementing the count of this value if now it is an odd number we should probably increment odd right we have one new number now that is odd now in the opposite case what if we had an odd number like what if we counted some value has an count of one it occurs one time therefore it occurs an odd number of times but now we see that same number again now we have a count of two for that number now it occurs an even number of times therefore in this case we should probably decrement the count of odd right this is probably the most confusing part of the problem but think about it draw it out and I guess just to walk through it on the left side over here when we have this two we have two occurs one time it occurs an odd number of times when we have this three it occurs once it occurs an odd number of times so at this point we would have incremented odd twice now when we get to the last Leaf node three occurs twice so this time we actually decrement odd it's going to be equal to one now and that makes sense because when you look at the path we have one number two which occurs an odd number of times long story short what we can do is say that the change in odd is going to be this it's going to be one if the count of that value is odd in other words if it's equal to one otherwise we're going to decrement odd we're going to set the odd change to Nega 1 using that odd change what we're going to do is update odd now you might be wondering why did I create this extra variable why didn't I just put odd over here and then have the plus equal set to this because think about this going back to the tree here on the left once we're down here at the bottom three occurs two times when we pop back up we're going to do the opposite of what we just did if we incremented the odd count by one now we have to decrement it by one cuz we lost that three if we did the opposite if we decremented the count when we went here when we pop back up we have to increment it so basically what I'm saying is that before we end up returning down here to odd we have to make sure that we subtract the odd change before we do that and don't worry like in between these there is going to be recursion that's the whole point of this cuz clearly we're just canceling this out and that would be meaningless if there wasn't anything in between this now we're ready for the interesting part there are two cases at this point we might have actually reached a leaf node cerr might be a leaf node how do we know if that's the case if not c. left and not c. right it doesn't have any children what do we do in that case we're definitely going to end up returning something we're going to return the result what is that result going to be well like we said if odd is less than or equal to one then we return one otherwise we can return zero cuz then we don't have a path so this is what I'm going to do I'm going to use a tary operator here I'm going to say the result is equal to one if the count of odd is less than or equal to one otherwise it's equal to zero and this is what we're going to return but I did this for a reason we're going to put something in between here because like I said we want to make sure we change odd we want to update odd before we return and just like we want to update the count of odd we want to update the count of the number as well when we found C we incremented the count of C by one when we returned from here we want to decrement the count of C by one so let's do that right here okay so that's the leaf node case that's the other base case finally for the recursive case we can say the result is going to be equal to the sum of whatever the result is in the left sub tree plus the right sub tree and it looks like I didn't even need parentheses here cuz this line isn't too long and I also realize it's not in order it's actually DFS so it's even shorter and so from here we'd also want to return the result but don't forget we probably want these two lines down here as well and since we're duplicating these lines maybe we can refactor this a little bit to have an else statement over here and put this result inside of the whoops put this result inside of the if statement well the else block and we want this to occur regardless we want to return the result regardless so let's just take these three lines of code out of here and they will execute down here anyway so we did a little bit of refactoring shortened up the code we are nearly done there's one last thing that I saved for the end when you have an object like count declared outside of a function like this we can access that and we can modify that object when I say modify like we can add values to it remove values but we can't reassign it if I were to do this count is actually equal to this I would get an error actually forget that we can reassign it and we can actually do the same thing with odd like if we wanted to reassign odd to something if we wanted to assign it to a 10 for example this would actually work what won't work is this odd is equal to odd + 10 because this odd is equal to odd + 10 because this odd is equal to odd + 10 because what this tells python is you've declared some variable called odd in the scope of this function it tells python that you're not using odd from outside you're actually declaring a new version of odd and then we're accessing odd at the same time like how can we say odd is equal to odd plus 10 when this isn't even assigned yet it will give an error and let me just run this to prove it see the error we get is cannot access local variable when it is not associated with a value so the way to fix that is just to declare Odd as a nonlocal value so just like up above this will basically tell python that we're actually not declaring a new odd value down here we're actually using the odd from out here that's the entire code let's run it to make sure that it works as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Pseudo-Palindromic Paths in a Binary Tree
minimum-difficulty-of-a-job-schedule
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be **pseudo-palindromic** if at least one permutation of the node values in the path is a palindrome. _Return the number of **pseudo-palindromic** paths going from the root node to leaf nodes._ **Example 1:** **Input:** root = \[2,3,1,3,1,null,1\] **Output:** 2 **Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path \[2,3,3\], the green path \[2,1,1\], and the path \[2,3,1\]. Among these paths only red path and green path are pseudo-palindromic paths since the red path \[2,3,3\] can be rearranged in \[3,2,3\] (palindrome) and the green path \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome). **Example 2:** **Input:** root = \[2,1,1,1,3,null,null,null,null,null,1\] **Output:** 1 **Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path \[2,1,1\], the path \[2,1,3,1\], and the path \[2,1\]. Among these paths only the green path is pseudo-palindromic since \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome). **Example 3:** **Input:** root = \[9\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `1 <= Node.val <= 9`
Use DP. Try to cut the array into d non-empty sub-arrays. Try all possible cuts for the array. Use dp[i][j] where DP states are i the index of the last cut and j the number of remaining cuts. Complexity is O(n * n * d).
Array,Dynamic Programming
Hard
null
101
okay welcome back to algojs in today's question we're going to be looking at the code 101 symmetric tree so given the root of a binary tree check whether it is a mirror of itself so symmetric around its center so in this first example we are comparing the left subtree with the right subtree so around the center and this is going to return true because they are mirror images of each other with an example two these are not mirror images because the right value here should be compared to this value here which is null and the left value on this side is null whereas the right value here is three so those are not equal so we can return false so let's dive into the solution so we will be using recursion for this solution however this is a bit more tricky than just your normal recursion because we're going to have to be comparing this value with this value as well as component these two values so this is going to be a divide and conquer approach with that being said we need some base cases right that are going to allow us to pop out this recursive call so we have three trees down here to walk us through the cases so within this first example let's say we get down to this level where we have null here or here null here so we are comparing these two for example if they're both equal to null then they are mirror images of each other so we can return true so if left and right both null we can return true so in the second example we have a value of null within this right side whereas it's not null here so if left equals null or right equals null we can return false right so if one of the values is null then it's not going to be a mirror image of itself and then in this last tree this last example here we have two and three so these values are not equal so this is also going to return false so if the left.val false so if the left.val false so if the left.val does not equal right.val does not equal right.val does not equal right.val also return false so there's the base cases this is what's going to allow us to hop out of the recursive call stack and determine whether this is a true mirror image of itself and then with the recursion we're going to do a divide and conquer where we're going to look compare these two values and we're also going to recurse comparing these two values so time and space complexity are both going to be equal to o of n because we are traversing all the nodes within this tree exactly once and space complexity because we're using recursion we're going to be populating the recursive call stack with n nodes okay so let's write this out so let's start by creating the recursive function when we call this recurse function we need to pass in root.left and we need to pass in root.left and we need to pass in root.left and root.right root.right root.right we don't need to initially look at the root because it's obviously going to be a mirror image of itself we just need to compare the left subtree and the right subtree so we can start off by doing that so let's hand in left and right to the parameters and let's write out those base cases so if left and right are both null we can return true because those are mirror images of each other if left is null or right is null that's going to return false or if the left vowel does not equal right vowel we can return false and then with the recursive call making that call we need to compare the left value of l so that'll be say this value here this three node we need to compare that with the right subtree and the right value of it so we need to compare it with this three node here we use the and operator because we need to make sure that these values so this four node and this four node here are equal to each other as well so we compare left at right so that's the left subtree but it's right value and right at left so the right subtree but it's left value remember to return this recursive call and then let's give this go okay let's submit it and there you have it
Symmetric Tree
symmetric-tree
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null,3,null,3\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-100 <= Node.val <= 100` **Follow up:** Could you solve it both recursively and iteratively?
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
59
welcome to tim's leco challenge today's problem is spiral matrix two given a positive integer n generate an n times n matrix filled with elements one to n squared in spiral order for given number three we're going to return a three by three matrix with the order one two three four five six seven eight nine in major like spiral order so this problem is really not that different from the first spiral matrix what we're going to do is keep track of the four coordinates of the start column the end column start row and the end row now as long as the start column is less than the end column or the start row is less than the end call end row we're going to do a nested for loop or not nested for loop we're going to do four for loops okay and we can just make sure that we'll fill in the correct order from the start column to the end column and we then go right then goes down going to the start row to the end row then go left going backwards from the end column to the start column and then going up from the end row to the start row now each time we make one fill we have to increment or decrement our starting row or ending row or whatever starting column ending column that way we can make sure that we're not going to be overriding any numbers so when we go like say in the beginning we start fill up this right side when we're finished we're never going to be approaching this row again right this row the starting row is done we should never touch that so we'll increment our starting row in the same way once we're done going down we're never going to be touching this last column right so we'll decrement our end column and we'll just continue that algorithm and because this is a square there shouldn't be any funny edge cases here so it's actually a little bit easier than the first spiral matrix so what we'll do is first create the output it's just going to be zero times n i'm going to say or blank in range of n now you don't have to do this but i just find it easier to do that we'll also have an incrementer keeping track of the number that we're on so we start with zero finally we need our four coordinates right so the start column start row the end column and the end row and what are these are going to be 0 and n all right so while start column is less than the end column or the start row is less than the end row we have to do our four for loops right so this is going to be left we're going to go down we're going to go right and we're going to go up and i'm sorry my side up here we're going to be going right and we're going left here all right so it's just let's keep it simple all we do is say 4 we'll be going these columns so for column and range of the start column to the end column we know we'll be filling up our output first increment our i and we'll say output start row and the column will increment that so equal to i now once we're finished with this like i said that starting row is done right so make sure we increment our starting row so that will never go there ever again now for down we'll say four row in range of start row to end row what are we going to do increment our i'll put let's see this would be the end column but make sure to do a minus 1 here because we made it equal to n and we'll say this would be the oops what's that up here this would be the row right here and this would be equal to i now when we go left we have to go backwards right so this is going to be a little bit different we'll say for range of start i'm sorry let's start n column uh and we gotta have a minus one here and then we'll go all the way to the start column again have a nice one don't go nice one so go backwards and we'll increment our eye we'll say output let's see this would be going left so we're going to be the end row and column now i forgot here up once we're done with the going down we have to decrement our n column by one so that we never approach the n column again same thing here we're going to decrement our end row so we never approach that again and finally going up let's say 4r in range of uh oops i for r in range of n row minus one start row minus one we'll increment our i and we'll say outputs would be the uh start i'm sorry am i doing row and the start column right make that equal to i and increase our start column by one and this way when we wrap around here as long as one of these is true and because this is a square both of them will be we'll be filling up everything that we need to and finally we turn our outfit at the end so let's make sure this works let's see i've got n row minus one uh more typos all right so i missed something up here one two three four five go left i must have that is very odd how did i fill that up oh what it's always something silly more typos here make it equal to i not subtract i all right so that looks like it's working let's go ahead and submit it and there we go so this is a n times well it's o then um i guess technically it's o of n squared because we have two n's but whatever i think that's self-explanatory that's self-explanatory that's self-explanatory now normally with the spiral matrix there's like some if cases for some weird edge cases when it's like a rectangle and stuff but luckily this is a square so we don't have to worry about that it's always going to fill in nicely with this right down left up pattern so that's it all right i hope that helps thanks for watching my channel remember do not trust me i know nothing
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
948
Hi gas welcome and welcome back to my channel so what is our problem today Bag of Tokens so what have you given us in this problem statement here we have been given initial power which is an initial score which is zero and given a bag of tokens OK, in which tokens i is representing the value of your token. Rectangle is on the index. Okay, what we have to do is that our goal is to maximize our school. Okay, so for this we have to play in two ways. See how, if you have If you have power then it can be equal to I. If you have power, it has power in greater then what you can do is to generate a score by spending your power equal to the value of token I. Okay then here is another way to can. If you do not have power then what will you have to do, you will have to spend score van to generate power, okay then you can play with this and what you have to do is, from maximum to maximum score, how much can you generate? Fine has to be given, okay, so let's understand it through an example, then we will solve it. Okay, look, the answer to this problem is given in its statement itself, so if you read the statement carefully, if you understand it well, then now this You can solve the problem easily. Okay, so we come, then let us understand through the example, is the problem exactly ours, after that we will see how we can solve it. Okay, so let's take this example here, it will be better to see what is here. Have given you tokens, what have you given here which has value here, it will be sorted here, no such statement has been given here but it is sorted here, okay so here you have given us a power, what is your power? 200 ok power is 200 now we have 200 now what you have to do is to maximize your score what is your initial score it is zero ok now it is given here that you will spend any token otherwise you will not have to van it If you get it, then you should have that much power to spend, only then you can spend. Okay, so here it is 200, so can you get power with 100, we can get school, we can get because we have power 200. So we can spend right, so what will we do here, it is 400 but what is your power, if it is 100 then it is hundred, then you can plan with any token out of it, right, so in this condition you will get power generation. If you have to do this then you will have to generate power, for this you will have to spend the entire score, how much score will you have to spend, 1 score will have to be spent, okay, for that you should also have a score van, okay, if you have zero score, then you will have to spend date minutes. Can't do it, okay, so in this condition, you can't play further, okay, because you don't have the power, you don't even have the score, then you ca n't play the game further, okay, so now it comes to us that we have to make it okay. If you have to spend on van, then it is okay and you will have the option that this is this power, which power would you like to take, then it is obvious what will be in our mind, we will remain with Giridih approach only. We take the maximum power which we have, right, so this is the problem, we are on 2.2, are on 2.2, are on 2.2, see, how are you on point, we have to spend minimum power to complete the school, so that we can save power, okay, power is ours. was We do n't need to buy power. Okay, even if we need to buy, then what can we do with a single score? We can buy whatever power we want with a single score, so why don't we buy the maximum power? Right? This is what we will do here, we will sort the gestures. Look, in this problem here also you have been given sorted, but it is not necessary that your arrow given is sorted because your If it is not given in the statement then the first thing we will do is sort it out, okay we will short it, why should we do it because we have to generate score, okay if we don't have power then we have to spend it also, score generation too It will be your van and what will be your expenditure also, it will be Varni. Okay, so in this condition, when we go to buy our power, we have to spend only one score, so why don't we take the maximum powerful one. Right, then we will take the maximum power when we get the score. If we have to generate then what will we do if we spend less power right then what will happen with this, we can score as much as possible with the power that is left, so it is simple, we will first sort it, we will keep one here, we will keep this here, okay now What will we do here, we will see how much power we have, now we have 200 power, so you first see, okay, what we have here is from here, we will reduce our score to zen, okay, so what will we do here. Let's see what power we have, what is the power which is less than equal, what will we do, we will make this our plus, okay, we will take this and our score is done, our score is fine, now we will also subtract this power that now our Pass power is left, see one answer, we will keep zero in the answer mix, keep in mind the actual maximum power, okay, so here we will update this also, we will change the answer from zero to right because it is greater than this, so update it here. You will do it, okay, now you have 100 power left, then when you come to this eye, you will know that we have 200, we have only 100, we have less power, now what do we have to do, we have to spend our power and buy it, so we We have to spend 1s course, then we have to spend 1s4, so why not spend 1s square, so we can generate maximum power, so what will we do, because this is the maximum, okay, so we will spend our van, spend It will become zero and we will get power 400 i.e. total apna will become 500. get power 400 i.e. total apna will become 500. get power 400 i.e. total apna will become 500. Okay, what will become of total apna? It has become 500. Now we will come to this. Okay, we will come to apna, then we will check the power. Is it greater or equal to this? Is it 200? So we can generate power, we can do right scoring, it will become van and it will become 200%, become van and it will become 200%, become van and it will become 200%, then what will happen, yours will become 300, then we will come here further, then what is 300 here also it is 300, that is, we have this You can put the power here, okay, you have put it here, what will happen to this code of ours, you will be okay, so what is this, your answer is 2, because you have spent 400, that is, to generate power, so this is the problem. This problem is quite easy, I hope you have understood the simple logic that when we have to spend power, we should do it as little as possible and when we have to generate power, we should do it as much as possible by spending 1, so what will we do sort of? We will do the minimum, what will we get from the left side and what will we get from the maximum, we will get from the right side, so what we will do here is by doing 2.8, we will solve this problem. 2.8, we will solve this problem. 2.8, we will solve this problem. Now we come to our code. Okay, as I told you, SIM is simply code. There is nothing here, what will we do, first of all, sort our tokens because we are not given sorted right, then we will take the score zero, one answer will take zero, okay then I will become zero, your left side will be the left pointer and our Right pointer tokens dot size is -1. our Right pointer tokens dot size is -1. our Right pointer tokens dot size is -1. Now we will keep doing this for how long till our i &lt;= If there is our i &lt;= If there is Han, then we will make it four in the condition and then we will update the answer. Is the score more than your answer? Is there more then what to do with the answer? Update it. Okay, here then what will happen here that your Now you have done it with the stocks. To generate the school, you will have to spend power, so what will you do with that power? People will mine the power by incrementing it. Okay, now it is possible that you may have this power or not. If you don't have any power, then you can check whether the school has Na &gt; 0, only then whether the school has Na &gt; 0, only then whether the school has Na &gt; 0, only then you can buy power because you have to spend one score of yours, it is okay to generate power, if it is zero then what will you do with the power. By doing Zen tax, people will become plus, your score will become 1 - and this will be your score will become 1 - and this will be your score will become 1 - and this will be your degree man, we will do it for you who will comment, then you will do this, if you do not have this also, if you do not have power, then it will not come here for you. If you don't even have a pass score, now you can't generate power here, so what will you have to do, you will have to move away from there. If you go, then this sir zero will come here, the answer is ok, like in this case, see what is there in the first case, your token is 100. And this is 50, that is, you have to see now, if you go to buy power then your score will also be zero. Power is not in F, we can generate score also. What will be your answer in this condition, it will be zero. I hope you understand the explanation. If you liked the video then please like, share and subscribe. Thank you.
Bag of Tokens
sort-an-array
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort
Medium
null
1,027
hello everyone welcome back here is vanamsin and today we are going to tackle daily uh lyrical challenge longest arithmetic subsequence it's a medium difficulty problem and it can be quite tricky to understand but once you do it's incredibly rewarding experience so let's dive into the problem so we are given an array of integer and we need to find the length of the longest arithmetic subsequence in the array and remembers sequence is arithmetic if a difference between every two consecutive number remain constant and sequence that can be derived from the particular array without changing the order so for example we have example 947 2 and 10 and the longest arithmetic sequence is 4 7 10 and the difference between each element is free and we need to return the longest uh sequence so in this case the longest length of the subsequence is 4 7 10 so three so we'll return free so let's implement it in Rust using dynamic programming so first let N be num length and if and less than 2 we return n as i32 and let's table longest element B2 and let's move table dynamic programming be a vector of 1 and 10 000. 1002 and for i 0 to n and for J from 0 to I we calculate the difference so it will be num y i minus num J and Plus 501 as U size and DPI difference will be DP J and previously difference plus 1 and longest will be a maximum of the longest element and the DPI with the difference position and finally we return longest element as i32 so let's run it and see if our code works so hopefully it work um yes or no yeah it's working so here is the example we mentioned before and this calculation is just the difference between num I and num J but because we are using the knowledge of the constraints so the maximum number could be from a range of 0 to 500 including so we at 501 because difference between uh each number cannot be greater than 500 and one two increment uh to the zero position so what we did so we are using 2D dynamic programming approach and the idea here is to create an array a DP where each position in Vector keep track of the maximum length of arithmetic sequence that ends with a particular difference and we start by iterating over the array from the beginning and for each part of numbers so it's uh I and J we calculate their difference and then update the maximum length of the arithmetic subsequence that can end with this particular uh difference and we continue this process for all person number always updating the maximum length in the corresponding DP RI and in the end we return max length uh found during this process so uh let's run it for unsynthesed cases and see if it's working as well so hopefully it will work and yeah so as you can see it's working and we beat 81 in runtime and also 55 in respect to memory so it's quite efficient solution and the beauty of this solution lies how we utilize dynamic programming storing and updating our finding as we Traverse through the array rather than performing exhaustive search and also we use the knowledge of the constraints of the problem so the maximum difference between numbers could be 501 and also the maximum RI cannot be longer than 1000 so remember the key to mastering this problem is practice and the more problem you solve the more pattern you will recognize making it easier to tackle new problems and if you have any question or ideas sure and please have uh this button make it a like and leave a comment down below as well if you have any question and or don't forget to subscribe for more coding challenges and tutorial in Rust and as always keep practicing and improving and happy coding see you next time
Longest Arithmetic Subsequence
sum-of-even-numbers-after-queries
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`). **Example 1:** **Input:** nums = \[3,6,9,12\] **Output:** 4 **Explanation: ** The whole array is an arithmetic sequence with steps of length = 3. **Example 2:** **Input:** nums = \[9,4,7,2,10\] **Output:** 3 **Explanation: ** The longest arithmetic subsequence is \[4,7,10\]. **Example 3:** **Input:** nums = \[20,1,15,3,10,5,8\] **Output:** 4 **Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\]. **Constraints:** * `2 <= nums.length <= 1000` * `0 <= nums[i] <= 500`
null
Array,Simulation
Medium
null
438
Ko Very slow Look at this Going to do a question Point Eyeliner Grams' actress We will have Point Eyeliner Grams' actress We will have Point Eyeliner Grams' actress We will have friends Ribbon AIDS patients And P What do we have to do with this ribbon P K Find these grams Okay Listen carefully S A string Happy string Have to find P's N grams, brother, there are a lot of S's and when you find them, at one point, you have to make a list of them starting from which index and they do stunts in the answer like it is ABC, now its gram is K, CBC. Exam is nothing but permit dictionary attachment is fine so its pan is heated, it is CBC and its chart is inductance, so this zero of our answer is fine and which ones to apply, let's see it remains the same in the juice of Gram BSEB and What is the starting of the scandals? What is this one? Zero 12345 606 If this story is fine then PK is NSS and where is it starting from? Its starting index is to throw us in the list. Example A BJP is behind the village. If it is fine then first. This is the work, okay, so I have seen its side in this 020 play list, then what is the second name given? Okay, its side is Intact One, then the third heavy is its Settings Tattoo 2012. Okay, let's start the code and first of all its length. Let's take out its length, it will come in NS and pick length will go in anti. Picos do one thing and used to write quality, I will tell you why I am writing ' quality, I will tell you why I am writing ' quality, I will tell you why I am writing ' Rob Light', is it okay? Changed the name due to any problem. Rob Light', is it okay? Changed the name due to any problem. Rob Light', is it okay? Changed the name due to any problem. Now see friends, it is okay and your skin is fine. If it becomes too big, then what is the situation and its grams, how will I get a job in it, is it possible in a small one, otherwise what do we have to do, we will return a new MP3 list, okay, there was gas, we had taken it out earlier. Now let's see carefully the logic, this reference, so many, how many will I check this, okay then I will do this, okay then I will check this, okay then will I do this or not, we can use the sliding window technique, okay now it comes to the point. How do we check the current track like now this and ABC how do I do this Ghr In the last video we had made a question on the issue, in this question also we have made a counter, village darkness has a shape, it is similar, two exams. If the key counter says then what is the account of a character? Inside the screen now like I have two strings ABC, we know that gram is there, pick it up and if I see then we will match their accounts with AB. Why baby is coming once. Once asi once and in the same way if there is one then do one work 2 hours define the counter how many lengths Jyoti 26 length is done by subscribing to YouTube 2 months account is taken is it ok for reference r which has changed No, have you ever taken a sliding account which will keep on changing, even though you are here now, you will go, then you will go to ABP, this is how it is done, so one by one it gets changed, brother, the reference one is changing daily, no, there is a counter, so it is okay. I have made a counter for the reference. What have I done? I have put a loop, so I have put a loop. We will go every quarter and keep increasing the reference account and tell us what is happening. Okay, so the counter of this ABC has been made. Time. Okay, now we will do the password of the first window, which I have put the loop, I have put it okay, from where to where, from where to the end, okay from to 30 chief and sliding, no problem, what has happened is that I am showing it by running and see. What is this of mine, this is this and this CR, see what is written, this is written in front of you, reference, Khairkhwah, reference, it is written, account, one, bank account, even better and then sliding, which is three characters of any Subscribe for the accused that he is okay in this, okay, this is a good check, this is the one above, for this, for the sliding window, we have taken it, for the children, so we said, we had taken it out directly, here the counter is okay and If you have taken out ABC then let's check here, brother, if the reference is correct and whatever is there like sliding account etc. then definitely add it in the result. What is the result? This result makes us tears by default. Let's depend on it here, it's okay, why zero, because we are doing it and finding the anagram of the string and then its starting index, which is zero here, okay, today the first sliding window has reduced, now we will do it, its BJP's Okay, so for that, people will have to wait from where to where, so they will put a loop because zero is okay, see here, we will start again from this minus plus that its length - so its length was why is it like this, - so its length was why is it like this, - so its length was why is it like this, Ludhiana, now I will tell you what? Coming why okay if now the slide which is that is my then we have to reduce to first I chief okay now I'm coming okay so - - - - I'm coming okay so - - - - I'm coming okay so - - - - Verb - which on which minus There Verb - which on which minus There Verb - which on which minus There was one character, before that the character was his - did it and - did it and - did it and subscribe and it is written on this position, now like this wwc2 means this and what do I need, I know that I am here at this time, I am okay, so the complete Anagram is this. AB can be made, if you understand, then my third one is inactive and from here, there is an N Okay, if the front says second spring, then okay, if it is equal, I will add it to the result. Okay, let's go to the commissioners. Sliding window will come next. Acid will come. It's okay, then I will have to do it and add its boot. New ones will be needed, then I will check both those legs, okay, then I will do the next chief, I can say this to this one, okay, before this, I will add one more to this one, so it is simple, okay, and in fact, let's run Aryas to return and see, accept. Okay, let's remove the laptop. If you feel like seeing it, I'll show it. Okay, I'll show you the reference to the reference on the step because why outside the first ones because I want me even here that I want here. But this whole hatred - Plus 10-30, first of all, so that - Plus 10-30, first of all, so that - Plus 10-30, first of all, so that I can make it so that you see brother, this is our account, it is getting printed, look carefully, what is this brother, this counter is ours, this is the first window account. It will be done then it is okay to do five like this with the third ODI of the second window and I am checking every account that only one counter is okay with this, do FD account like this till now, see which one has come due to acidity. Okay, what will come next? Then these two are okay, one is okay, so now we submit it here. Before doing this, it has been printed.
Find All Anagrams in a String
find-all-anagrams-in-a-string
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "cbaebabacd ", p = "abc " **Output:** \[0,6\] **Explanation:** The substring with start index = 0 is "cba ", which is an anagram of "abc ". The substring with start index = 6 is "bac ", which is an anagram of "abc ". **Example 2:** **Input:** s = "abab ", p = "ab " **Output:** \[0,1,2\] **Explanation:** The substring with start index = 0 is "ab ", which is an anagram of "ab ". The substring with start index = 1 is "ba ", which is an anagram of "ab ". The substring with start index = 2 is "ab ", which is an anagram of "ab ". **Constraints:** * `1 <= s.length, p.length <= 3 * 104` * `s` and `p` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Medium
242,567
1,021
all right let's talk about the remove outermost parentheses so you're given a valid parenthesis screens it's either empty or you have the something inside the parentheses so this is the example um so here we go so uh you are going to remove the outermost parentheses so you basically return this right so for this example it's super simple you return this and this entire string is going to be equal to this one but how do you actually uh do it uh you can actually uh keep count of the opening parenthesis and closing parenthesis so i have a counter starting from zero so if i see the opening i'm going to increment right so let me create a variable just call uh just call v val all right and now just keep adding so this should be so starting from zero so if i say opening it's going to be one and then if i see opening again two and then if i see closing uh minus one so it's one and then this is opening two this is closing one and this is closing zero and then uh this is opening again so it's going to be one two one zero so if you see a pattern so let me draw uh let me draw an another line so if you see a pattern uh the substring for the value parenthesis is going to be starting from 2 and with end with zero right starting from two and then end with zero and then you don't want to include the zero one so this is the example one but if you don't believe let me just do it again but in this time i'm going to just quickly uh dive into the question so one two one zero one two one and then two and then three and then two one zero right and then this is a pattern so i need this string right so this ring will become this one and then this one right so it's going to be um open opening closing coding right so if you see a pattern it's super simple like if the count is actually equal to two you just keep adding and if your count is actually equal zero you don't want to add not that but if a count is equal to two you also have to check the character is opening and then not equal to zero you have to c is closing so this is supposed to be a uh the math behind right so i'm going to say uh equal to view and i need to create a stream builder new screen builder and i also need a boolean i will tell you why but i say equal to false right away and this is it so i have a traversing entire third string i mean character except for right all right so i would say you see you go to the opening and then comes plus i'll say closing points minus so i will say if c is equal to opening and count is equal to 2 right i just said and i equal to true right i'll see it's equal to closing and thumbs is equal to 0 at equal to 4 and then if at is if it's true right i can actually do like this then i will just say stream builder come on speed up and here you see right there must be something about my people so let's speed up youtube and again so if you don't know the i don't know what i did you have to go back to the beginning of the video then you can know what i meant for this entire stuff and let me run it hopefully i don't mean typo all right here we go and this is a solution so let's talk about time is going to be open space is going to be relevant you can append every single character into a string so this is not optimal solution so you don't need a boolean array you can just using a counter but in somehow that you just have to follow along with the counter and if a comma is valid then just append to the stream builder so here's the optimal solution i'm going to just copy and paste so i have stream builder and i have a prompted counter so it's going to be open all right so if opening uh is greater than zero and your pen so this is increment is after this line right the plus actually uh after this line so which means opening will be uh increment after this line and then this one is opening will decrement after this line if the decrement is actually before opening right if opening is like this then your decrement first but in this case your decrement after and this is still uh doable so let me submit and this time and space is going to be the same all of them for the time other than for the space and this is a solution so if you don't know this idea you can go back to the beginning of i mean the first version i uh the first version i wrote so this is supposed to be the newbie code but it doesn't matter i mean still it's still doable and i will see you next time bye
Remove Outermost Parentheses
distribute-coins-in-binary-tree
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. * For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings. A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings. Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. **Example 1:** **Input:** s = "(()())(()) " **Output:** "()()() " **Explanation:** The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ". After removing outer parentheses of each part, this is "()() " + "() " = "()()() ". **Example 2:** **Input:** s = "(()())(())(()(())) " **Output:** "()()()()(()) " **Explanation:** The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ". After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ". **Example 3:** **Input:** s = "()() " **Output:** " " **Explanation:** The input string is "()() ", with primitive decomposition "() " + "() ". After removing outer parentheses of each part, this is " " + " " = " ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'('` or `')'`. * `s` is a valid parentheses string.
null
Tree,Depth-First Search,Binary Tree
Medium
863,1008
402
Jai hind is tutorial am going to discuss programming question remove kids for the problem statement that has given unknown negative interior name represented as a spring remove kids from the numbers for the new number is this small as possible and a great two important points improve length of number So on this day the order given when will be given equal to two given number 90 examples to understand this problem statement for example number one more remove virus from these numbers with small as possible number to remove the last digit number which is the smallest possible number This example to remove the pimp from these numbers but with a small extent possible number and after removing 432 from this number will get this small as possible number 12192 Third examples for example to remove visit from the number one digit number which is the smallest number 10 Representative From Obscurity Directly From 10 To Remove subscribe The Channel Let's Move To The Number Subscribe To This Channel Remove All The Best A Message Number Were Left With Nothing Services Should Not Be A Problem Statement And Subscribe To That Before Serving This Problem Let's Understand How They Can approach this problem and to understand the approach let CO example scientific example din port number is 12345 and will have to remove visit from this number so let's salute all the combination so let's first remove one is Vansh Vihar to remove visit so let's remove wicket 10 Number Purchase 235 No Valid Key and Nurses Move to the Number One to Three 500 Notes Key More than 120 Remove 310 Number 124 59 Key 12345 Subscribe Number One to Three 500 Key 12345 to 10 Number One to Three 400g The Number Which is the Smallest 151 234 The Sofa With Latest Features 123 409 In This Unlikely Number All It's An Order To Avoid Button To Remove In Subscribe So Let's Take Another Example And See What Will Happen In The Temple To Remove Visit From The Number Possible Number So Let's Move With This Descendants of number 90 number 1091 and remove 20 wickets December 10 2010 Kids two numbers and remote two so wickets are zero let's remove 10 number that two states and foreign number one they remove 1000 words from left side subscribe button that DPS number one Vihar To Remove Decrease Numbers To Keep So To Make The Smallest Possible Number In These Conditions How To Remove After Updates Number Penalty One More Examples For The Wicket Declare It Was Doing This Select Direct Examples For Example Switch To Remove With May Possible Number Of All The number subscribe and welcome to the number is model number solve this problem on Thursday solve this problem due date for the dividend subscribe to let's see how we can find a small s possible number after removing k digits from this number using stack in data structure Vowel Hair Fall Condition Swift K Is 0f E Don't Have To Remove Any Graduate From This Number Return On Time 10 And Number FD Length Of K On The Length Of The Number From District Information Length Of The Number Is Equal To Remove All Dirt From The Number 10 Already Examples For Here Declared Abscendent Number Subscribe Button More Which Holds Several Types Of Phone Number Spring And Take One Day At A Time And Exit So Let's Subscribe Now To Subscribe Not A Small Arvind Subscribe And Also Will Have To Remove The Number Remove Vidra From The Earth I 10 Number 10000 Left With Two Vegetable Newly Married To Remove The Number One Number Two Which Is The Chief Subscribe Number To The Number Valve That Subscribe Now To Receive New Updates Reviews Found Them Next 9 Minutes Ago A Novel Alfia 10 Code Share And For Watching This String 16 Dec Strength And Take One Day At A Time When It Is Not Entertained Is Video Of Or Vighn Daily Dividend That Dps A Digit Is Great Arandi Current Weather In That Case Property Value From Distant And Decrement And End Of Leaf Imposed in your value 100 then after doing just here is the extra check quality of mid to input number is one to three 500 in this case will never go into the scenario digit numbers in ascending order to remove the last digit Subscribe now to the Subscribe And Simple Way Also Pending Amina String Bill Singh Builder So Lets Se Date Comes First Day Or 1271 102 Stocks Last In First Data Structure Improved Element Which Cons First Is The Last Element To Be Popped Out Its Objective In To Remove The Actress Subscribe Visit 12191 Adhesion 10 Have Removed From This Thank You 500 Years Before And After That Simply Return 10 Strange And Will Get This Small As Possible Number Listen Let's Talk About Cyber ​​Space Complexities And Time Cyber ​​Space Complexities And Time Cyber ​​Space Complexities And Time Complexities As A Space Complexities Also Women Should Get Set For These Video Tutorials For More Sach Programming Videos You can subscribe our YouTube Channel and subscribe thanks for watching this Video plz don't forget to like this video
Remove K Digits
remove-k-digits
Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`. **Example 1:** **Input:** num = "1432219 ", k = 3 **Output:** "1219 " **Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. **Example 2:** **Input:** num = "10200 ", k = 1 **Output:** "200 " **Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. **Example 3:** **Input:** num = "10 ", k = 2 **Output:** "0 " **Explanation:** Remove all the digits from the number and it is left with nothing which is 0. **Constraints:** * `1 <= k <= num.length <= 105` * `num` consists of only digits. * `num` does not have any leading zeros except for the zero itself.
null
String,Stack,Greedy,Monotonic Stack
Medium
321,738,1792,2305