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 |
---|---|---|---|---|---|---|---|---|
7 |
hey yo what's up my little coders let me show you today how to solve the lethal question number seven reverse integer and as you already could guess we just basically need to return the reversed integer if we get let's say 123 we need to return 321 similar pattern applies for the negative numbers and if we have some trailing zeros we just don't care about them and just return the rest but in the reverse way if it's only one digit value we just return the same one digit value this is what we need to do guys and also there's one rule if reversing x causes the value to go outside this sign 32-bit integer sign 32-bit integer sign 32-bit integer range then return zero okay this is a nice rule but for now let's not care about it and let's just figure out the way you know how to reverse the integer without thinking of the integer ranges for now and how people would usually do it probably you might think okay if i get an integer what if i convert this integer to the string after that reverse string then again convert string to the integer and just return it and it will work however it will not be very efficient there is a better way to do it and you can do it just by doing some division i will show you in a second what i mean so we just declared two variables let's one will be to store the result and one to store the last current digit and because we are going to do some division inside this nice while loop while x is not equal to zero then let's try to get the last digit and how you can get the last digit you can basically do oops x mod 10 if let's say the input value was 123 and you do 123 mod 10 basically you'll get three which is the last digit and if you get the last digit then we can update our results right away we just do a result multiply by 10 towards the last digit and you know to somewhere escape this while loop we also need to basically do x divided by 10 if you start with 123 you calculate the last digit it's equal to three then we do a result multiplied by ten positive last digit which is like zero by ten plus three which is equal to three so right now our result is equal to three x is equal to 123 but we do like 123 divided by 10 x right after that will become will be equal to 12 then we go on the next iteration of the value again once digit from 12 it reaches 2 then we update the result so result will be equal to 32 right now and then basically again division so we divide 12 by 10 we have one and basically we're doing this thing again and then we return 321 this is how you solve it just return the result and if i run the code now then yeah you pass the test case the first one however if i submit it will say to us that we passed almost all the cases however not 400 so we didn't pass the five test cases and this is because of you know this rule that like when uh reversing the x value if you go outside this sign 32 bit integer range we need to return zero okay let's just do this modifications so what if you just don't use the integer for the result what if you use long and after we do you know uh this thing is here what if we just check if there is out vent outside this 32-bit there is out vent outside this 32-bit there is out vent outside this 32-bit integer range and it's just simply you know result if result is greater than the integer dot max value or if you're dealing with the negative numbers if result is a less than integer dot mean value in this case we just returned zero and elsa because right now the result is of type long but we need to return the integer we just convert it we just can convert it to the integer when we return it and that's it guys so if i run the code it passes now if i submit i get 100 guys simply as that so it's a quite simple problem i will not wife however you know you need to know the best way to solve this problem because actually a lot of companies in the past ask this question and you know this is quite popular question so you really need to know how to solve it and guys please also make sure that you subscribe to my channel then challenge your friends to see if they can solve this question or not and guys i will see you 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
|
1,704 |
Hello everyone welcome, are you my channel or not? Now let's see how likes are defining this. Google Facebook Microsoft Amazon has asked these questions. Generally such questions are asked in screening, phone interviews have been done, such questions have been asked in such situations. The questions are asked are a bit simple, so let's see the input and output and understand what the question is, then you would have been given a simple string which would be of key and size. Okay, similar. What is meant is that in this half, the number of vowels is number. Off if both are equal number for right half If both are equal then they are alike See will send it True Not like Will send falls till here Okay will start from here Okay I will go from where to where I will just go till half It will work ok, how long will it last, this much will last, what will we name as count left, we will check the count of left, if it is not so, where you input a character and tell whether it is a vowel or not, what do we do with this equal? Tu is equal, you have to write capital letter too, it is possible to write A, I, O, U, Similarly, here U is fine, then write a simple function, there it has its own character. Send, send to C, look like this, send and if there are vowels then return true from there, if there are no vowels then return first. So what is another way that you are not man lo man to write this function, okay then you don't do anything. Do it, you create a set, right, add it to the set, and what both this function and this set is doing is just telling us whether a character is a vowel or not, otherwise you can do that as well. Isn't it the checkup of vowels, no matter how many teams you take, let's code it. Okay, so the question is very simple. You must have understood it. You come to the direct solution. Okay, first of all, it's okay It will It will It will be N/2, okay with Mitts. Right will start, this is what I said, now the account will go to the left till zero This was the talk of ours, okay, write a function for this vowel, then submit the count of left and see what happens, ok, sorry Aayi Ho Kas Solve this question Why will you call Okay, so let's make an ordered set in the set Is it of characters Okay, of characters and insert it in this set I O U Capital A Capital I Capital O Capital Okay Similar st.find all example videos thank you
|
Determine if String Halves Are Alike
|
special-positions-in-a-binary-matrix
|
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half.
Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters.
Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "book "
**Output:** true
**Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike.
**Example 2:**
**Input:** s = "textbook "
**Output:** false
**Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike.
Notice that the vowel o is counted twice.
**Constraints:**
* `2 <= s.length <= 1000`
* `s.length` is even.
* `s` consists of **uppercase and lowercase** letters.
|
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
|
Array,Matrix
|
Easy
| null |
337 |
hello everyone welcome to this video so in this video we will see the question that is 337 house robert three so this is the continuation for the two videos that i made before this that were for house robber one and two so before watching this video i will recommend you to solve those question first that is house rubber one and two and if you are not able to solve them so you can watch my videos i will also provide the link in the description and in the i button also so this will be a bit tougher than those problems so let's see so it is a medium level question you can see and one of the most likes question also so it has been asking various interviews also because it is of form tree so let's see the thief has found himself a new place for his rivalry again there is only one entrance to this area called the route besides the route each house has one and only one parent house because you know it as it is written to root so it will form a tree you can see this example also so in a tree each child has only one parent so you can see each child has one parent you can see from here then you can see after a two the smart thief realized that all the houses in this place forms a binary tree so binary tree is a tree where each parent or a node has only two children or zero or one it may it will not have more than two children so it will have one zero one or two shelters you can see then it will automatically contact the police if two directly linked houses were broken into the same right so it is actually the concept is similar to the house over one and two but the conditions are or constraints are different you can see now houses are connected in a tree format is it forms a binary so that means if we root a one house so we can recruit the adjacent houses so that will be the child of this so we will have to do the other houses so it will automatically contact the police otherwise so you can see determine the maximum amount of money that the thief can drop tonight without alerting the police so this example is given and this example is given so i will explain you new example first of all let's see so in this example you can see the input that we are given so it is actually a pre-ordered reversal so this actually a pre-ordered reversal so this actually a pre-ordered reversal so this will be the root you can see this will be the root and two and three will be the left and right child of this root and this null means the left side of this two the left side of two is null you can see it is not there and here you can see left side is not there and this is a three so this is right side you can see and this these childs are for this three these are for left and right so left is null and right is one you can see like this is our trees form so this is a pre-order vessel for this tree so let's pre-order vessel for this tree so let's pre-order vessel for this tree so let's see what our example is about so as it is told that all the houses are connected in a tree format so you can see this is the parent this is a root node and these are its children so they are actually connected you can see there is a direct edge between them so if you see carefully you can see this edge three is connected to two to through this edge and three is connected to three through this edge so that means we cannot move these houses together you can see three and three so it will automatically trigger the alarm and the police will be uh coming so that's why we cannot loot like this so we will have to actually loot the houses which are not directly connected so that means the which are not the children of the parent so you can see this three so it will be uh if we do we loop this three so we can loot this three and one because it is not directly connected to this edges you can see they are not directly connected there is there are two houses in between so that's why we can root this so what we have to do is we have to maximize a profit or we can we have to uh drop the maximum houses and collect the maximum money so let's see how we can do that for this example we given this so this is this actually denotes the amount this three is actually the amount so let's see so if we load this three okay we if you look this three so we will have three profit then we cannot do to this two and three because they are connected so the trigger will automatically trigger so that's why we cannot root this so we will come to these houses so these we can root it will be three plus one it is not written that you cannot lose these two houses or a particular level uh together we cannot loot these particular houses these three plus one this will be uh rooted together so it will become you can see three plus 36 or one plus one it will be seven but if you see if we don't loop this root node then we can do uh loop this two and three so if we loot this two and three then our profit will be two plus three which will be five but now if you see if we didn't lose this route and we rooted this houses in between the intermediate houses this two and three then we can include this three and one also because they are also directly connected so then our profit will be five so what will be our maximum profit we have to return the maximum profit so maximum will be seven you can say seven is greater than five so our output will be seven you can see here also the output is seven this is how we have to solve this example this is a basic uh like problem statement that we are given so this was the explanation for the same so let's see the algorithm how we can do it as it is a tree so you can think of the recursive solution also so because we have to find the houses you know the maximum profit that we can root so we will actually call the our function main function recursively to find the profit for the all routes so let's see how our like algorithm will be so actually as i told you if we root this house so we cannot root these houses so what we have to do is we will make two variables that is a1 and a2 and even variable will have the profit for this these nodes that if we are on this node for this node we have called the function so it its left child and right side profit will be added so it will be even will be having the value as nine you can see it will be having the value as nine but it cannot be uh like we add these values because we cannot root them we can root this only four and five then whatever a2 variable will be having is root so it will be having the profit that we can get if we rob this root house so it will be three plus we cannot root these houses so we will we have we will check first if this root that we are looting has left child so if it has left child then as i told you we cannot move the intermediate roots so we will have to loot the left child's children you can see left child cheltenham will be three and one and three so if we look at this three so we cannot root this four but we will check if this three has left child so four is present that means we can root four children so that will be one and three so these will be also rooted so profit will be you can see one plus it will be three plus uh three plus one you can see three plus one so now again we can if you loop this okay this will be the one case that we are adding so the third or the root node has also the right children so our right learns children's profit will be also added so that will be 1 so 3 plus 6 it will be ok uh this 7 plus 1 so it will be 8 if you see careful it will be 8 so that means our even variable that we are having will store the profit even variables will store the profit when we loot the intermediate houses we don't uh loot this route we load the children of the route then what we will do is we will recursively call so if we have this you can see we have in even we can simply add this so what we will do is this is not actually left child and writer we will recursively call the function or the same function for root left root dot left and root dot right roots left children and right china and they will recursively call for the same function again with their children so that is how it will work so now this function will call for this three so it will but if this value will have even with the values as you can see for this will it will be having four plus five because our four and five don't have any children uh that can be looted you can see grandchildren because we cannot root the children you can in this way also if we lose three if we root the parent so we cannot root its children we can look its grandchildren these are its grandchildren not the children so that is how it's working so for this you can see value will be four plus five it will be nine if we would uh we leave the root node and we loop the children of that particular house or note so what we will do is we will have this even variable okay it will have value as nine if we don't root this root and these values if you skip this so it will be simply this four plus five it will be saving the value as that and now for the case when we loot this root node if we loop this root node so it will be three okay then we cannot root this four and five so it will be skipped then we can load this also one plus three plus one it will be six so uh seven so seven pl uh sorry it will be here one plus three so yeah it will be eight so you can see three plus three six and one plus seven plus eight you can see this will be eight actually so the maximum profit so actually when we will call this for function uh call for this function so our a2 will have the values when we root this root and again for recursively for this also actually it does not have any further note so it will be returning simply the value that is eight because it's this left hand and i shall be null so it will return its value only root value that will be one simply uh it will add that so what it will have is now even our even variable his will have value as this four plus five it will be nine and our a2 variable that will we when we root uh when we drop this root node it will be having value as three plus one plus three plus one that will be eight so we have to return the maximum profit as a given in the question so whatever maximum profit so it will be a you can see maximum of 1 and a 2. so it will be this 9. so this will be our maximum profit that you can see the answer also here so yeah you can see this is the maximum profit that we are getting is from four plus five if we loot this root node then we cannot loot this so that means we will simply skip this and loot this four plus five so we will get the maximum profit so this will be our main function actually so let me show you the code in c plus and python also so then i will explain you how we can do that so actually i will explain you the code that is memoization code because this recursive code will give you tle so we will have to use memorization code let's see okay what's happening okay yeah so this is a code so actually you can see for you uh let me explain you here only why we are using the recursive why we are not using simply the recursion if you use the recursion you can see uh if for if we have like if we have this tree let me make this new slide if we have this tree particularly so it has more nodes okay it has more nodes from here also it has nodes here also so here also like similarly here and here you can see if for example this node has value something like green value and it is also oh sorry not this is also green value so our recursive function what it will do is it will score for every function and it will check the value or find the value for every root and whatever it will similarly it will lead to the tle so what we can do is to reduce the time complexity we will have compromise of a space complexity and what we will do is we will simply maintain a dp because we will use a dynamic programming and we will save the solution for this node this particular green it will save the solution for example just like imagine it is or giving value five so when we leach we call for this function when we reach to this function you can see this will be similar we will check if it is present in our dp array we can simply return that value because for this green value we have already calculated so it will be five so we can simply return that file if it is not there we can search for it or we can find the solution and then before returning the solution we will add that value to the dp okay dp array or in this case we will be using a map because we have to store the root and the maximum profit for that particular rule so in this week for memorization we will use a dp uh this map hash map we can say or a dictionary in python because we have to save the root will be three and then the value for the particular root will be you can see it for this profit will be actually our profit will be eight so that is how we will be saving so let's see so you can see we have initialized in c plus we have initialized this unordered map it will be having key as tree node as i told you this would be a node so we will be saving uh this node as the key and the int or end is the maximum profit that will be get from the particular node if we include it so that will be the value so it i have initialized it as dp you can see then this is our main function so actually i've written the comments because i committed this one hacker over also so you can read from these commands also so i will explain the code for server so you can see the base condition that will be having is if root is null because if this is a recursive candidate this recursive function so you will have to make a this base condition so don't forget to do this if root is not we will simply return 0 because when we for this function we call for we are on this function so it will call for s even so it's even will be actually null you can see it will be it does not have any left side or right side so it will simply when it will come here so it will call for zero so uh i need this left cell so it is not so when it root is null we will simply return zero because it cannot contribute anything there is no house uh below this one so we will simply done zero from here and zero from here so even will have value zero and a two will be having value as root so root value will be one and you can see for this am i telling through to eight will be having is one plus the its grandchildren but it does not have any grandchildren if you will check if it is having any uh left child and nature then only we will check for the grandchildren otherwise we don't do anything so it will return one so out of null uh zero and one but we'll maximum one so we'll return the one to the parent node so this is how it will work in the recursion and as i told you we have to do some uh memorization because for to reduce the time proxy otherwise it will give a tle so we will be using a dp you can see this our map that we created so what we will do we will check first of all before like calling for the functions we will check if it is already present in our map dpmap then we can simply turn the value for that dp root will be the key okay root will be the key and its value will be written dp of root will turn the value for that particular key and value will be our the maximum profit that we will get that is eight for this three that is the example so let's see so as i told you we will call this end e it a will be the case when we are rooting we are not robbing the root node and we are dropping its children the particular uh it is the case when if we are at this node okay we will not rob it we will draw its children so this is what this case is about you can see rob root dot left and root uh dot right so this is how it will work and this the a2 will be the case for when we drop the root node so when we drop the root node we can uh drop the root node plus the grand children of the root one if it has any grandchildren so this will be the condition we will check if root is a root left has any values that means there is a left node for this root if we are at this value so we cannot uh drop this if we cannot drop this so what we'll do we will check for the grandchildren so you can see it does not have any this left chair does not have a grandchildren you can see so that means it will not call for the function so this is how we have to uh check for the conditions you can see so then for this particular node we will again recursively call you can see root left and left because for this value uh let me erase this all stuff so you can see when we are on this particular three if we drop this three then we cannot drop this four and five so what we'll do we'll check if three has left node it has left one so it will check yeah it has left one then it will recursively call for the root dot left you can see group dot left and root dot left dot right for this one and three the same function will be calling and it will be returning the maximum profit that we can get from this node so this is how this recursive call will work and we again similarly as a root has a left check and right held so we will check for the right head similarly we will check if right a child is present that is five is a present so then it will check if uh it will call for the function that is uh root dot right dot left and root dot right dot uh right you can see root. right so actually in c plus this is arrow syntax so you can see then we will we have to add this because i told you on the particular level we can drop all the houses that are on particular level because there is no edge between them it is a tree so its these nodes or children are not connected to each other they are connected to their parents only so we if we loot the parent we cannot root their children so this is how we are doing this and at the end when we get a function so you can see as i told you we will having the value for this function we in the even we were having value as 9 and in the a2 we were having value as 8 so we will have to return the maximum out of which maximum will be returned so before returning we are also saving it into the dp of root as i told you for this screen before returning this value we will simply save it to the our db map so if we save it so it will have value s5 so when we come to here you can see if we come here so it is green so it will check yes dp of green if for example you can expose that is present so it will return that value simply the value that we say five so we can save our time lot of time will be saved because instead of calling these this function for the same subtrees it will simply return the value for the particular subtree which has been calculated before only so let's submit this so i hope you understood how we are solving this or how we can solve this problem and i will provide this code in description also so let's see the python code also so it will similar actually you can see this uh function that we are given and we are uh like initializing rdp you can uh dictionary in python then for this function i've written this function inside this function because in python the function inside function is allowed you can see so let's see so similarly if the root is null you can see in python syntax is like if not root so we can return 0 otherwise we will check if root and dp dot keys because in python to assess the keys of this dictionary we have to write dot keys so it will check if it is there then we can simply turn the value for that particular key and similarly profit one will be for the root dot left and root right that is skipping the parent note and looting the left and right children and similarly for this if we look this route then we will root the left grandchildren and write grandchildren similarly we will check for the maximum you can see before returning the answer we will simply save it with our tp or the dictionary before uh for memorization so you can see return dp or root and simply you can see returning the this function that we have made inside the main function that we are having so it will turn the value of this tpu let's submit this also so i hope you like this video and like guys do like this video and subscribe this channel for more such videos and uh do let me know which videos should i make or like which videos you do you want to me to make so thank you for watching guys i hope you like this video and also do don't forget to like i will tell you about the time complexity also so time complexity for this will be actually o of n because at the max what we are doing is we are traversing whole three so at max we will traverse this the size of this array you can see will be and okay and so our time complexity will be also n before we will make similar calls you can see this will be calling one two and three four so it will be having like calling for the similar values so it will be having the time complexity of one for traversing the tree and the space complexity will be also n because we are using the stack also and also the dictionary that we are using for the memorization so that's why the timing of next will be o of n and time release it will end and space will be also n so thank you for watching guys i hope you like this video do like this channel and subscribe
|
House Robber III
|
house-robber-iii
|
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`.
Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**.
Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_.
**Example 1:**
**Input:** root = \[3,2,3,null,3,null,1\]
**Output:** 7
**Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
**Example 2:**
**Input:** root = \[3,4,5,1,3,null,1\]
**Output:** 9
**Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104`
| null |
Dynamic Programming,Tree,Depth-First Search,Binary Tree
|
Medium
|
198,213
|
1,060 |
all right so two discussing as 1016 missing element in solid array we are given a sorted array of unique numbers so these uniqueness of numbers is telling us there is no tie we wouldn't have some kind of you put like a four seven nine ten that's not the case that's the we don't need to worry about those kind of cases so with this problem and the question is asking us to return the case missing number starting from the left and most of the array so the example here if the input is 4 7 9 10 and we're looking for the first missing number that's 5 but we should come directly after 4 if we're looking at the third missing number we have 5 & 6 third missing number we have 5 & 6 third missing number we have 5 & 6 missing in between 4 & 7 and the next missing in between 4 & 7 and the next missing in between 4 & 7 and the next missing number is the 8 that's missing between 7 & 9 between 7 & 9 between 7 & 9 the third example we have 1 2 4 we're looking for the cert missing number we have a 3 missing between 2 & 4 and after have a 3 missing between 2 & 4 and after have a 3 missing between 2 & 4 and after that there's no more numbers in the array so we're just incrementing this last number by 2 to figure out that's 6 so just based on the description that just reasoning through how why these 3 examples will have their outputs we can see what can have a linear scan linear path just one pass through the array and keep track of how many numbers we are missing in between numbers and to compare that missing number of missing values with K and there will be some kind of logical conditions you can figure out based on that you can figure out the when to stop this iteration and the return the case missing number but we're definitely looking at something that's better than doing one pass so mm I guess if you look at the think about what's been given to us it's a sorted array and we are looking for searching for some values based on based off that array that's pretty much a very clear hint it's a ship we should be utilizing some kind of a binary search method to reduce the search time from linear to log of n so we have to think of how can we have a direction of search so one of the way to think about is to it's important to realize that we can actually calculating how many numbers we have missing between any two numbers right so let's say let's walk through some examples say that we have four seven nine ten if we're looking at this particular location here how many numbers we have missing from the left to this current location that would be 7 minus 4 and that's a 3 and minus 1 right so this is the because this is the first allocation here for the example if we're looking at the example under 9 listen this 9 the second element tonight here I can see that the number of missing values we have there is how much this is too right this is five minus two which is three so there is this relationship that number missing between zero and I ice number is I minus zero minus the location knife so index I so that's something that we can derive based on looking at based on the property of it's a sorted array and it's non unique based of this we can actually give us a direction of the searching right we can compare this number of missing numbers compare that with K and telling us to how we can search for a particular location faster this is not gonna give us directly the location the case missing number but it will be able to tell us which location we start to have number of missing values more than K so if you call this method if we define a function that's a missing number and taking just a one input argument to the index of a particular number and to just map this function to all the elements within the nonce it will give us something like a 0 1 kind of if it can compare the output of the function with K it will give us something like a 0 1 because initially for the left a cup of elements in numbers locations in the array we not gonna have any we the missing numbers are going to be smaller than K and apparently sometime this would change and the number of missing values will gradually you know you will once we have that turning point the missing value is greater than K then everything else after every location afterwards is going to be the same so that gives us a sorted array again it's a zero one search space we can use that to find the first location where we have more than K missing numbers then the previous location to that it's going to have a number of missing number that's less than K and based off that location that number and that the number of missing value the difference between the missing values at that location and K we can figure out how we can directly calculate the actually the actual case makes a number so it might sounds a little bit complicated when I was explaining but when you see the code it's pretty simple and straightforward so to put up with the question by a binary search let me just lay out the you know the bare bone of binary search typical binary search code while the two pointers are not in not equal yet meaning that we still haven't pinged on the location will get the middle elements to be just to be the middle one and we'll have a function here take the index that compare that with K if it's a smaller than K meaning that we haven't find the first location where we have more than case missing number we were increment to the lower number otherwise we will decrement the high number so after this binary search the area the air here is going to be the first location where we have the more than case missing number notice that I use lens of Nam skier rather than the very last two locations because we can go out of bond so that's why we have this that's actually one plus the very last two location and array and when we find our location what we can do is take the previous element previous number and just add the difference between the number of missing values and the K missing funny that so that's the rear that's the number we can calculate you know we have to have some more missing values that's acylated as the difference between K and this is the result of this function call and since this is the first number after this after we have missing midst of so many numbers we just add that difference directly to this number we can get the case missing number so that's the binary search code and this is the formula to figure out that what's the case missing number the left is just to code this function not missing here we just take one of the index and the relationship is this I hear just return that so was this the code looks right to me so yeah we have we changed the low to low a location to mid plus 1 because this fails this is strictly less than so yeah it looks good to me so let's submit it and it's working so the time complexity for this binary search from solution is log N and was n being the number of elements no it was yeah with M be the number of elements in the input array and the space complexity is its constant we don't have any data structures that consuming more than constant space in its associate so yeah that's the question for today
|
Missing Element in Sorted Array
|
longest-repeating-substring
|
Given an integer array `nums` which is sorted in **ascending order** and all of its elements are **unique** and given also an integer `k`, return the `kth` missing number starting from the leftmost number of the array.
**Example 1:**
**Input:** nums = \[4,7,9,10\], k = 1
**Output:** 5
**Explanation:** The first missing number is 5.
**Example 2:**
**Input:** nums = \[4,7,9,10\], k = 3
**Output:** 8
**Explanation:** The missing numbers are \[5,6,8,...\], hence the third missing number is 8.
**Example 3:**
**Input:** nums = \[1,2,4\], k = 3
**Output:** 6
**Explanation:** The missing numbers are \[3,5,6,7,...\], hence the third missing number is 6.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 107`
* `nums` is sorted in **ascending order,** and all the elements are **unique**.
* `1 <= k <= 108`
**Follow up:** Can you find a logarithmic time complexity (i.e., `O(log(n))`) solution?
|
Generate all substrings in O(N^2) time with hashing. Choose those hashing of strings with the largest length.
|
String,Binary Search,Dynamic Programming,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
1,926 |
hello everyone welcome back here is benampson and today we diving into intriguing lead code uh challenge uh it's problem number one nine two six uh nearest exits from entrance enemies so this problem is a classic example of how to use breakfast search BFS to find the shortest path in a two-dimensional the shortest path in a two-dimensional the shortest path in a two-dimensional grid so let's get started all right let me pull up the problem statement for you essentially we are given a maze with empty cells and walls and the entrance to the maze is also given and our goal is to find the nearest exit from the entrance and exit is defined as an empty cell at the border of a maze so uh here is example so let's get start by setting up a main variables so we will be coding this one in Python but yeah I will also provide implementation in go rust C plus Java and more so firstly we need to determine the dimension of the maze so let's write it down so m n will be Len maze 0. and direction will be 0 1 0 minus 1 0. so next we Define our possible Direction Up Down uh yeah left and right and this are direction we can move within the Maze and we are going to use a cube for BFS and we will initialize the queue with the entrance coordinates and start our BFS from there so initialize the queue with the entrance and distance as zero so Q DQ entrance zero and entrance one and mark the entrance as visited by converting it to a wall so mace entrance zero entrance one will be plus so while Q and now row column distance will be Q pop left and check if we have reached an exit that is not their entrance so here is a cool trick So to avoid visiting the same cell multiple times we will mark it as visited right away so in our case we will convert the entrance to uh wall so plus and now its main part so and color logic we will Loop through our queue and apply BFS so uh let's code it as well so check for each so if row equal 0 row M minus 1 or column 0 or column n minus 1. and distance greater than zero so return distance check all Neighbors neighbors and cue them if they are empty it's also so for the error DC in our directions we simply put r c as row plus Dr Co plus DC so new coordinates and if less than equal error and M 0 C n mace error app Point maze RC will be visited and Q append RC distance plus one and if we get here there is no path to exit so return minus one otherwise so as you can see we pop the front cell from the cube and check if it's exit and if it is and it's not the entrance we return the distance otherwise we move on to its neighbor and enqueue them for the future exploration so now let's run it to see if it's working for this test case so hopefully yeah it's work perfect so now we can also submit it for and since cases to double check uh it's working so I'm running it and yeah as you can see all good and we beat 80 four percent with respect to random and also really good 98 with respect to memory so it's probably because we use a BFS iterative approach rather than recursive so it's doesn't create a memory stack uh okay so and now you see how to solve it with BFS and there you have it uh we have successfully solved a lead code challenge 1926 and if you found this video helpful make sure to hit the like button and subscribe for more awesome content tutorials challenges machine learning Tech and much more and thank you for watching keep practicing stay motivated and happy coding
|
Nearest Exit from Entrance in Maze
|
products-price-for-each-store
|
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell.
| null |
Database
|
Easy
|
1948
|
200 |
hey guys it's off by one here and today we're going to be solving number of islands in this problem we're given a 2d grid which is represented in ones and zeros where one is land and zero is water and the one is returned the number of islands so what is an Island an island is defined as being surrounded by water and formed by connecting adjacent lands horizontally or vertically so what that means is that diagonal lands like these two here do not count as one piece of land so for example this would be one piece of land and this would be another piece of land and a third piece of land would be this so now that we understand what an island is let's get into the solution so here we drawn the example from the problem and I think a fair place to start would be by saying that we want to search the entire grid here so let me just write that down okay but what do we want to do while we're searching this entire grid well we know we want to search for an island but how do we do that well we know we can only have an island if we encounter a one so we can say while we're searching a grid if we encounter a one then that means we encountered an island but let's say we started this one here there's a lot of other ones that are connected to it and this whole thing here is what makes an island not just this one so we have to consider all the rest of these ones and how to account for them so what we can do is actually a depth first search so for example let's say we started this here we can visit the node next to it and the node below it and do a DFS from there as well so we can do DFS for these two nodes and then if we go below this node we see there's a zero so that wouldn't be part of the island but if we check the node next to it we see that this is part of the island so this whole Square here would be an island and what we can do is mark them as visited so we don't visit them again and just as a side note whenever I say node I'm referencing the grid itself and not some actual node object like we've done in previous problems so let me just summarize what I just said so if we encounter a one like here we want to do a DFS we want to do the first search so let me just write that down okay and then once we do the DFS then we want to go all the way recursively until we find all the zeros that are on the edges of it and once we find all zeros then we know we found a whole island so our goal with this algorithm is to be able to count how many times we run this DFS algorithm and this is basically the entire algorithm so let's say we're doing DFS for this node here and that none other node is visited yet what you want to do is visit the one above it the one to the right below and to the left and if we encounter a one then we want to do the same thing we go for every single coordinate around it and we haven't visited it and it's a one then we do the same thing over and over again if we have a zero then we stop our DFS algorithm and the way we're going to Mark knows it visited is just by zeroing out whatever is the value so obviously we only have more than zeros so if you make it a zero then we're never going to visit it again because it's a zero and we don't run DFS unless we encounter a one so this would also be a zero and then once you visit these nodes these are also going to be zero and as you can see we have two rows of zeros now and we encountered one Island so far and if you keep doing this algorithm we'll run into this one here and then eventually that'll be zeroed out and we can increase our count to two and now if we run the algorithm again for this row here then we see we're done because it's all zeros and for the last row we see we have this one here we'll run DFS for it and see that we only have one other one and once we do that we Mark these two as zero as well and now our count is three and that is how many islands we have so to summarize One Last Time what we're going to do is search the whole grid row by row and then if we encounter a one then we want to run our DFS algorithm in our DFS algorithm we're going to search every node that is adjacent to it so the node above it to the left down and to the right of it and then in this DFS call we're going to zero out the node we're currently visiting because that means that we already visited it and we don't need to go over it again once we find all the zeros on the edges then that means we found a full island and we can just increase our count of islands our time complexity for this algorithm is going to be o of n times M because we're only going through the grid once and the grid is of size n times M so that's why we have this complexity our space is going to be constant because we're not using any data structures we're only changing the grid itself in place so we don't need any additional storage so now let's get into the code to start I'm going to define the number of rows as the length of the grid and the number of columns as the length of Grid at index 0 and that's going to tell us how many rows and columns we have just to make the code a little easier to read and then we're going to iterate through the whole grid so we're going to do for Row in range of rows we want to iterate through every column and from here we want to check if the current coordinate is equal to one so we're going to do if Grid at this row and column is equal to 1 as a string by the way because that's how the problem is formatted then we want to run our DFS but we haven't defined our DFS yet so let's do that first so we're going to do Define DFS and we want to pass in just the row and column and from here we can just do our algorithm and we can break this up into three steps first we want to do our checks to make sure we're in a valid position and then we want to do our marking as visited and at the end we just want to run DFS as needed so let's start our checks are going to be to first check if we're in bounds so we're going to do if row is less than zero or column is less than zero then that means we're out of bounds and vice versa we don't want to go too high so we're also going to do if rho is greater than rows minus one or if column is greater than columns minus one then that also means we're out of bounds and if we're out of bounds we just do a returned because we don't need to do any DFS for that next we want to check if our current coordinate is zero because if it is then that means we don't want to run DFS for that so we check if Grid at our current row and column is equal to zero then we also do a return so now we're done with our checks and now we can just Mark our noses visited and how do we do that well like I said in the example all we're going to do is set our current coordinate equal to zero just like that and then next we can just run DFS as needed and for this problem we're going to need to go to every single adjacent node so we're going to go above below to the left and to the right and the way you do that is by going to DFS at row column but slightly modified so to go above we do row plus one to go below we do row minus one to go to the left you go row or column minus one and then to go to the right you do column plus one so that's it as far as our DFS algorithm goes so now we can go back down here and finish our DFS call so we're just going to pass in our row and column but like I said every time we call these DFS we want to keep a count so we want to increase our count by one and we also have to initialize our count to zero here in case we don't find any ones and then at the end we can just return our count and then that should work so as you can see this code is pretty efficient and now I'll go through the code manually so for this code we're just going to start down here immediately because this top part is kind of irrelevant so we're going to have our counter initialized to zero which we already have here and then we're going to iterate through every single point in the grid so let's start if our current point is equal to 1 which it is here in the top left then we want to run this DFS and increase our count by one so let's just increase our count first and now let's run the DFS so we're going to run DFS on this and as you can see it passes our checks and then we want to mark it as visited so now this node is going to be a0 and we do DFS for the left above to the right and Below but we already know that to the left and above just give us out of bounds so we're going to skip that part but we are going to go below and to the right so now we're going to run DFS on these two and let's just do it for this one on the right so we're going to check if we're in bounds and obviously we are and it's not a zero so we're good there so we're going to mark it as visited so that's going to be a zero and now we do DFS for every single adjacent node so we're going to go below to the right above and to the left but as you can see the ones to the left is zero now and above is out of bounds so let's go to this node so we see that it's a one so our checks pass here and now we want to mark it as visited so we're going to convert this to a zero and now we want to do DFS for every node adjacent to it so we're going to go to the left down to the right and above but as you can see these are all zeros so we would just get a return value here and that's it for this DFS call now let's go over here so for this DFS call now we passes our checks and we just have the market to visit it now so this turned into a zero and we do DFS for every node adjacent to it and we're going to go down and we see that it's a zero and we're going to go to the right and we see that it's a zero and I didn't do it for this one but also we go down into the right and these are both zero and up here as well is the zero so that's why our DFS call would end now and now we can increase our count which we already did so now let's go to the next coordinate would be this here and we can see it is the zero now so we keep going and we see more zeros and more zeros until we get to this one here when we get to this one we want to do our DFS call so we're going to go into DFS and we see that it's inbounds and it's now zero so we want to mark it as visited so now this turns into a zero and we do DFS or above below to the left and to the right so if we go above we see a zero we go to the left we see a zero we go to the right we see a zero and if you go below we also see a zero so that's it for our Island here so now we can just increase our count to two and then from here we keep iterating through the grid and we see that we see more zeros and then finally we see this one over here so we're going to run our DFS call again and we see that our checks pass so now we're going to Mark our notes visited so we set that equal to zero and we do DFS for every single adjacent node so we're going to check above us to the left and to the right and as you can see the one above is zero the one to the left is zero down would be out of bounds and then to the right we see a one so since we have a one we can go past these checks and we can mark this current node as visited so we make it into a zero and now we do DFS for every single adjacent node so we go above and we see it to zero if we go to the left we see a zero but low is out of bounds and to the right is out of bounds so now we're done with that DFS call and we can just increase our count to three so now that we're done with this coordinate here we want to check our last coordinate at here at the bottom right and we see that it's a zero because we zeroed it out for this DFS call and we can just return R3 at the end because we're done with our iterations and we know this is correct because we can see here that we have one Island here and one Island here if this video helped me in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
|
Number of Islands
|
number-of-islands
|
Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_.
An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
**Example 1:**
**Input:** grid = \[
\[ "1 ", "1 ", "1 ", "1 ", "0 "\],
\[ "1 ", "1 ", "0 ", "1 ", "0 "\],
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "0 ", "0 ", "0 ", "0 ", "0 "\]
\]
**Output:** 1
**Example 2:**
**Input:** grid = \[
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "1 ", "1 ", "0 ", "0 ", "0 "\],
\[ "0 ", "0 ", "1 ", "0 ", "0 "\],
\[ "0 ", "0 ", "0 ", "1 ", "1 "\]
\]
**Output:** 3
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 300`
* `grid[i][j]` is `'0'` or `'1'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
130,286,305,323,694,695,2035,2103
|
496 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem next greater element one and i'm actually going to be doing both solutions for this problem so over here you can see that there is a follow-up for this so there's going to follow-up for this so there's going to follow-up for this so there's going to be kind of an n squared solution and then the more efficient one which is pretty much big o of n where n is going to be the size of the larger input array but before we do that let's actually understand what the problem is asking for so first of all the next greater element of some element in an array is defined as being the first grader element to the right of that element in the same array so it's pretty intuitive just like the name says we're given two arrays nums one and nums 2 where nums 1 is actually a subset of the second array and what the problem is asking for is a little bit tricky to understand so if we were just given this array nums 2 and we had to find the next greater element of every single value in this array that's simple to understand but what the problem is asking for is actually a little bit more complicated than that so basically since nums 1 is a subset of nums too we actually only want to find the next greater element of the values in this array that are also included in the first array so we don't want to find the next greater element of every one of these we only want to find the ones that are four one and two so four uh one and two you can see that they don't even show up in the same order so that's gonna be a little bit annoying and so the output that we return is of course going to be the same size as nums1 and the order of the values is going to be the same so if we want to know the next greater element of 4 while we look at our second array 4 is over here what's the next greater element of it two is not greater than four and there's no other elements here so four doesn't have a next greater element so the default value that we do in this case is going to be negative one so we just put a negative one in the output the next value is one what's the next greater element of one well looking at the next value three is greater than one so that is the next greater element of one four is also greater than one but three is closer to one on the right side so we use three in the output for two a two doesn't have any elements to the right of it so it doesn't have a next greater element we can just put negative one there so the brute force of this problem is not super crazy but it's a little challenging for an easy problem so one way to approach this problem is to kind of just find the next greater element for every single one of these because we know if we do that we'll pretty much have what we're looking for and then we can create the output but at the same time we could also skip the values we don't need to in this case three is not in the first array so we don't need to find the next error uh element of three so what i'm actually gonna do is convert the first array into a hash map where we're going to be mapping every single value in that array to the index that it shows up in the same array the reason we're going to be doing that is because let's say we are iterating through each value in n2 so we have one so first we would want to know does one even show up in the first array yes it does okay so we need to find the next greater element of one let's say we find it over here three okay we found the next greater element of 1. so now we want to add that 3 to the output in our result well where are we going to add it in the result are we going to add it here or here well it depends where did one show up in the input array it showed up over here at index one so that's going to be the same index we added in the output so that's why we need the hashmap so that we know the index of every single value and the hashmap will also be very efficient for us to just look at this value and say does it even show up in the first array yes or no we can do that in of one time okay so we found that's you know the next square element and then we're just gonna basically repeat that for the rest of the array so three does it show up in n1 it does not so we can skip it four does it show up in n1 yes it does so we can't skip it and how are we going to find the next square element well pretty much we're going to iterate through the entire array until we find a value that's greater than four the first value that we find that's greater than four and then add it to the output but in this case we would iterate through it and see that it doesn't exist so in that case we could just add a negative one uh in the same corresponding position but we could also just initialize our result array with all negative ones so that we don't even you know have to do that which is probably how i'm gonna handle it in the code and then lastly for two there's no other elements that come after two so we'll just add a negative 1 here so not super crazy but the overall time complexity if you kind of caught it is going to be n squared because for every single value in n2 we're potentially going to have to iterate through the entire input array to find the next greater element and we're going to have to do that for every single value in the array in the worst case so the time complexity is going to be something like n squared but technically let's say the size of this array is m and the size of this array is n technically i think the time complexity is actually going to be n times m because we're not finding the next square element for every value in this array we're only doing that for every value in the first array the memory complexity is going to be big o of m because we're going to have a hash map for the first array and we're also kind of building the output as well so now let me just show you the code really quickly and then we're going to get to the more complex solution but also the more efficient solution okay so let me just walk you through the code really quickly so like i said this is going to be our hash map the way i'm initializing it is kind of you know some python fancy stuff but you don't have to do it this way you can do it a traditional way if you want but pretty much this is just taking every single value in nums one mapping it to the index that it shows up in then we're having our result which is an array of the same length of nums one initially it's just going to be all negative ones because we know that's kind of the default value and then we're basically doing our nested for loops that i talked about we're going through every value in nums ii the bigger array but we're checking does that value even show up in nums one if it does not then we're just going to skip this value and then go to the next iteration of the loop but if it does show up then we're going to do our nested loop then we're going to go through every single value starting at i plus 1 because we only want to look at the values that come after the original value and then we're checking which is the first value that's greater than the value that we started at if we find the next greater value we're going to get first of all get the index of the original value and then we're going to set the result equal to the next greater value and then break out of this loop because we're already done but if this never executes and we never find the next greater element then the result will stay the same at that index it'll stay as a negative 1 the default value so that works out for us and then once this nested for loop is done we'll just return the result so that's the basic brute force solution now let's look at the more complex more efficient one so now let's look at the n plus m time solution and i'm just going to tell you straight off the bat that this is going to take a stack to solve but it's not super intuitive to know that it's going to need a stack especially if you never solved this type of problem before if you've never heard of the monotonic stack technique but i'll try to explain the intuition of y i changed the example a little bit though because the original example doesn't really lead to the intuition of a stack so that's why i changed the order of the values at least to this because this will be a bit more interesting so let's say we started at two we know two shows up in the first array so we want to find the next greater element of two we look at the next value one it's not greater than two so it's not the next greater element then we look at the next value three it is greater than two so we found the next greater element of two and we can add it to the output but hold on a second if three is the next greater element of two shouldn't it also be the next greater element of 1 well that's only the case if one even shows up in the first array which it does but then that is the case and that would be the case for any number of values you know suppose before the three and after the one we had a zero over here then we'd say well one is not greater than two and zero is also not greater than two but when we finally reach the three is greater than all of them by definition because all the values that came after 2 before 3 they were definitely not greater than 2. that means they must be less than 2 because all the values in the input array are unique so that means when we find the answer for 2 we're also finding the answer for all the values in between that's where the stack is going to come in because we want to remember all of these values in this case of course there's only two of them but like i said there could be a lot more so how the solution is gonna go is we're gonna start at two it's in num1 so what we're gonna do is add it to the stack you're gonna notice that this is going to be a one pass solution we're not going to have nested for loops next we're going to look at the value one first of all is it greater than any of the previous values that we need to find the next greater element for well we're going to check that by taking a look at our stack what's the top value on our stack it's 2. so 1 is not greater than that so we didn't find the next square element of 2. but 1 does show up in n1 so we are going to add it to the stack because this is another value we need to find the next greater element for okay and then we look at three and we're going to compare it to the top value of our stack notice how the stack is always going to be in decreasing order it has to be because by definition if we find a value like we just did now we found a 3 and that's greater than the values here so now what we're going to do is pop all of these values what we're going to do is see 3 is greater than 1 we found the next greater element of 1. so what we're going to do is find the index of one we're going to use the hash map that we talked about in the previous solution to do that so we're going to say the next greater element of 1 is going to be 3 and we're also going to pop this from the stack and we're not going to stop there we're not just going gonna check one value from the stack this three could be greater than multiple values on the stack so what we're gonna do again is compare it to two is three greater than two yes it is so we're gonna pop the two we know that two shows up at this index so we're going to add a 3 at that index we found the next greater element of 2. and now the stack is empty so we can't keep you know popping values anymore so we're done with that phase of the algorithm now is it time for us to add 3 to the stack no because three does not show up in the first array so we don't need to find the next greater element of three so we're not going to add it to the stack so now we're done looking at three we're gonna go to the next value four we're gonna add four to the stack then we're gonna go to the next value after four well there aren't any values after four so the next square element for four is just gonna be negative one so we're just gonna add a negative one at that spot so notice how we did that and we did it with one pass through the input array now we are adding elements to the stack but we're also going to only be popping each element from the stack once so the overall time complexity yes in this case is going to be m plus n the space complexity is also going to be a big o of m one because of our hash map which is gonna be the size of the first array also the stack is only going to be the size of the first array because we're only adding elements from the first array to the stack so that's pretty much the whole solution i really hope it makes sense now let's code it up okay so now let's code up the more efficient solution you can see i have the original solution down here and we're going to be starting this problem the same way that we did we're going to have that exact same hash map and initialize our result the exact same way but in this case we're also going to have a stack which initially is going to be empty just like the drawing explanation and then we're going to start iterating through every element in the second array just like we did in the first solution but where things are going to get a little bit different is we're going to look at the current value which is just nums 2 at index i and we want to know if this is the next greater element for any previous values that could be on our stack now initially our stack is empty but later in the algorithm it could be non-empty so in algorithm it could be non-empty so in algorithm it could be non-empty so in that case if it was non-empty we would that case if it was non-empty we would that case if it was non-empty we would want to know well is the stack not empty and is current greater than the top of our stack the top of the stack you can get with negative one in python or you could take the length minus 1. if this is the case of course we want to pop from our stack and we're going to pop the value we know that current is the next greater element of this value so we want to find the index of this value thankfully we have our hash map to do that so let's get the index of this value and then we can set that at that index we can set the result which is going to be cur because cur is the next greater value so pretty straightforward after that is done the question is does cur show up in the first array if cur is in nums 1 index hash map that means it shows up in the first array that means we should add this to our stack now if it doesn't show up then of course we just won't add it to the stack because we don't need to find the next greater element of this stack or not of the stack of that value but once that's done that pretty much is the entire algorithm we can go ahead and return the result and let's run the code to make sure that it works and as you can see on the left yes it does and it's very 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
|
Next Greater Element I
|
next-greater-element-i
|
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
| null |
Array,Hash Table,Stack,Monotonic Stack
|
Easy
|
503,556,739,2227
|
349 |
hi everyone this is MK and here is another Lico da challenge um today we have a quote from the shaing Redemption I love this line where Andy says hope is a good thing maybe the best of things and no good thing ever dies okay today's problem is an easy problem uh I will solve it with two different approaches first a Brute Force approach and then a two-pointer approach and then a two-pointer approach and then a two-pointer approach let's go and read the problem is about the intersection of two arrays so we are given two integer arrays num one and num two and we should return an array of their intersection the only catch is that the result should be the elements in the result should be unique and it doesn't matter if we can return it in any order it doesn't need to be in sorted order in increasing order or decreasing order so this is the first example we have 1 2 1 so as you can see input is not sorted and n two is two and the intersection is number two only once not twice here we have 495 we have 94 984 and again N9 and four only one nine is the intersection and we return it so how do we solve this problem with a Brute Force approach is trying all possible ways to find the answer to a question like what I mean let's go and take a look at the example so imagine you want to find the intersection between a A and B okay so you have a0 A1 and A2 and so on and you have b0 B1 B2 and so on so the Brute Force approach is you take a Zer and you check it with every element in B you ask are you a Zer are you a z and so on until the last element this checking of a z with every other element in B is a Brute Force approach okay and we do the same for A1 and we do the same for A2 we are not being a smart we are not using any data structures we are not using any specific algorithms just a very simple linear search algorithm linear search is this are you a z and so on checking a z with all of the members of B is a linear search okay and if at some point the answer is yes if a z is equal to some bi we add that to C which is a set C okay a z remember the answer should have unique elements and set lets us have unique elements the most important application of the set data structure is that it keeps the elements that are unique like only unique elements are in set there's no repetition in set that's what I want to say okay all right let's go and write the code for the first solution and then we are going to discuss the second solution so for the first solution we need a set C and then I'm going to call input A and B and then we are going to take every element of a so for in x of a we are going to take every element of B so for INT y of B if x is equal to Y that means we have uh an element that is in both of the arrays so C do insert X and we do break because we just found out that c exists in b okay and that's it this is this gives us the intersection and we add all of them to C we just need to add this set in a vector because the answer is a vector so we Define a vector into result and we iterate over all of the members of c and we add them to result okay and we run two green flags okay and submit okay this was the first solution let's go and see the second solution involves sorting and the running time is going to be better because the The Brute Force approach was very slow I'm going to discuss I'm going to write about the running time and the space complexity in the comments or the show notes yeah so the second solution we sort a and then we sort B okay and now we know that a is sorted so let's say we have 4 9 17 22 something like that okay and then we have here 2 4 7 10 something like that what we do we need two pointers one that is pointing to the A and one that is pointing to B We compare the two is a0 equal to B 0 no it is not right so two so a z in this case is greater than b 0 a0 is 4 B 0 is 2 so what happens here if this is I and this is J in this case we should increment J why remember we are looking for intersection so we are looking in this case a has a four B has a two so we are asking b hey b do you have a four and B says no and the smaller number is guaranteed that is not going to be visited again so what I mean is that a is not going to visit two anymore because any other number that comes after four is greater than two sorry greater than four okay so because of that we increment J so and if so this was one of the cases so if a z AI let's say is greater than bi in this case we increment I because this is the smallest number the smaller number and this number is not going to be matched anymore so this is one case this is another case and the last one is if AI is equal to bi in this case we should increment both I and J sorry BJ sorry so in this case we should increment both of them because we found the match i++ the match i++ the match i++ j++ but before we increment them we j++ but before we increment them we j++ but before we increment them we should add the answer to a set C so here we say c. add Ai and then i++ i++ i++ j++ j++ j++ so remember we can remember the condition that the output should be unique the elements of the output should be unique so we can solve that problem with the same set data structure or each time we are adding a number to C we can compare AI with the last number that was added to C so in this case for example let's say you have let's say here let's say you have three 4 7 and we have 3 59 okay and here is C so we compare three with three that is a match so we add them to C so that is going to three is going to be added to C which is the result then we increment I we increment J now we compare the two again three is equal to T to three we want to add to tree to C but we should check the last number that was added to C and since three is equal to three we don't add it and why can we do that because the numbers are in sorted order and if numbers are equal they are going to be added consecutively to C all right that's why we can just check the last number that was added to C in this case we just ignore we es skip basically and we go to the next one I just wanted to show you that We compare the last added number to the current match that's it let's go and write the code here I need to reset this so a b so this time I just need a vector vctor in C and we just return C at the end we need two indexes so in I is zero and J is zero so while I is less than a size while I is valid and while J is valid okay if AI is equal to BJ what do we check if C is empty or C that back which is the last number that was added to C is not equal to AI okay we add AI to c. pushback Ai and here we increment I we increment J regardless of the fact that we were able to add it to C or not we increment I and J else if AI is less than BJ in this case we just increment I and else we just increment J okay and here we just return see yeah let's just run the code wrong answer so n oh we should sort them sorry we should sort them sort a that begin B do begin sorry a do a begin a. end yeah and B that begin B that end okay and that's it we submit okay that's it I hope you enjoyed this problem uh please do subscribe and follow And subscribe that's the same yeah or not I don't know if you enjoy and introduce me to your friends thank you have a good day
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
990 |
hello everyone today I will solve the question satisfability of equality equation in this question they will give us a vector of strings and inside that factor of questioning there will be the equations that equation will be only of the double equal to or not equal so what we need to do we need to check if it is possible to assign integers to variable these variables so that it satisfies all the given equations like in this example if we assign is a is equal to 10 so B will be 10 right so now we need to check whether it this equation is satisfied or not B is equal node to 10. it is not satisfied because 10 is not equal to 10 is false so we will return false so we need to solve this question so we can solve this question by using Union find in Union find what we do we break all these uh all this character into small groups like a is equal to B is equal to C so all these are equal right so we will make it a group of a and there will be a leader like here G is the leader of this group like this uh here e is equal to f is equal to e so it is different group and the leader is e so like this we can assign a value uh to these groups and in the last first we will check for the equal to and in the last we will run a for Loop 4 not equal to and we will check if the leader of like e leader of e will be P only if there is no leader uh that value itself will be the leader or you can see that value itself be the root so here root of e is e right and root of B is G so it is not equal so we can return true because it is not equal if both will be equal it means that both these values belong to the same group so it is not equal it can't be equal so we in that situation we will return false so first we will run for double equal to that is equal to for Loop and after that we will learn for the not equal to and we will check if any values uh comes like both belong to the same group in that situation we will simply return cause so here we can do first we will call a function that will be find parent or you can say find roof that function will return us either root if there is no root that character itself it will return that character itself like here first in our first uh and first input is equal to B here root of B is nothing right we have not assigned uh any route to the B so in that situation it will return the B only and same goes for a so the root of B will be okay here is equal to C so the parent or you can say root of C will be a only and for this b equal to D in this question in this input the parent of D is D only but parent of B is a so the parent of D will be a like this it will not be the parent of D will not be the B because the parent of B is a and for G equal to B the parent of B is a and the parent of G is G only so the parent of a will be G now for e equal to F here parent of f is equal to e like this now we are running for this not equal to and we are getting true now see the code part so here it is our function here if we are assigning the parent we have 26 character and an English alphabet or you can say 26 Alpha so we are making it a size of 26. and we are running a for Loop for assigning the root of each character to that character only the character itself is the root of that character here if it is equal to if the string 1 is equal in that situation we will find the root of both the value like X or Y and if it is not equal we will assign the parent y will be parents of Y will be the Axon like here parent of B is G so first we will find the parent of B and parent of G and the value of this uh parent of this B will be G so if after uh after checking all this equal to we will check for the not equal to and if we find that any characters belong to the same group X and Y both belong to the same group in that situation we will return false now then this code it successfully got submitted thank you
|
Satisfiability of Equality Equations
|
verifying-an-alien-dictionary
|
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter.
| null |
Array,Hash Table,String
|
Easy
| null |
1,652 |
hey everybody this is larry this is me going over q1 of the bi-weekly me going over q1 of the bi-weekly me going over q1 of the bi-weekly contest 39 defuse the bomb uh i hope this doesn't get me a wizard from the fbi but this is actually just hopefully you're watching it just to see me explain this problem because i think this is pretty straightforward um the tricky thing to note is that you can't do it in place i mean you could maybe but it's just gonna be a lot of um you know being careful and then also just writing it and i actually to be honest wrote this really badly during the contest because i was trying to rush it and sometimes i do for q1s especially since usually i try to solve it under a minute but this is literally you and there are ways to do it with partial sums to optimize this problem but for q1 you don't have to given these constraints it makes it a little bit less interesting so i just perforced it and actually you could have done something like if i now to kind of rewrite it um i would kind of clean this up a little bit so that we don't have to do something like this um so then now i can just do something like that and then this code would be really quick um or queena to read maybe not quick but so i would write something like this uh you can kind of you know check for it but um so something like that um but basically it's just really followed the instructions right so uh um the key thing is that doing it in place you're getting the trouble so make sure you just allocate extra space it's 100 elements you could afford it i believe in you uh that's all i have for this problem it's um linear time uh actually n times k times so not really linear but uh but it'll be good enough so yeah let me know what you think and you can watch me stop this live during the contest including all that typing now hmm i could done this but better uh that's just that all right hey uh thanks for watching uh hit the like button hit the subscribe button join me on discord let me know if you have any more questions about this problem or another problem i will see y'all next problem bye
|
Defuse the Bomb
|
minimum-suffix-flips
|
You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **next** `k` numbers.
* If `k < 0`, replace the `ith` number with the sum of the **previous** `k` numbers.
* If `k == 0`, replace the `ith` number with `0`.
As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`.
Given the **circular** array `code` and an integer key `k`, return _the decrypted code to defuse the bomb_!
**Example 1:**
**Input:** code = \[5,7,1,4\], k = 3
**Output:** \[12,10,16,13\]
**Explanation:** Each number is replaced by the sum of the next 3 numbers. The decrypted code is \[7+1+4, 1+4+5, 4+5+7, 5+7+1\]. Notice that the numbers wrap around.
**Example 2:**
**Input:** code = \[1,2,3,4\], k = 0
**Output:** \[0,0,0,0\]
**Explanation:** When k is zero, the numbers are replaced by 0.
**Example 3:**
**Input:** code = \[2,4,9,3\], k = -2
**Output:** \[12,5,6,13\]
**Explanation:** The decrypted code is \[3+9, 2+3, 4+2, 9+4\]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers.
**Constraints:**
* `n == code.length`
* `1 <= n <= 100`
* `1 <= code[i] <= 100`
* `-(n - 1) <= k <= n - 1`
|
Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left.
|
String,Greedy
|
Medium
| null |
899 |
in this video we will solve orderly Q so let's see the problem statement it says that you are given as string s and an integer k and we can choose one of the first K letters so if you see this example b a c a k is 3 that means among the these three letters the first K letters you can pick one of these and move it to the end so this is a string and let us say this length is K we pick one of these elements and we are allowed to move it to the appended to the end of the string so this letter from here will be gone and it will be appended here so a new string will be formed you are allowed to do it uh infinite number of times so as many times as you want and after that you have to return the string which is lexo lexicographically smallest so if you see this example we have baac a then the best string the smallest string that we can get is AAA BC in fact if you sort these you see that this is all the letters are sorted and here K is 3 but can we always sort the string the letters of the string let's see so if we have let us say ah BCA and the value of K is 1. so this is the smallest possible value of K so in this case you have to pick one letter among the first K that is first one letter that is the first letter itself so you can move this B to the end so you will get c a b if you again move this C to the end you get a b c again it's sorted but let's take another combination let's say we have C ah b a now if we move C to the end we get B A and C comes to the end BAC again if we move B to the end we get a c b now if I move a back we will get C B A which will be back to the original string so after uh n rotations we will get back the original string so in the case of 1 K is 1 we got ACB and it seems we cannot get a smaller ah string so we will return ACB but when K is more than 1 it seems we can always sort the letters of the string so we can return sort s and then return the sorted value now let's see why we can always sort the string if K is more than one so first let us understand let's take this example b a c a so here K was 3. so ah you should realize that a larger k is powerful than smaller k why because let us say k is 2. then you are allowed to pick one letter out of first two letters in the string and move it back if K is 3 you can pick any letter from first three so these first two are also included so you can do whatever so you can always do what you can do with k equal to 2 with k equal to 3 but you cannot do that with k equal to 2 what you can do with k equal to 3. so let's take the weakest case so if I prove for k equal to 2 that we can always sort the letters of the string then that should be possible with k equal to 3 k equal to 4 all the larger values of K as well because in the k equal to 3 case also you can always ignore third letter and pick one of these in fact with larger K you can do that even quicker but k equal to 2 is the weakest or the worst possible case in which can be sort the string or not so let's take a general string let's see here so let us say ah some part of the string is already sorted let's call this part as one this substring as 1 so we have a string s which is composed of let us break it into two components so let us say in component 2 it's not sorted let's take some realistic characters let's say we have Z followed by w followed by p so it's decreasing in this order the same we can do with just two letters also but let's take a bigger case and then let's say there is another segment there are more characters after this and that segment two so ah first I will using k equal to 2 I will sort this part so similarly for any other place where it's violated the Sorting is not done we can repeatedly do that so let's say this part is okay to the left of zwp to the right of it we have not explored yet if they are not OK we will repeat the same process but we have sorted the string till this part one so what we can always do with k equal to 2 is ah we can follow what we did with k equal to 1 so keep moving one character at a time to the end so ultimately we will reach a place where this entire substring one is moved to the end so we have here z w p so we were picking one character at a time so this was c one C two c three so first c one went to the end then C 2 after that then C3 after that so their ordering remains same so now zwp comes in the beginning and then we have this after immediately P we have 2 so we have this 2 and then this one now what we can do we can pick the smaller among these two z w so a smaller is W so we will do z p 2 1 and W is pushed back again ah pick the smaller and move it here so w p and then Z and later put Z here so it was zwp and then we can move a 2 here shift one by one so we have one WP Z2 so here p z is sorted only this part is unsorted so again move it like this w p z 2 1. now the smallest among these two is p so move P to the end and then 2 1 and P comes here again ah now pick the smallest that is W now in fact it's done so just move w and z to the end so it will be Z 2 1 p and w comes here and then move Z to the end so it's 2 1 p w z Now move all the elements of 2 to the end so that we get back to original state 1 p w z and 2. so we got from this one let me clear it so we got from 1 z w p 2 1 p w z and we said that we have already sorted till all the characters in this first substring that is one and now this PW Z is also sorted so we can extend this solution now next we will find again the place where it's violated and again we will repeat the same thing so you see that even with the smallest uh even with k equal to 2 we can do this so we can do with larger values of K as well since ah k equal to 2 is a subset of k equal to 3 in the larger case also we can pick just two characters and we have already seen what happens with k equal to 1 we have to try all possibilities like we had here CBA so we keep track of minimum string initialize to original string and if by moving it to the end we found a smaller string keep that so CBA initially it's CBA then we move C to then we get BAC is smaller than CBA so now we update s mean to BAC then we move B to the end we get ACB now ACB is a smaller than BAC so we update s Min to ACB and now if we move a again it will be C B A we will get back to original so try for all the n characters and see which is minimum and return that and for K larger than 1 simply sort the string and return that value so let's write the code for this so if K is more than one then sort s and return s we will have one s ministering initialized to s and so what we are doing s equal to s dot service tier so take the substring of s from first character till the last character since the first character will be going to the from second character till the last character and first character will be going to the end so it's in zero based indexing so subtr starting from second character and plus S 0 the first character is appended to the end and then we compare with s min and after this s dot length or times moving the first character to the end we will get back the original string so no need to do it again and then we can return s min and the two cases are accepted let's submit and the solution is accepted
|
Orderly Queue
|
binary-gap
|
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters.
| null |
Math,Bit Manipulation
|
Easy
| null |
392 |
Hello gaze myself Amrita welcome back to our channel techno sage so this is our recurring court series in which I will be solving lead code problems if you also wish you join you can subscribe our channel and will solve lead code problems now let's move ahead with today's problem. Today C Will Be Solving Problem No. 392 Date Is This Subsequence So Let's Get Started Let's First Understand D Problem Given To Strings S And T Written True If S Is A Subsequence Of Tree And False Adverwise So In D Example You Can See Have Bin Given Tu strings s and t c need tu check wether sequence of t if yes c need tu retain true and vice c need tu return false nine let's understand what is this sequence and how are you going to solve this problem so let's say tu strings van Give it a b c and string t is a h b g c if c have tu check weather s is a substring of t what c are going tu do c have tu check weather letter check if b exists in d string s it exists move on tu D Next Character Date Is Character C Nine Check Weather C Is There In String T Yes It Is There Give C Can Say Date Strings S Is Un Sub Sequence Of Spring T Right And Also It Should Follow D Se Order For Example A Is Un Pairing First And Let C Similar Order It Should Be There A And Let B And Let C Let's String S Is B A So Nine You Will Check Weather B Is Appearing Yes B Is Appearing In D String T Let You Want To D Next Character A Where A Is D Parent Yes A Is Un Parent But It Is Not Following D Order Date Mains A Should Upper Only After Character B Which Is Not In D Case Every So Date Mains C Can Say It Is Not That All Sequence Of String Right Nine Let's Understand c are going to subsequence of string t so these are d tu strings which c need to check so far date what c are going to room c are going to take tu points van is pointer i for string s and inside van is pointer j for string T So Firstly Let's Write I Zero K Zero Right So C Are Going To Check If The Character Matches A Is Equal To A True Write If It Is True Then C Are Going To Move To D Next Character For Both D Strings Date Mains Increment I And Also increment g so date mains nine pointer i is index one end pointer j also come index 1 again c are going to check if is equal to no right if it is false give what c are going to do c are going to increment only Index J C Have You Hold D Index I C Just Have Tu Increment Given Correct So Nine K Is Date K Is Aate Character B Again C Are Going Tu Check Weather By Equal Tu B Yes Date Is True So C Have Tu Increment Both I And k right so nine i moves her and j moves tu di next one c = b no when it is false c tu di next one c = b no when it is false c tu di next one c = b no when it is false c tu have increment only k so k moves tu d next character se is equal tu di no when it is false c have tu just increment k so k move every right so nine c is equal tu c date is true so c have already reached till d last character of d string s if c have reached till d last character then date mains c have checked for all d characters of string s D date mains c time return true c need you solve this problem nine let's try d solution for it so this is our class this sequence nine let's try d method so date would be public static booleans it is going to return true or false this sequence end The inputs would be string s and string t and then what would be first condition if length of string s is zero then let c can directly return true if we are going to take tu pointers i and k both will be starting at the zero end Let i < t length c need to check if the characters matches right so if dot caret i have to move to d next character and they can check d from string s=abc and t = a h b g b c nine let's write s=abc and t = a h b g b c nine let's write s=abc and t = a h b g b c nine let's write un print statement
|
Is Subsequence
|
is-subsequence
|
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_.
A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not).
**Example 1:**
**Input:** s = "abc", t = "ahbgdc"
**Output:** true
**Example 2:**
**Input:** s = "axc", t = "ahbgdc"
**Output:** false
**Constraints:**
* `0 <= s.length <= 100`
* `0 <= t.length <= 104`
* `s` and `t` consist only of lowercase English letters.
**Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
| null |
Two Pointers,String,Dynamic Programming
|
Easy
|
808,1051
|
1,431 |
uh we're going to go over 1431 kids with greatest number of candies so the question says given the array of candies and the integer extra candies where candies at index i represent the number of candies that the eighth kid has okay for each kid check if there is a way to distribute extra candies so we're going to distribute extra candies among the kids such that he or she can have the greatest number of candies among them so great is meaning max uh notice that multiple kids can have the greatest number of candies okay so we can have multiple max values if you look at example one we get an array candies and it's only numbers and each number represents um a kid the number of candies and what we're trying to do is uh distribute extra candies and see if that kid has max number of candies or not okay so if we look at our first example there's an array with two three five one and three candies and we have three extra candies so what we want to do now is figure out if this kid can't have the maximum number of candies or not okay and this will be our result all right so if we give three candies to this kid um the first kid will have five candies if we give it to this kid we'll have six and eight if we give it to this kid um be four and if we give it to the last one it'll be six and if you look at our first array that was given the maximum number of candies that the kid has is five right five is the highest number in the array so max is five and if we distribute like all the candies to um each individual kit we get this array and we what we have to do now is check max number to each number in the array so is five greater than five no but if you look back at the question again we can have multiple greatest number of candies so this is true uh six is greater than five so this is true eight is greater than five so this is true oops um true and four is greater than five no that's false six is greater than five yes that's true so we get chu true false true and choo true false true so that's what we get okay now let's code our solution so first thing we do is declare our function kids with candies which takes two parameters uh candies and extra candies and we know that candies as an array of numbers and extra carry extra candy is an integer so first thing you want to do is you're going to find the max number and the candies array so i'm just going to make a variable named max and this is going to be i'm going to use the math dot function and we're gonna use the spread and i'm gonna spread the candies array so what this does is uh it goes through all the items in the candies array and it's gonna find the max and if we just to return max here we know that max is 5 for the first one 4 and 12 for the last one and now i'm just gonna make a variable name result and set it into equal to an empty array and that's where we're gonna store our result and let's return result okay looks good now that we have our result array we want to loop through all the elements in the candies array so let's make a for loop and we're gonna start at index i is equal to zero and loop through all the items in the array can these dot blank increment by one i'm just gonna make another variable named current value and this is gonna be equal to candies at index i okay and now we want to push in true and false values right so what we're gonna do is result that push and we want to add our current number or current value cv by extra candies and see if this is greater than or equal to max and the reason why we do greater than equal to is because the question said we can have multiple max values uh if you just did this it'll be wrong so greater than equal to max and we get our result um so for the first one there's true false true choo false true second one is true false okay true false and last one is true false true okay all right guys um let's go over our quote one more time so first thing we do is to get a function named kids with candies which takes in two parameters candies this is an array with numbers and this is um integer extra candies okay and next what we want to do is find the maximum number in candies array and i just use the math.max function and i just use the math.max function and i just use the math.max function and what i did is i use the spread operator to get individual items from candy's array and next um declare the variable name result and set it in equal to an empty array and we'll return that later so now we want to go to our candies array and starting at index 0 we're going to go through the whole um candies array and what i did was i just declared a variable current value and set it equal to candy at index i now um we want to evaluate whether or not the current value plus extra candies is greater than or equal to max right so that will result in a true or false value so we add whatever we get from this operation so if we try the first one we have two here actually uh let's use the second one because um we did that already so we have an array four two one two and extra candies is one and this is our result array when i is equal to zero current value is 4 so if we add 1 to 4 we get 5 and that's the current max is equal to 4. so is 5 greater than 4 yes that's true so we get a true and let's add one to the next one we get three for the next one and that's not bigger than four we get a false and next one we get two and three are these bigger than our maximum value for no so we get false and after we get our result we return result finally and we're done
|
Kids With the Greatest Number of Candies
|
all-ancestors-of-a-node-in-a-directed-acyclic-graph
|
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_.
Note that **multiple** kids can have the **greatest** number of candies.
**Example 1:**
**Input:** candies = \[2,3,5,1,3\], extraCandies = 3
**Output:** \[true,true,true,false,true\]
**Explanation:** If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
**Example 2:**
**Input:** candies = \[4,2,1,1,2\], extraCandies = 1
**Output:** \[true,false,false,false,false\]
**Explanation:** There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
**Example 3:**
**Input:** candies = \[12,1,12\], extraCandies = 10
**Output:** \[true,false,true\]
**Constraints:**
* `n == candies.length`
* `2 <= n <= 100`
* `1 <= candies[i] <= 100`
* `1 <= extraCandies <= 50`
|
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
1912
|
670 |
hey guys so welcome back in this video we'll be trying to solve the six seventieth lead code problem that is maximum swap okay so given a non-negative swap okay so given a non-negative swap okay so given a non-negative integer you could swap two digits at most once to get the maximum value number return the maximum value of number you could get okay um so now if you interchange two and seven like you'll get the biggest number right that is 7 2 3 6 but in this case 9 7 3 like there is no possible way of like interchanging it that like you could get a number bigger than this one right so you are supposed to output the same number so now let's see how we can solve this okay um okay so now let's say we have a number that is 2 7 3 6 okay now the first thing we'll do is we'll convert this into a string and we'll put this inside a list okay so now our list will have something like 2 7 um 3 and six okay now we will be having two variables which will allow us to like know which is the biggest number to interchange with so i'll say what i mean by that we'll be having largest okay so now largest will be equal to zero by default and we'll be having index so now index will basically be the index of the largest number to swap with okay so we can exchange with that at the end okay now i'll be having a nested for loop okay so my first for loop will begin from two okay and my second for loop will um begin from i plus 1 that is from 7 in this case okay so now we'll be checking if 7 is bigger than 2 or not now since 7 is bigger than 2 we know for a fact that this can be a possible swap right so now what we'll do is we will put the value of largest as seven and we'll put the index as one right because the index of the number seven is one then we'll come on to three now we have to check if three is bigger than seven or not like only then will we modify that with the largest array so let's say i mean the largest variable so now why is that because if you exchange 2 and 7 you get 7236 right but if you exchange 3 and 2 you get 3 7 2 6 now of course 7 2 3 6 is bigger right so yeah you have to always make sure that the uh like the element in the j loop is bigger than largest so now in this case three is smaller than largest so we'll skip it okay now we'll come on to six even six we know for a fact that it is smaller than largest so we'll skip it okay now after this j loop gets over we have to check if largest is zero or not so now if largest is equal to zero we know for a fact that we found no big numbers that we can interchange with so now in this case like let's say for example i had 2 1 so in this case we can't interchange this in any way to get a number bigger than 2 1 right so now in this case largest will be 0 right because in this case when we come across 1 is smaller than 2 so you know largest will be 0 then when we come across this one it will still be 0 right okay so now after a j loop we are supposed to check if largest is bigger than 0 or not so now if it's 0 we'll continue with the i loop but if it is not 0 we like it means that we found a possible match so what we'll do is we will just exchange the values so we'll um put i mean we like remake the list as seven two three six and that should be it and all we'll do is we'll join this list so it becomes a string and we'll convert this to an integer okay now that is the basic idea about how to solve this problem okay now uh there's one more exceptional case i want to talk to you guys about uh so now the process of checking with largest right so now the process okay now like let's say for example i had a number one two okay now we have to check if l of i like let's just say the um this number is l okay you have to check if l of i is smaller than l of j which basically means that like the l of j is bigger and we have to check if l of j is bigger than or equal to largest okay now why are we checking if it's bigger than or equal to large it's like why don't we like check if it's just equal to so like uh like this is an example for that okay so now i'll be having a for loop my eye loop will be at one okay so my j loop will be at this one now one is equal to one right like it's not bigger than l of i so we'll continue now my j loop will go to two okay it'll go to two it knows that 2 is bigger than 1 right because my i is over here and my j is over here so 2 is bigger than 1 so i'll change the values of largest and the index so now largest will be 2 and the index will be 2 right okay now like if i come acro so now if i had something like if l of j is equal to largest i mean is bigger than largest only to shift it so now when i come across this 2 for example so when i come to this 2 like i know that like this 2 is not bigger than largest right like because 2 is equal to 2 so what i'll do is i will just interchange this i will get 2 1 2 okay now this is the case if you interchange the first two but what if you interchange the second two if you interchange the second 2 you will get 2 1 now we know for a fact that 2 1 is bigger than 2 1 2 right so that is the main reason we put l of j is bigger than or equal to target okay so we need to get the biggest number so now when we'll come across this two it is equal to the largest value so now we'll again so now largest will remain as two how the target will be i mean the index will be 3 and then once we exchange it we will get 2 1 and we can join it and return the integer form so now that's the basic idea of how to solve this okay now let's try to code the whole solution out all right so now i'll be having l which will be our list of string of num okay so we are putting all the numbers into a list we'll be having largest is equal to index is equal to zero okay now for i in range oops a typo for i in range length of num minus 1 okay because our j loop will go at the end okay so now for j in range i plus 1 to length of l it's not nums i'm sorry it's l okay so now what do we do now if l of j is bigger than l of i and l of j is bigger than equal to largest then what can we do we can exchange the values right now largest is equal to l of j and index is equal to j now after the j loop if largest is more than zero which means we found a number bigger than l of i then we can interchange so l of largest is equal to l of i and l of i is equal to l of index right now that should be it then i can just break the loop then i can return the int form of joint l okay now let's see if this works um it gives us a warning that it should be an integer not a string oh i'm sorry it should not be l of largest it should actually be l of index okay and over here it is supposed to be largest okay one very like silly mistake on my part okay now let's run the code and see if it works and there you go it works let's submit so now that's how you solve this problem hopefully you guys got the idea if you have any doubts do leave them in the comment section down below and that's it for this video don't forget to like and subscribe and yeah i'll see you in the next one bye
|
Maximum Swap
|
maximum-swap
|
You are given an integer `num`. You can swap two digits at most once to get the maximum valued number.
Return _the maximum valued number you can get_.
**Example 1:**
**Input:** num = 2736
**Output:** 7236
**Explanation:** Swap the number 2 and the number 7.
**Example 2:**
**Input:** num = 9973
**Output:** 9973
**Explanation:** No swap.
**Constraints:**
* `0 <= num <= 108`
| null |
Math,Greedy
|
Medium
|
321
|
70 |
how's it going everybody in this video we are going to go over the leak code problem climbing stairs so this is a really useful problem to go over if you have never done dynamic programming before this is like the most basic level of dynamic programming before we get started I want to let you know about my technical interview prep platform alos with Michael if you are preparing for coding interviews I highly recommend checking it out so this platform is different from other coding prep websites because I teach you the patterns to solve various categories of interview problems such as sliding window top K element and binary search learning these patterns is literally like having a cheat sheet because you will know exactly how to approach the problem based on the type of problem it is and also just for my YouTube audience you guys get a discount using the code algo help so back to the problem the description says you are climbing a staircase it takes n steps to reach the top each time you can either climb one or two steps in how many distinct ways can you climb to the top so in this first example n equal to 2 the output would be two and this is because there are two ways to climb to the top so if n was equal to two and we had two steps right our goal is to get here uh we could go one step and then one step or we could just go two steps to the top so you know that's one way and then two ways two would be our answer for this input and the second example n equal to 3 so if n is equal to three uh we would have three stairs right and we want to get to the top here so we could do this uh in three different ways actually so the first way is we could just go one at a time so we would go one and then one so that is just 1 + 1 + one and that equals three just 1 + 1 + one and that equals three just 1 + 1 + one and that equals three that means we made it to the third step the other way is we could go one step and then two steps right so that would be 1 + 2 and that also equals 3 and then be 1 + 2 and that also equals 3 and then be 1 + 2 and that also equals 3 and then the last way is we could go two steps and then one step so two 2 + 1 = 3 so in and then one step so two 2 + 1 = 3 so in and then one step so two 2 + 1 = 3 so in total there are three different ways that we could get to the third step by going only one or two steps at a time so for this problem we're going to be doing a bottom up approach and what this means is that we are going to calculate the answers for essentially our base cases so our constraint says that n can be between 1 and 4 so if n is equal to 1 what would be our answer it would just be one right because if we were trying to get to the top of just one stair we can only get to that stair in one way which is just by going up one and then when n is equal to two we can get to the second stair in two ways like we've already gone over and then n = to 3 like we've already and then n = to 3 like we've already and then n = to 3 like we've already gone over we can get to it in three different ways let's calculate what Nal to 4 would be so we could do that by going one step at a time so we could just do 1 + 1 + 1 + 1 we could also do 1 just do 1 + 1 + 1 + 1 we could also do 1 just do 1 + 1 + 1 + 1 we could also do 1 + 1 + 2 we could do 1 + 2 + 1 and then + 1 + 2 we could do 1 + 2 + 1 and then + 1 + 2 we could do 1 + 2 + 1 and then we could do 2 + 1 + 1 and then we could do 2 + 1 + 1 and then we could do 2 + 1 + 1 and then finally we could do 2 + 2 so in total finally we could do 2 + 2 so in total finally we could do 2 + 2 so in total there are five different ways that we could get to the fourth stair by going one or two steps so when n is equal to four we would return five now what I want you guys to notice is that we are building off of previous results that we've already calculated and that's kind of the core concept of dynamic programming you're just building off of previous t calculations so notice at n = previous t calculations so notice at n = previous t calculations so notice at n = 3 you can see that we're just summing up the previous two steps so all we're doing is we're doing 1 + 2 and that doing is we're doing 1 + 2 and that doing is we're doing 1 + 2 and that equals 3 right we're just doing the sum of the previous two steps or when n is equal to 4 we're doing 3 + 2 right and equal to 4 we're doing 3 + 2 right and equal to 4 we're doing 3 + 2 right and that equals 5 so since we calculated our base case answers of when n is equal to 1 and N is equal to 2 we can always know the answer for any n number by just building off of the previous calculations so with that in mind n equal to 5 right all we would be doing is 5 + 3 so we would have 8 and then n = is 5 + 3 so we would have 8 and then n = is 5 + 3 so we would have 8 and then n = 6 we'd be doing 5 + 8 which is 6 we'd be doing 5 + 8 which is 6 we'd be doing 5 + 8 which is 13 and we can keep on doing this for however many steps that we want to compute all right so let's go over the code for this solution we are given an integer n and we need to return an integer which represents the distinct ways that we can get to the top so first we want to handle our base cases so when n is equal to 1 or n is equal to two right so we could have a conditional here that says if n is less than or equal to two then just return whatever n is right cuz if n is equal to 1 then we return one if n is equal to two then we return two and now we need to actually start our dynamic programming algorithm so we could say int first is equal to one and then second is equal to two right because these are our base cases one and two and now we need to start looping starting from three up to whatever n is right and the next step is going to be calculated by just doing first plus second right and then we need to reassign our variables so our first variable is going to become our second and then our second is going to become our third right and then we just need to return the second variable so let's make sure that this works let's submit and there we go so our time complexity for this solution is going to be Big O of n where n is our input and our space complexity is constant because we're only initializing variables here so that is how you solve the problem climbing stairs I hope this was helpful for you guys this is a really good introductory problem to dynamic programming I'm going to be releasing a lot more dynamic programming related videos so definitely subscribe if you want to get notified for those videos and also check out my platform alos with Michael if you want to learn the patterns to solve a bunch of categories of interview problems and with that I'll catch you guys later
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
90 |
okay welcome back to algo js today's question is leak code 90 subsets 2 given an initial array nums that may contain duplicates return all possible subsets the power set the solution set must not contain duplicate subsets return the solution in any order so in example one we have nums array which is equal to one to two and the output contains six different arrays containing all the different possibilities of this nums array excluding duplications so this is just an addition onto subsets the original question but it's a really tricky question especially when it comes to resolving this duplication conflict so let's dive into the explanation okay so for this question we are going to be using dfs and it is going to be a backtracking solution and the way i like to do these is to draw out the recursive call stack so initially we're going to have a result array and this is going to be set initially with the empty array because the solution requires an empty array within the results so we can simply just populate the resume with that and that solves that issue so let's draw out the recursive call stack and see what we can come up with so if we take one at this point we have one in the current array right we need to populate that in the res array now what do we have left well we have two and two so we can either take two or we can exclude two because if we take 2 on both sides this is going to cause duplication right so say we take 2 we have 1 2 in the current array and we only have 2 left to traverse to so we can add 1 2 into the result array now we take 2 we have 1 2 in the current array and there is nothing within the array now so we can add that into the result array so 1 2 we carry out our back tracking so we go up to the previous level there aren't any other positions to go to we go up to the previous level now with this one we have a two down the other side but we aren't going to be taking that so this is a no-go zone so taking that so this is a no-go zone so taking that so this is a no-go zone so we go back to the top now we take two so the current array is going to be two and we have two left to take so we can add that into the result array we take two again in the current array we now have two 2 and we have an empty array to search through so we can add that into the result array we have reached the end of that search so we backtrack another direction to go to so we backtrack again at the top level this is where it gets tricky right so we've got a two here if we recurse down this we are going to get the same solutions as here so we need to avoid that and the way to avoid that is to compare these two values now we don't know initially whether this array that we're initially given the nums array is sorted so we need to sort that to begin with and then we can simply check if i is equal to i minus one so the values are equal to each other if they are then we continue so we move to the next value so say we had four to search to we'd move straight over to that value but in this case we just exit this loop and we return the result array but this is the general kind of structure of how you'd avoid duplications so we'd sort the initial array and then we checked the values that are next to each other whether they're the same if they are we just continue through the nums array so with respect to time complexity on this one we have two branches coming from each cursion and it's going to be to the power of n which is the height of the tree and we need to do that n operations that's going to be n times 2 to the power of n we have this sorted we have the sorting of the initial array which is going to be n log n but this becomes insignificant seen as the overall time complexity already is n times two to the power of n so we take the largest and then space is also going to be o and two to the power of n because of the recursive call stack that we use within the dfs so let's write this out so let's start by creating the result array and we said we initially populate it with an empty array that solves this case within the output let's create the depth first search function so when we called that first search we're going to have to pass in the nums so the nums array we're going to pass in res because we need to populate that passing in an empty array that'll be our current array and we pass in zero this is going to be the index of the number we're on so nums res current ray and we're called the index star so initially before we carry this out we are going to sort the nums array so let's sort that and then we have to loop through this array we're going to take i as the starting index is less than nums.length now we need to make the check to see whether there are any duplications so let's start off with if i is equal to start or nums at i does not equal nums at i minus one so if they aren't the same values so we're going to push into current array num.i then we're going to push into the result current array and we're going to create a copy of this because we are going to be using current array throughout the recursion we carry out the recursive call we pass in the nums array we pass in res which we just updated the current array and we update the index or the start value to i plus one and finally we need to backtrack so we can simply do currentarray.pop we can simply do currentarray.pop we can simply do currentarray.pop let's return res and give this go okay let's submit it and there you have it
|
Subsets II
|
subsets-ii
|
Given an integer array `nums` that may contain duplicates, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,2\]
**Output:** \[\[\],\[1\],\[1,2\],\[1,2,2\],\[2\],\[2,2\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
78,2109
|
382 |
hello hi guys good morning in this video we're gonna see linked list random node before starting just a random request to you guys if you like the video then please hit the like button it do helps me a lot if you like the video if not then it's okay you can also press the dislike button whatever you want but if you like then please hit that it motivates a lot but yeah uh let's start with this video uh so yeah before starting no one has ever explained like this what we're gonna see in this video it's proper traditional on that part the problem says that we are given a single linked list written a random nodes value we need to return a random notes value from the linked list and each node must have the same probability of being chosen so while I am choosing a random node I should make sure that every node should have the same probability of being chosen that's a very big start point please keep in mind cool uh implement the solution class with solution of the list initializes object with the singly linked list okay cool then we have a get random function which choose a random which we choose a node randomly from the list and returns its value and especially all the nodes of the list should be equally likely to be chosen which means the probability of choosing every node from the list should be same cool let's say for example very quickly um we have one two three four so solution will initialize this linked list which means that it will become something like as one two three then get random will need to find a random value out of this whole list so it can like result in anything but we need to make sure that it is if let's say here it is same one is the random value but it should make sure that one when being chosen it should have the same probability as if we have chosen two or three cool so basically if we have three elements so choosing one element out of three element what's the probability it's one by three very simple right choosing one element out of three elements the probability is one by three I can just choose any element for the productive one by three and just write down here so the answer would also have been three one three two one anything it can be so like it's not that okay the answer is fixed right now I can't explain it because it's a random value but the thing is that every element has a probability of one by three of being chosen as we are choosing because initially we have a picture of this Arrow kids one two and three so I can easily say okay the probability of choosing any element or any index out of this particular Vector it's one by three so I can choose any element and that's the whole intuition of this question see it's just a part we will see every part of this problem so if we have this linked list then we can easily make a vector or an array out of it and we can choose an index randomly and when you choose the index randomly so it's probability of being chosen will be 1 by n and thus I can just return the value at that particular index and as the constraints are pretty low so everything will work and it would give the thing in of n time because I am iterating on my linked list I know of n space because I am making an extra array or vector because I need to iterate on the index kind of I just choose a random index which has a probability of being chosen as 1 by n and I just put that value let's see the code quickly so basically here we made the vector out of the linked list cool and when it is made we are choosing a random index and returning the random index value and make sure that it has the same probability of being chosen as well as of the N Elements which means every element has a priority of choosing being 1 by n so the condition which was marked here all the nodes of the list should be equal likely to chosen is valid and we choose a node randomly from the list it's also valid so we returned it cool now okay it's done space and time is done but the follow-ups let's see the is done but the follow-ups let's see the is done but the follow-ups let's see the follow-up first follow-up was what if follow-up first follow-up was what if follow-up first follow-up was what if the linked list is extremely large and its length is unknown to you firstly you might not see okay what's extremely large what is unknown how can possible but I'll tell second point was could you solve this efficiently without the extra space as you can easily see that I choose an extra space right here so if just the follow who was there so I can just follow these steps okay I can just pre-count the steps okay I can just pre-count the steps okay I can just pre-count the length of the linked list because ultimately what I was doing was I was making my linked list as a vector and then seeing okay random index out of all the A and indexes and just returning that index value so rather than making into a vector I can just iterate on this length of the linked list choose a random number between 0 to n minus 1 because I have this length which is n i can choose a random number between 0 to n minus 1 now I have this random index I which is this particular value I can just Traverse back on this linked list from head to tail and stop at this particular index and return the value so here we just reduce the space complexity and as we're trading on this particular whole list linked list so its time is O of n okay one follow-up is done one follow-up is done one follow-up is done what was the next follow-up what was the next follow-up what was the next follow-up next follow-up was what if the length is next follow-up was what if the length is next follow-up was what if the length is unknown what does it mean it means that let's say it's a stream of numbers which is never ending or maybe it is that okay you are being provided with a chunk of numbers let's say I give you five numbers after that I give you eight numbers after I give you nine numbers but you never know what is coming up right now you have to find oh so I explained you what does it mean it just means that you are given n numbers let me change the color you are given n numbers and suddenly a number again comes soon how what you will do you will just firstly that okay it's gone it's done you can't have it now the only thing which you have right now is this particular thing now you want to find okay what will be that a random element chosen because ultimately the probability needs to be one by n because it is being chosen from these n elements so we need to make sure okay if it would have been chosen from here and if it is chosen from here it should have the same probability let's see much with a better example I have these n elements now this one element comes so ads as this is an upcoming element so now we have to make sure that the probability of the chosen element which is this particular chosen element it should be 1 by n as we said that the particular element being chosen it should have the same probability which means that when the element would have been coming from here let's say you forget the blue part let's say it is not here let's say it's not here if it would have been from here and we know n elements we need to choose one element out of it randomly so we will choose every element of by the probability of 1 by n right but now suddenly one element came out of nowhere now if for now you know okay I have these n plus 1 elements right now so now the probability of being chosen is n plus 1 by n plus 1 right because it's an upcoming element but earlier when the blue part sorry when the blue part was not here so you knew that it was 1 by n now with this upcoming element it became one by n Plus 1. but you will say Okay Aryan but you said one thing right every element see this particular one thing I said all the nodes of the list should be equal like to be chosen here in this case you are saying okay uh sorry yeah here in this you are saying that okay choosing this thing has a priority of 1 by n plus 1 while earlier we knew that it was 1 by n so by any how I need to prove that okay it is not actually 1 by n but it will be 1 by n plus one I have to prove you that because if it would have been 1 by n which was earlier only then it would not work right so after the upcoming element it should also become which means the probability by choosing out of these elements which would have resulted in this particular element right here which is the element which we should choose randomly it should also be one by n plus one so that I can satisfy my condition that all the nodes should be equirect to be chosen only red I can randomly try to choose new upcoming element right because else it will not work let's see much more clearly what I've what I meant to say or if you are not understanding what is that upcoming element what's the probability like let's see with an example so basically in our case we have a stream of elements right and we need to choose one node randomly right having equal probability there's the other nodes cool now rather than one note I need to choose one node right let's generalize I need to choose K nodes and for our example we will choose the ks3 now out rather than choosing one node I'll choose three nodes where K is three for example if we have the strip now I will just keep on adding the elements in my stream so make sure that something is coming up spicy I had three elements in the Stream 100 200 300 and my bucket was just of length 3. now I need to put elements in this bucket so let's say I get 100 choosing a number 100 out of these three numbers or choosing a number out of these three numbers it's priorities one by three after we go on to place that number in these three buckets I have three options so one by three into three because for one by three then one option one by three one option so it is one by three into three so basically if and it's it just indicates a one probability which means that every element needs to be in this bucket so it's probability of being Chosen and being placed in this bucket is one for every element okay cool it is one which make sure that okay every element what was the condition all the notes on the list should be equally likely to be chosen here all elements are equally to Children okay we are good now the Upstream come now the 400 the new element came cool new element came as 400 so basically it's probability of being chosen out of n elements because we have 100 200 300 400 so basically choosing one element out of these four elements is probability is one by four which is actually 1 by n because I am choosing one element out of n elements because it's the one element which came now cool facing that particular element which is choose an element which is 400 choosing placing that we have three options because the bucket is three we have three options which means these options are K because it's the bucket of size k so basically we have three options which means that for this 400 element which has which when we choose it was one by four and we have three options one by four which means that it will be three by four it's probability of Chosen and being placed here will be three by four which is nothing but K upon n because here it was K as you can see and here it was N I just showed you that okay it's K upon n you can see here it's K upon n cool no worries but now wait a second it says its probability is three by four but earlier we saw the probability of every element was one they are not same RN is false no I will say no why no because of this upcoming element 400 the probability which was one earlier it now changed to what let's see so basically these elements had the probability of one but because of this upcoming element what happened what should have happened was its probability Should Have Become Three by four but how are you how it's possible so basically the elements were 100 200 and 300 right here so basically probability of 100 being in this particular bucket probability of hundred being in this bucket there are two options for it one option being that 400 never comes in that particular place where 100 is here right basically 400 Never Comes or if 400 comes then it comes at the place of 200 or 300 Only then my 100 will remain in that bucket right so basically 400 it should not come in that particular bucket in that particular place so choosing 400 and not coming it one by four and then choosing that 400 which is one by four and then we have to either place it in the bucket in the place of 200 or 300 which was 200 or 300. it was two options it has cool so it will become one by four plus two by four which is actually three by four which is actually same as that of the 401 which was entered so basically after this entering of 400 what happened was the existence or being of 100 in that particular bucket because I am just trying okay what if 400 comes in that bucket so existence of this 100 being in that bucket it just changed to three by four because of that particular upcoming 400 and the same would go for 200 and 300 it will also become three by four and three by four right cool no worries now let's say another element game which is upcoming let's say 500. what will happen now as is the new element which upcoming element so we can make sure okay that one thing it's already being chosen as one by n which is one by five now after that is being chosen we have three options to place it switches as earlier we saw it's 3.5 which is K as earlier we saw it's 3.5 which is K as earlier we saw it's 3.5 which is K upon n cool no worries but now earlier its probability was 3 upon 4 we saw right it was 3 upon 4 earlier all the elements which was in the bucket while because of the upcoming element it should have been three by five is it really let's see so basically we need to see okay 100 being placed in that bucket what is the probability right now so basically 500 being chosen but not been placed here it is one by five into one 500 being chosen and being placed in a place of remaining places which is 300 400 so that 100 will remain in that bucket I just wanted 100 to be remain in that bucket what is the existence of 100 in that bucket it will be one by five because I need to choose 500 and I just replaced what 300 and 400 and it can be randomly I just purposely changed it from 100 to 100 300 because I know it can be anything random cool no worries it just became three by n which is actually the same as when 500 came so now it's actually what it is called it's called it is sampling as well as sampling it states that it's a randomized algorithm which is used to select K which was the bucket size for us out of n samples n was the stream and as I said I never knew from the starting it was three four five but I just meant on moving and moving in the Stream and still everything worked perfectly where n is usually large or unknown in our example we never knew what was n was earlier here n was three then an element came it become four then a element it become five so it just kicked kept on increasing and it is what is Reservoir sampling I hope that you guys got it's very simple code is uh we initialize the head then we just initialize okay the current basically the current will move on up till the end of this particular thing now up till I just move in my particular link list and every time at the I8 index basically this particular thing is just moving at the index of this particular linked list cool randomly choose that element because here I was doing yours I was choosing 500 randomly cool I just choose randomly and I just should come or not here's the random function which we choose that okay if this is a random okay it will come or not it is random function so it will automatically be randomized it will come maybe or not coming then I can just simply say okay I'll just return my result now you will say Okay RN it's the same that you knew the size you knew everything then what's the point firstly before moving here I choose a node randomly in my example I choose I showed you that you can choose number of buckets which will be like which was K as random so basically in our case we had to choose a node randomly a node will be between one node and that's my case one cool no worries but why was that needed because I was I already knew the size and everything I just say one thing what if that if we had another link list with another head let's say then I initialize my another current and then iterated within another loop then still it would have work because there is a wire sampling helps us to elaborate conditions on the basis of chunks and not particular like whole thing we can break things in chunks and we can just process the same thing again and it will work and thus I can just add another loop another element or another anything and still the answer would be correct without needing to iterate on this previous Loop so I hope that you guys got it the video has gone bit lengthy but yeah it was very important for me to explain why this was needed how did we got the tuition and I never started with what business was sampling and what is all that stuff I just intuited in the last okay it is called Reservoir sampling what we are doing and yeah ultimately we got the answer so if you guys liked it then do it the like button helps motivates a lot and it's going to do that goodbye take care
|
Linked List Random Node
|
linked-list-random-node
|
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?
| null |
Linked List,Math,Reservoir Sampling,Randomized
|
Medium
|
398
|
1,765 |
hey everybody this is larry this is me going with q3 of the bi-weekly me going with q3 of the bi-weekly me going with q3 of the bi-weekly contest 46 map of the highest peak so hit the like button hit the subscribe button join me on discord let me know what you think about this prom so this prom is a little bit awkward um so basically the idea is that each cell um you know the idea is that okay you have cells of water uh and then you have cells of the max and then you try to figure out you know any two adjacent cells have at most distance of one so then what does it goes out to be right and the i think the diagram is actually pretty standard uh pretty basic if you will pretty fundamental and i'm not saying that to say that this problem is easy because converting this problem to that algorithm is kind of tricky and requires a little bit of insight and math and i don't know why this is in five in c bus plus um but yeah but basically what i did was my first search going from uh the water tiles so basically the idea is that you know let's say you have some input let's say look at this one right let's make it a little prettier um the idea is basically that you know um because um yeah uh because you want to maximize the height the thing is that the maximum of the height is going to be bound by you know its surroundings right and you know and i think we start off by you know making sure that the water times are zero so that's i mean that just has to be true so you know let's just say we have x zero uh i mean this has to be true because it's just the definition of the problem um you know 0 x right and then now by default well what's the maximum height of the um things that are bigger than zero right well it's going to have to be one so we can set this to one right and then the question is well why can't this be two um because oh actually i lied because i think it's just up down left right so i actually like on that one um so okay so this is the what it would look like right and then the question is well why can't this be two well this can be two because if this is two then this zero you know this violates the invariant of keeping it by one so it ends up being that you reduce this to the short um or pairs or not or psi multi source shortest path uh algorithm where the rates are one because basically you get another way to think about it and you know you could do this in a number of ways i think if you do it another way the complexity may be slow um is that okay given each water um given each water tile right uh you look at the distance from each um thing so for example looking at this one uh this is the distance to all the mountains right so if this is if there's only one water tile then this is going to be the answer and i hope hopefully that makes sense and that explains why right so then now we do them independently so let's say let's do this one so then that one the you know we start with 0 and then now we go out and actually this is easy for me to do okay something like this right so this is the shortest distance and that's what the mountain the highest peak would look like um and now to make sure that they're only constrained by one we take the min of these two graphs so you look at this one and then you look at this one and you just combine them in a min way and that's basically how you would get the answer to enforce that you know all the neighbors are at most one because um because yeah and it turns out that you reduce that further and some of this requires playing around and proving it to yourself so um i'm gonna leave that as an exercise at home which is another way of saying uh i you know like i know how to explain it but it might you know the intuition is something that you have to kind of you know draw maps and figure it out itself but after that uh the code itself is pretty straightforward once you get that understanding which is not an easy understanding but once you have that understanding um then becomes a multi-source shortest um then becomes a multi-source shortest um then becomes a multi-source shortest path and this code is basically how i m i probably do variation of this all the time so um so yes i was able to solve this in about four minutes um during the contest um but yeah so what's the complexity well it's just a breakfast search on a grid so it's gonna be linear in the size of the input because the number because you know bfs is equal to o of v plus e uh the number of vertexes is you go to o of you know rows times columns which is linear and then e is equal to row of also row times columns times four up down left right also linear um and this is linear in the size of the input because the input is all times c so it's going to be linear time linear space because the size of the q and also i guess the result that we return are also going to be linear in the worst case so uh well in this case it's just linear always but yeah so this is linear time linear space so yeah so this is o of n times time and space this is linear right um that's all i have for this problem let me know what you think um i sometimes i go over the code but this is actually very standard for me you know at least that's the way that i usually write my multi-source that i usually write my multi-source that i usually write my multi-source uh bfs so you know if you have any questions let me know but um you if you know if you have trouble understanding this code i would definitely urge you to practice other breakfast search problems and get it from and do it your way and kind of get familiar with it um that's all i have you can watch me sober live during the contest next why is there two in there oh the two is the output okay i think this is a binary search problem but um okay alright okay i think my neighbor is moving and it's really loud in the background for me i don't know if you could hear it if not that's great but it isn't bothering me for sure i don't know what's going on um hey thanks for watching hit the like button hit the subscribe button join me on discord and i hope you know you take care of yourself take care of others if you get the chance you know stay good stay well uh to good health and to good mental health i'll see you next time bye
|
Map of Highest Peak
|
merge-in-between-linked-lists
|
You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells.
* If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell.
* If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell.
You must assign each cell a height in a way that follows these rules:
* The height of each cell must be non-negative.
* If the cell is a **water** cell, its height must be `0`.
* Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
Find an assignment of heights such that the maximum height in the matrix is **maximized**.
Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_.
**Example 1:**
**Input:** isWater = \[\[0,1\],\[0,0\]\]
**Output:** \[\[1,0\],\[2,1\]\]
**Explanation:** The image shows the assigned heights of each cell.
The blue cell is the water cell, and the green cells are the land cells.
**Example 2:**
**Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\]
**Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\]
**Explanation:** A height of 2 is the maximum possible height of any assignment.
Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.
**Constraints:**
* `m == isWater.length`
* `n == isWater[i].length`
* `1 <= m, n <= 1000`
* `isWater[i][j]` is `0` or `1`.
* There is at least **one** water cell.
|
Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1.
|
Linked List
|
Medium
| null |
704 |
Hello Everyone Welcome Back To My Channel Short Today Khayal Ko Increase Ko Shraddha Problem And Here Problem Is Binary Search Tree Will Be Discussing Va - Binary Search Tree Will Be Discussing Va - Binary Search Tree Will Be Discussing Va - Versus Yes This Sach Works And Sports Rosemary Fundamental Topic Write In Data Structures Algorithm By Any Such Native With Problems That life airplane teacher with spotted in ascending order to address given and spotted in ascending order ok a very important day respected and interior target write function to search target in that very basic rent explanation is one number target any to find weather the target in that River Or Not Ko Iftar Exit Temperature Indicators Otherwise Return - 1m OK Otherwise Return - 1m OK Otherwise Return - 1m OK Weight Lifting This Test K 100 Servi A Hearing Test Case Where To Find Weather Nine Second Or Not So Nice Day And Didn't Give One Two Three Four Points Ko Pause Of Ninth Hindi Fonts for so in its present it returns in tax return stop in this index 8110 test case here targets to right here from this 0.22 is not be so is the element the return 0.22 is not be so is the element the return 0.22 is not be so is the element the return of the element is not the return - - of the element is not the return - - of the element is not the return - - 2 OK no one simple approach is very easy they can just hydrate in directions reveal hydrate will not travel tours and travels is egg and will check the limit language the star kid a lot for example of the target and five I will certainly no point is equal to zero still having got even Last index and i plus every time they will check agarose file rtice element if it is equal to do it a is it is equal to target what will i do avengers return online tax return came which index ok so year - 1615 will which index ok so year - 1615 will which index ok so year - 1615 will go For 0453 is not good for 2ND year fair and 504 505 Vitamin E that how simple something ok but in case of road traversing the indirect now everything needed to give the target with the target to avoid you are watching Vitamin E that in the Worst Case Invest This Will Give Meaning Intelligence And Travels In Every Bird Its Food 2050 Blast Index Dominant Targets Achieve So What Will U Will Be Traveling Decide Forward To 12925 Not A Good Speech In Go For Know 5th A Suite My Nail Giving Target With Me Too Find Is Add Last Index In Every Student Travels From Starting And Check Element It Is Equal To But I Don't Like This Condition I Have Every Time Way How To Check Previous Year's It's Because Target With Me To Find The Two Drops In The Dark How To Find So it is traveling in tire and watch this time complexity of any number of elements in the phone ok so go to Swedish approach first time complexity of introspection the issue is the problem of the written that you must write an algorithm with law and order in time complexity the Time Complexity Morning Login Button First Time Complexity Of Linear Search Wale Liquid Liner Element Comparing With Vitamin E Record No Judgment Linear Lee Das Wife This Project Is Near Search But This Time To Villagers Who Spread To Win* Improved And Will Have To Make log Win* Improved And Will Have To Make log Win* Improved And Will Have To Make log that me to make login will have to make lord of 10th and hear little doubt approve laxative in research work okay by Sachin and this search operation in search of time they do the thing e that sensitive beneficial flashlight on in nine left How many spokes are a 102 let's my tab where from Dimple Soni - 1035 - 103 my tab where from Dimple Soni - 1035 - 103 my tab where from Dimple Soni - 1035 - 103 15 Fab and Know No Wealth and Targets Five Targeted Five that I Don't Thing 2012 Three Four and Fame and Listen See What We Do in Binary Search for Tomorrow Morning Tweet Serious Steps of Minor Changes Will See How It Works on Phone Tapping Binary Search Tree Find the Midday I'll Find Some Idiots That Have Found a River But Before Finding Dismissed 10 Steps You Can Say Is to Take Two Variables Low in This Noble Will Be Storing Starting Index Which You Are Another Absolutely High Will Be Storing The Last Indexes 5 Tomorrow Morning Slow Stories For Kids And Histories Last Index Of The Evening The Indian Freedom Fighter Middle Inquiry Is Hello How They Find And Access Media And X Is Equal To and writing styles made metal index is equal to low n This to the meaning displacing index sweet sumit da the mid-19th century add that mid-19th century add that mid-19th century add that into what is this tomorrow morning for crr and driver number 700 beating 10 withdraw from this there with oo that made in ets2 and middle element 3D animated 3D is so sewn What we do in binary search the first point view take 12000 festival tips giving figure metal index which came out with two tourism in the recent past What we do now is very important point given the problem is that which is reported in ascending order on And other smaller ones because - 1035 to Zor And other smaller ones because - 1035 to Zor And other smaller ones because - 1035 to Zor Trade in Ascending Order on OK So What We Will Do It Swift Metal Index Will Find What is the Middle Index Value Water Element Is the Metal Index This Year of Media in Taxes and Support This Threat I Disrespectful Topic And target today's date final will check weather this target in greater day see weather were target that this is greater than when middle element which direction will get minute free this middle element so that this target is grated ginger middle element and the target is relaxed and middle East that now you see this target is great and middle element servi what is target side element what its pride and target is file is greater than what is the condition of in this condition target is greater noida middle agreement to what you think they will be The laptop model element and under the right of the video that directly listening to right in water should right of freedom under the right of three days when it is hair oil elements with great attention on that and under the laptop free all elements will second only Target is greater second target with also inside take right hand side you free mode turn on right side right hand side tamil element hearing aids page no 200 bear low here and have seen a that you just 2.5 right how to that you just 2.5 right how to that you just 2.5 right how to find which where is the other not And 209 rates on target with five great Indian middle element will be in rights of some benefit searching in right yes right the benefit in right yes no point in searching for record office let five great attention to what will be the right of freedom in these Stupid photo laptop not ok you they target is greater noida raw middle element will go to the ceo vikram middle plus one class 12th a noble kam hi koi virus ki lo belkom clear ki hey yaar 9:00 this ki hey yaar 9:00 this ki hey yaar 9:00 this claim scripted low to high the delhi special Elastic Listen Specify Are You Can Specify Face Search And Festival 2014 1.5 Inch 1.5 Inch 1.5 Inch Greater Than Any Right To Left For Nothing Too Low How To Have A Terrace Ya Ki Medical Mean Equal To Two Plus 138 Remix Ki Download Listen To Ok Sona Va Laddu Father Swimming Which Now And What Will You Find That Made Flight Mode Turn On That Show That Made Will Be Ide Index Also Find Media Will Be Low Plus I Want To See A Lower And Higher Oil Se Indices Dongre Confusion Lohavat Free A Series Of Conduct Plus He what 505 in this will ka 1248 124 test metal index is used oil so guys this side other defense responsible element middle index of this area election on this what is hair oil media file player of the year of the phone yr office nahi aa ke daag Will See and Target in here CR Target is 502 and Hear It Means Effective Edit Minutes Will Be to the Left of Ninth Office Late Will Not Be to the Height of Ninth Class to the Light of Nine We All Elements Greater Than Not Developed Haunted Show Effigy In the meaning of banal f-18 chair with a ok so what will do witch chapter he to made induct minus one 's daughter next what then 's daughter next what then 's daughter next what then 552 idiots minus point witch 300 I will come here 988 hydraulic and trick ko sweet welcome to Three D A Aur Sunao Leta Game C What Will Happen In The Air Okay Good Night See You Aur Navghan What Will You Find That Made Against This Step Will Find Videos With Equal To Low Plus I Want To See A Noble Side To What Is Lohri what is higher than divided into which will be six bittu than some idiots in no way notice after minutes ago i soya do meeting one is this year of which of this five in ecuador target 55.50 successful 55.50 successful 55.50 successful notification aa torch light condition which 10,000 due to which Condition refill which 10,000 due to which Condition refill which 10,000 due to which Condition refill third edition you will be lost condition and target is absolutely the ecological c equal to year of media That woman 17 2014 status ok and still 3G is a view of freedom index I hope you understand this algorithm Binary search very busy every time I find matter if they compare the width of the wider element than the width of the target targets greater than the middle element Winning Target Will Be Too Right After Maz Pe Parlu University Target Is The Meaning Of The Name Of The Meaning Of E Will Right Viral Low Is Lieutenant Equal To High Share It Will Daily Want To Request Was In The Last Low Also A 3D Live Wallpaper 3D Song again with the thing to win you to do the thing anil edison electronic and this 12448 pathri bodh monk solid directly which account this proof of which code very simple review is proposed a the first deccan since 2008 district labor election record only final to middle Element Id M Id That Daily The Middle Element Is Equal To Target That Founder Target Soen Return Vid Is Otherwise Only Tempered Glass Day B Target Previous Bank Market Leader Admits Meaning Of The Giver 2018 Class Is Nothing In Return Servi To Mean That This Element Target Was Not In System - 138 System - 138 System - 138 That Know How This Form And Complexity Is A Half Years Of Love And Complexity Time Complexity Every Time But Every Time I Request One Part Of The Laptop Left And Right Left With No Veer Is Active This Point To The Every Time is e are due singh are wow aap rate badhe how to actually this like process to calculate list of but e just like they divide into every time they will refer to live for nine the process but not for research and they calculate That lets right like vowels important context for nine see over a year hello how many element skin be in the name classes loop established on that its established up then a how to take ₹10 up for will be the lashed how to take ₹10 up for will be the lashed how to take ₹10 up for will be the lashed is also a maximum minute like example Amity School Maximum Intact So Let's Los Also On One Side And These Is Also A Temperature For U 120 Calculate Low Plus Yes Betu Ko 2015 Virtual For Class Seventh Floor Bike 220 Mortal For Quitting Smoking Is And Right But See That Which Will Get To Arvind Singh Teacher Record Seat In 2G Is From This Negative Number To This Beerwali This Story In The World In Win 10 Inch Is But Some Times What Happen It Is Test Cases Of Very Cute Loop Se Effective Less Above Line Is OK And Greater Noida To Something Dar Suit Most Probably it will feel your bismil overflow Can right intent that made is equal to low plus high - that made is equal to low plus high - that made is equal to low plus high - low by two is raw calculating the middle agreement will give correct answer for the effigy that is logical to live no is show and hide is 50 oy or plus 5 - 0.25 will give one correct 50 oy or plus 5 - 0.25 will give one correct 50 oy or plus 5 - 0.25 will give one correct Ne ok so just once son please subscribe my channel and see
|
Binary Search
|
binary-search
|
Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 9
**Output:** 4
**Explanation:** 9 exists in nums and its index is 4
**Example 2:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 2
**Output:** -1
**Explanation:** 2 does not exist in nums so return -1
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 < nums[i], target < 104`
* All the integers in `nums` are **unique**.
* `nums` is sorted in ascending order.
| null | null |
Easy
| null |
5 |
hi everyone today we are going to solve the problem longest palindromic substring the problem statement is given a string s written the longest palindromic substring in string s if you don't know what a palindromic substring is let us consider the given string so we need to find the longest palindromic substring so what is a substring any group of more than one letters in a given string is called a substring in this case ba can be a substring b a b can be a substring or b a can also be a substring so any group of two or more letters can be called as a substring in a given string and what is palindromic in the sense if we read any string the same from left to right and right to left it is called palindromic for example race car if we read from left to right race car it becomes rates this car when we read from right to left it becomes r a c e c a r which is race car from left to right and right to left so this is called palindromic so in the given problem we need to find the longest palindromic substring which means that we will take a substring out of this given string and find the longest substring that can be formed out of this given string there are multiple approaches to solve this problem the first approach is like from the given string b a d let us form all the possible substrings let us iterate through all the letters from the beginning start with b and form the form all the substrings that can be formed with letter b and then start with a then with b and again way and D so we get all the list of substrings from the given string and among these substrings we find which term which among these substrings are palindromic and find the longest among this one so this is the one approach and the other approach is to use pointers like for example in the given substring we use two pointers one will start at B and the other will also start at B so let us call this I and this one as J we will be continuously comparing if I equal to J so in this case I equal to J which where we have the substring as B it is of length one right now we move I 2 what's left and J towards right so as there is no element on the left so we stop moving these pointers and then we start with letter A so our I and J are now initialize that letter A let me write it here so we have our I here and we have our J here so we check for I equal to J in the first case I is always equal to J so our substring is a which is of length one then we move our I towards left and J towards right so our substring now becomes bab and now again so we know that our I is here and J is here and now we check for equality so B is equals B so our substring now is b a b which is of length 3. again we move I towards left and J towards right so for moving I towards left there are no elements on the left then we start with the next letter so the next letter is B so we initialize I and J here and when we move I towards left and J towards right it becomes I will be at a and between we have B and J will be at a so I is equal to a so our substring now becomes a b a which is of length 3. then again we move I towards left and J towards right so now our I will be at B and J will be at D now again we compare I equal to J so B is not equals to D so we will not see any palindromic substring so like that we will be iterating through all the letters in the string and the palindromic substrings that we found are bab and a b a so the one with the longest length will become our result so in this case b a b and a b a are both of same length we can use any of them as our longest palindromic substrings now this is one case now what if there is another situation where our substring is V A B A so in this case if we iterate the same way we did for the last case the maximum substring that we should be getting is Bab which is of length 3. and there is one more way to do this which is by starting I at a pointer I at B and pointer J RTA now we compare e for I equal to J both are not equal what we do then we shift our pointers towards right so from b a now our I pointer would be at a j Pi enter would be at B again we check for I equal to a both are not equal then again we start with initializing I and J here so I set B and J that b both are equal now our substring becomes BB so this is a valid substring of length 2 and then we move our I towards left and J towards right which now becomes a b a and a on the left a on the right and a on the left are equal now our substring becomes a b a which is of length four and now again if we move I towards left and J towards right on the right there is no element so we cannot move so like this we will be iterating throughout the string and we find that this is the maximum possible palindromic substring Abba but if you have followed the previous approach we would have got B I mean we would have got bab which is of length 3. so the two cases in this problem are Bab and a b a if you consider these two this is of odd length palindromic substring this is of even length palindromic substring so we need to write a solution which will cover both of these situations so let us score this out and see how we are going through so how we are going to solve this problem I am using python to solve this problem first The Edge case check that we are going to do is if length of string is less than 2 we just written that string the length is 2 is it would be 0 or 1 so if it is 0 or 1 if it is 0 there is nothing we written if it is 1 will we return the same string and now let us initialize two variables one is result which will be of empty string and the other one is of max length which is of 0 for now let us first try to solve for R length palindrome for every letter in the given string let us initialize two pointers left and right pointer both starting at the letter I mean both are starting at the same letter the condition that we are going to check is L should be greater than or equal to zero and R should be less than length of the string the letter L and write pointer should be the same if this is satisfied we check the length of the parent room palindromic substring which is R minus L Plus 1. if the length is greater than max length then we update max length and we also update result and once we do this decrement L by 1 and increment R by 1. now this will solve the problem for odd length palindrome substring again for even length palindromic substring what we do is we write the similar code but now we will be initializing right Point rug I Plus 1. and at the end we written the result and let us try to run this code and check if it runs perfectly or not okay this solution is accepted and let me try to submit it so the solution is accepted so this is one of the simplest solution for solving the longest palindromic substring and this problem is being asked in many data engineering interviews so in case if you are preparing for data engineering interviews and if you don't know what are all the topics that needs to be covered in DSC you can subscribe to my channel I will be posting videos related to DSA for data Engineers that's all for today see you in my next video
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
518 |
welcome to joey's tech my friends in this video of choice tech you are going to learn to solve a coin change 2 problem from lead code we are going to solve this problem using the dynamic programming technique so why not go directly to the problem statement you are given an array of coins basically these integers represent coin denominations in our example three coins of denominations 1 2 and 5 are given note that these coins are in infinite supply now you are also given an amount let's say in our example it is five so you need to find out the number of combinations of these coins of denominations one two and five that make up this amount five so if the amount is five then there are four combinations using the coins given which are possible in the first combination five is being formed by five coins of denomination one in the second combination five is being formed by three coins of denomination one and one coin of denomination two in the third combination five is being formed by two coins of denomination two and one coin of denomination one and in the final and the fourth combination five is being formed by using a single coin of denomination five thus there are four combinations possible so this number four is whatever dynamic programming algorithm must find out so let's now move to discuss the dynamic programming approach using which this problem can be solved but before that a humbly request to you to subscribe to my channel and hit the bell icon if you haven't done it already as that way you won't miss out on these dynamic programming videos i create for you there is a video i made on the problem of minimum coins change in that video i showed how to solve this problem of minimum coins change using dynamic programming using a single array approach i suggest you watch it first and then resume this video you can find that video in the i button so i used the same single array approach to solve this problem but it didn't work out for me thus i took the liberty of coming up with the tabular approach there are two pillars already available number one is the amount which when counted from one to the value forms the columns and number two are the coins that are forming the rows okay there is a zeroth row and a zeroth column that we are also going to put in this table to facilitate the algorithm you will understand why we did that in a while there is one more prerequisite that we need to take care of which is filling the zeroth column with one and the zeroth row with zeros all right again i must say that you are going to understand why we did that in a while now we start from this cell so in how many ways can we form the amount one using the coin of denomination one it's simple only one so we put one over here in the cell currently we are using common sense to understand the approach from the next row onwards i'll tell you how the algorithm is going to make the calculation moving to this cell in how many ways can to be formed using coins of denomination one given that the coins are in infinite supply obviously so again the number of ways will be one okay similarly all the subsequent amounts can be formed in one way using coins of denomination one now let's move to the second row we now have two coins in consideration the coin of denomination 1 and the coin of denomination 2. the key to this problem lies in understanding that there are two scenarios pertaining to any amount for example if the amount is 5 then the number of ways in which this amount can be formed only using this coin of denomination 1 and number 2 the number of ways in which this amount can be formed using the coins of denomination one and two okay so in scenario one five can be formed only using coins of denomination one and in scenario 2 5 can be formed using coins of denominations 1 and 2. this is the key actually this is the key to many dynamic programming problems now when the amount is one then in how many ways can we form one using the coins of denominations one and two common sense says only one way how the algorithm is going to derive that but it's going to look at this which contains the number of ways to form the amount 1 using only the coin of denomination 1 it's going to take this value and first populate in this cell okay and then it will check if 2 is less than or equal to the amount 1. since here 2 is greater than 1 hence it cannot form the amount 1 in this universe so the algorithm is not going to do much in this case especially it's going to simply populate this cell with the value of this cell and that's it will move ahead so the elbow moves ahead now the amount is 2 now so the elbow is first going to take a look at this cell which gives it the number of ways to form two using only the coin of denomination one okay so it's going to populate one into this cell now the elgo will check if 2 is less than or equal to the amount 2 over here yes it is in this case so what it is going to do next it is going to subtract this 2 from this 2 which is going to give it 0 okay so the elbow is going to go to this cell at column 0 and what's the value over here it is 1 so it is going to add this one to this one all right which will make this cell's value as 2 hence there are two ways to form 2 using the coins of denominations 1 and 2. now what's the logic behind it subtracting 2 from this amount 2 takes us to the amount adding 2 to which gives us this amount to only so hypothetically if 0 could be formed in one way using the coins of denominations 1 and 2 then there is also one way in which two can be formed using the coins of denominations 1 and 2. when we add 2 to the 0 we get 2 that's the logic and now you understand why to facilitate the algorithm we kept this zeroth column as one only don't worry if it sounds complex at this point in time because this will be very clear to you in further cases okay so the algorithm is going to move to the amount three now the elko is first going to populate this cell with one because there is one way in which three can be formed using only the coin of denomination one so let's populate this cell with one all right now in the second scenario when the amount is three let's see it from a different perspective let's say if the amount is one and if we add a coin of denomination two to it we get the amount as three now the number of ways in which one can be formed using coins of denominations 1 and 2 will be the same in which 3 can be formed using the coins of denominations one and two so the number of ways is one in which the amount one can be formed using coins of denominations one and two so there will be only one way in which three can also be formed using coins of denominations one and two and how we reach to this column by subtracting two from three okay the value over here is one this one when added to this one is going to give us two hence there are two ways in which three can be formed using coins of denominations one and two now the elbow moves to this amount four so it's going to first populate this one over here this one indicates the number of ways in which 4 can be formed using the coin of denomination 1 2 will be subtracted from this 4 which is going to take us to this of this row only here the value is 2. what does this mean that 2 can be formed in two ways using coins of denominations 1 and 2 both included all right so this 2 when added to this one is going to give us 3 hence there are 3 ways in which four can be formed using coins of denominations one and two okay note that this value over here includes the number of ways using the coins of denominations 1 and 2 and this cell gives you the number of ways in which this amount can be formed only using the coin of denomination 1 and this sales value is the result of the addition of these two values all right now the algorithm moves here the amount is 5 so it will be 1 first which will be populated and then 2 subtracted from 5 is going to take us to this cell only that means there are 2 ways in which 3 can be formed using coins of denominations 1 and 2 when added to this one is going to give us 3 only i hope now you understand why we kept the values of this 0th row as 0s because even though we calculated these values using common sense but the algorithm is going to derive the first value from here only okay now we move to the third row now the coins are one two and five all right the amount is one now the elgo is going to come over here in this final row here in the second scenario 5 is the denomination that will be considered along with 1 and 2 all right and you can see that all these amounts from one to four cannot be formed using the coin of denomination five because they are less than five okay so in all these cases these cells will be populated with the values of the cells above them so let me straight away populate these cells with the values of the cells above them in the interest of time so this cell will be populated with one this cell two three and we now come here to the final cell in this cell first the elbow is going to populate the value from this cell so three will be populated over here okay that means the number of ways in which five can be formed using only the coins of denominations 1 and 2 has already been considered now since 5 is less than or equal to the amount 5 so 5 will be subtracted from 5 which is going to take the l go over here the value over here is 1 this one will be added to this 3 which is going to make this cell's value as 4 okay and this cell gives us the number of ways in which we can form this amount five using the coins of denominations one two and five which are in infinite supply problem has been solved using the dynamic programming technique you will find the working code to solve this problem on my github link which you can find in the description box of this video and with this we have come to the end of this video i hope you enjoyed learning this dynamic programming problem from joey stick let me know in the comment section if you have any doubts related to this problem i'll see you in the next video of joystick goodbye and take very good care of yourself
|
Coin Change II
|
coin-change-2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Array,Dynamic Programming
|
Medium
|
1393
|
303 |
welcome back to fast talk channel in this video try to expand 303 range some query mutable even an integer array Norms handle multiple queries of the following type calculate the sum of the elements of nouns between indices left and right and close the fare left is less or equal to right implement the number Ray cost normally cost initializes the object with the integer array Norms method sum range Returns the sum of the elements of nouns between indices left and right inclusive I.E times left was number so left pause I.E times left was number so left pause I.E times left was number so left pause 1 until now until nums is Index right so let's go to the code I have the class now array with Constructor nouns and this nouns is nums some range method it's a function with indices left and right I also have a counter the defined variable C which is equal to zero and I have a cycle this within left let I variable the defined variable I was in is equal to the left in this index like this and while it's less or equal to right we should update our I index and after that we should update our counter it's a c uh with this nums with I index and after that we should return our counter so let's run and let's submit our final solution thanks for watching bye
|
Range Sum Query - Immutable
|
range-sum-query-immutable
|
Given an integer array `nums`, handle multiple queries of the following type:
1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`.
| null |
Array,Design,Prefix Sum
|
Easy
|
304,307,325
|
1,616 |
Hi Halloween welcomeback chicken driver withholder fighting Liverpool Destiny episode wikikopi so Fortuner challenge for speaking to Strings so before we love you so much often twinbet finished uh cardboard lemon Twist Shout your server more Travel the second care@jne. co.id methods love you how are you marry me is one of the network and you can speak your mind he himself Poison hand so banyusri testing YKS and you need to speak testing downloadfilmbaru21 you can come on Dad you can make by combining yes prefix and can be fixed or you can come bridges and you can make even so remixed version is just the stars from the sky separately the United States high official prayer because Singgih and check if think by and Yudi posted by vibration Rohmat about semi cool ke Official Facebook as high as possible is if ye or be otherwise balendrong make here because each is often the one that makes me confused. Wheels are finished where is the selection of wireless bridges of wbc instinct b&w Chaeri y n g often D wbc instinct b&w Chaeri y n g often D wbc instinct b&w Chaeri y n g often D play matching and Brother unit savefrom.biz Kyle What are you savefrom.biz Kyle What are you savefrom.biz Kyle What are you bridges to you for download on the basis of critical apliksa short piye if you subscribe if with the Sheep Sharp DDR2 finspire afiqshop with shoulder Like [ with shoulder Like [ with shoulder Like Mike Live Once Hi suhir scorched earth The Morning driver ot17 function cgvg setting fragment from the station is even crown subscribe Hi hopefully installing station legonkulon Poison sik fresh Persada USB auditor behind freede Nira Poison ichtus also Rhapsody full yourself Must have to steal the song comprehend The Processing of wedding website Zulfadli snow Falls from the check-out and up to snow Falls from the check-out and up to snow Falls from the check-out and up to zero-length Israel zero-length Israel zero-length Israel MP4 Hi and freestyle rowogandu Jack's promise to finish ping Abi again now to cigarette consumers and chef brands every bottle cromwell.co.uk suhono Kristal G bottle cromwell.co.uk suhono Kristal G bottle cromwell.co.uk suhono Kristal G Bosen Jero of Change and tour invoice love checking out Carrefour mystery hitchhiker promo Hi starring Andy consumers so after this let Suddenly we check whether the spring Love From The Star episode recaps sekampusnya dan subjects from a question of the week end at the lake Hi yesterday's perception and simple riordan Fort Lenovo 1901 sing ngati-ati you know Fort Lenovo 1901 sing ngati-ati you know Fort Lenovo 1901 sing ngati-ati you know soap operas Shooter about compresses take shelter certification Hi Ho Kya most sophisticated pockmarks Yes technically convey cheating in tanks Wulan hai Hi send email chain Miss lives a life of sustenance until production is acceptable, test Thanks for watching, forget to subscribe
|
Split Two Strings to Make Palindrome
|
minimum-difference-between-largest-and-smallest-value-in-three-moves
|
You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bsuffix` or `bprefix + asuffix` forms a palindrome.
When you split a string `s` into `sprefix` and `ssuffix`, either `ssuffix` or `sprefix` is allowed to be empty. For example, if `s = "abc "`, then `" " + "abc "`, `"a " + "bc "`, `"ab " + "c "` , and `"abc " + " "` are valid splits.
Return `true` _if it is possible to form_ _a palindrome string, otherwise return_ `false`.
**Notice** that `x + y` denotes the concatenation of strings `x` and `y`.
**Example 1:**
**Input:** a = "x ", b = "y "
**Output:** true
**Explaination:** If either a or b are palindromes the answer is true since you can split in the following way:
aprefix = " ", asuffix = "x "
bprefix = " ", bsuffix = "y "
Then, aprefix + bsuffix = " " + "y " = "y ", which is a palindrome.
**Example 2:**
**Input:** a = "xbdef ", b = "xecab "
**Output:** false
**Example 3:**
**Input:** a = "ulacfd ", b = "jizalu "
**Output:** true
**Explaination:** Split them at index 3:
aprefix = "ula ", asuffix = "cfd "
bprefix = "jiz ", bsuffix = "alu "
Then, aprefix + bsuffix = "ula " + "alu " = "ulaalu ", which is a palindrome.
**Constraints:**
* `1 <= a.length, b.length <= 105`
* `a.length == b.length`
* `a` and `b` consist of lowercase English letters
|
The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array.
|
Array,Greedy,Sorting
|
Medium
| null |
1,685 |
hey everybody so today we're going to talk about the leite code daily problem um from well I guess Friday November 24th to Saturday November 25th and that's the sum of absolute differences in a sorted array now this is a decently straightforward greedy problem use prefix sums to find the answer you need to do a little bit of manipulation of the math to come up with um the intuition for the solution and that's the most important part so let's get started with that so let's think about an index and an array um and note the array is sorted so if we take like index two which is six every number to the left is going to be less than six or equal to six but not more so the absolute abute difference of this six and any number to the left of it's going to be six minus the number because that's going to be positive as six is greater than the numbers greater or equal to the numbers to the left of it so we can represent the left side at some index I taking the sum of the ab absolute differences um which can be simplified to just taking the number at I minus the first number plus the difference between the number at I minus the second number all the way up to the number right before this number now notice we can actually rearrange this because um addition and subtraction played nicely together um this is actually equivalent to adding the number at I plus the number at I for a total of I times minus the first number minus the second number minus the number right before where we are so this is just I times the number we're at minus the prefix sum of everything to the left of this number now on the right side it's pretty similar it's just a little bit different notice if we take six then every number to the right is going to be at least six or maybe greater so we know each absolute difference between six and some number to the right of it is going to be the bigger number to the right minus six which is smaller to get a positive result so we can write this as the bigger number at the end minus this number minus plus the second to last number minus this number all the way down to the number right after this minus the number we're at which again can be re rearranged similarly to this left side equation into the suffix sum of everything after this number to the right of it minus um multiple occurrences of this number and the math works out to nus1 - number and the math works out to nus1 - number and the math works out to nus1 - I * X is I because we have the n - 1 the I * X is I because we have the n - 1 the I * X is I because we have the n - 1 the N minus 2 all the way down to I + 1 N minus 2 all the way down to I + 1 N minus 2 all the way down to I + 1 so we take everything from one to n minus one and then we subtract I occurrences of x's I and that's a total of n minus 1 minus I * X that's a total of n minus 1 minus I * X that's a total of n minus 1 minus I * X is I now we just Loop for the left side and the right side we splited it up and we add to the result from the left side add to the result from the right side and each situation we just keep track of the prefix or suffix sum and then the result falls out for us at the end so if you enjoyed this uh please leave a like if you have any questions or comments feel free to leave a comment and I'll be happy to talk to you or answer any questions you have all right have a great day
|
Sum of Absolute Differences in a Sorted Array
|
stone-game-v
|
You are given an integer array `nums` sorted in **non-decreasing** order.
Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._
In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**).
**Example 1:**
**Input:** nums = \[2,3,5\]
**Output:** \[4,3,5\]
**Explanation:** Assuming the arrays are 0-indexed, then
result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
**Example 2:**
**Input:** nums = \[1,4,6,8,10\]
**Output:** \[24,15,13,15,21\]
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= nums[i + 1] <= 104`
|
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
|
Array,Math,Dynamic Programming,Game Theory
|
Hard
|
909,1240,1522,1617,1788,1808,2002,2156
|
1,508 |
limbs from the bi-weekly contest from limbs from the bi-weekly contest from limbs from the bi-weekly contest from lead code violently contests 30 we can discuss the first three problems in this video and then the last question is sort of DP and game theory so we will discuss this in a lecture so let's start the first three questions the first question statement states that you have to reformat the date that it is given in this format as you can see 20th October 2002 - and your output in this form in 2002 - and your output in this form in 2002 - and your output in this form in which we have to first output here then if they talk to why I have to represents it in the what is the index or what's the number of this month and the date itself okay so you have to remove this space with this - and so on so what you can here did is - and so on so what you can here did is - and so on so what you can here did is you can first take out these this date this month and this year separately store them in different strings and then therefore the and output string the first is just the year then according to that you can store this set of like this once and then see what is the index of this particular month and store that convert that number into the represent representative like month number and then because the date is consisting of the last two characteristics you can pop out these two characters and then output just the number itself but there is one thing as you can see in this sixth as you can see there is no zero so you have to check that whether if it is a single digit number you have to in like insert a 0 at the stop same it's for June is like six if you go from indexing it's just six but you want to insert a zero ID of this so take your data to the port so you can first parse out that date the date month in here I have first inserted a space at the back because every space is like separating everything which is date month in here so I have first push that at space in the end says that again iterate over from a start till the end and whenever I encountered a space I break out till then I like push back the date for month and the year okay so that's I have like pass out all the date Montaigne and then I pop out from the date last two characters it because it disputes now the string consisting of the first is the year so I first inserted here then I inserted a - and inserted here then I inserted a - and inserted here then I inserted a - and then I make this string of all the guns then I iterate over all the months and then I check the month which I have passed out which is in M whenever M is equal to MFI we have to make this two string so I use this two string function to convert this into the represented string okay but if the string length is 1 then I have to insert a 0 in the start so let's assume it is just June so it will convert it to 6 but I have to insert 0 6 so we will insert a see you in the start will leave the length of this as one if it's tens we don't have to insult you it will be gone like 0 1 so it's not true but we have done sort like it's 9 then we have to begin to unite then we will insert this month in the answers will break out then we insert another - and then we insert another - and then we insert another - and then we will do same for the date in the end if it's this size is 1 we will insert a 0 at the start and then inserted it and then it is all put on so that's the simple version - first the second person simple version - first the second person simple version - first the second person statement states that you have to find out the range some of the sorted sub-array songs so you are given an sub-array songs so you are given an sub-array songs so you are given an array and you have to take every sub arrays and then after for every sub it is some what you have to do you have to find out every sub n is some then sort out all this a very sums and then you have to do a summation from this index to diff index so like these are the sub various sums as you can see it is just 1 then 1 plus 2 it is 3 and 1 plus 2 Plus 3 is 6 1 plus 2 it's like 10 and 2 plus 3 is equal to 6 and so on so what you do for all the sub arrays you will sort them and after sorting them you have to take from the index like 1 2 index 5 take all the submissions and you output the summation so that's a simple question as you can see the length is very small so you can just iterate over all possible like sub arrays find out this sums sort them and just print down in the answer because it's very small and because the sum can exceed well as value so you have to just output with what listen to online listening because like it's also very simple just have to financial some like sub-areas have to financial some like sub-areas have to financial some like sub-areas sums so for every I starting at the sub-array starting at I equal to 0 you sub-array starting at I equal to 0 you sub-array starting at I equal to 0 you will retreat from I equal to 1 to N and find out the total so I can show you how so let's assume that you have this sub array which is like equal to 1 2 3 4 then you will take that sub array start someone so you'll do a summation for 1 then 1 + 2 3 1 + 2 + 3 6 and so on now then 1 + 2 3 1 + 2 + 3 6 and so on now then 1 + 2 3 1 + 2 + 3 6 and so on now the I will become come to here and then you take this of any sum like 2 then 3 + you take this of any sum like 2 then 3 + you take this of any sum like 2 then 3 + 5 then the sub array start from 3 then the sub arrays will be 3 & 4 and so on the sub arrays will be 3 & 4 and so on the sub arrays will be 3 & 4 and so on so that's the whole logic you will count the total sub arrays and push it in the sum vector which is long then you will sort this and the total is just your to find out the total which is just suited over all the values from left to right and just do a summation of them you can do a modulus because you have to because this can overshoot the value so you have to do a mod this ad in the top in this okay value and this return okay cool that the last question is you have to find out the minimum difference between the largest and the smallest value in three moves so you're given and nums array and you are allowed to choose one element okay nums and change it to any value you want in one so you can take this numbs vary and you can convert any of the numbers to any of the new numbers if you want you have to find out or return the minimum difference between the largest and the smallest value in the dumps so if this is num array you have to find out the smallest and largest value you have to find the smallest or the largest value after this operation so you can perform at most three moves you can perform three moves you can choose any three numbers convert them into whatever number you want and then after these operations you have to find out the minimum difference between the largest and the smallest number okay I'll tell you with this example so because what just talking about the smallest and the largest number what you can easily do here okay great you can take this number and you will take this array and then you can first sort this so after sorting you can easily know what is the maximum and the minimum numbers so as you can see if you sort them it will become like this it is zero and five so it will like zero one five ten forty so that's the whole array of the sorting now you can do at most three changes so what you will do I'll put some spacing here so as you can see like not oh yeah so as you can see this is a number zero one pile 1014 okay so now because you have to you can do at most three changes like you can change let's assume you don't change the largest number you can change like these smallest numbers because they are sorted my main aim is to bring them as close as possible and because this number which is just close because as we go from like from this number to this number the difference between these numbers are getting smaller okay this number sorry this numbers are getting bigger and a difference between these numbers will be getting smaller okay because they are like these are increasing numbers so what I can actually do here is you can also understand this with this example also because they are four numbers I can change please now if I sort them it will it become like two three four five and I can make this four five and three to two and then a difference between a smallish and I get is some of it is just zero so what I've actually done here is we have taken the smallest and a largest number and we will do the same here we'll talk about the smallest and the largest number if I can change like these all numbers to ten okay because if I change something to ten like this will be the smallest numbers like if I change them to 100 then this will go back there okay so then what will its beneficial is I can change everything to that and this is 40 so now the difference I will get is 4 okay now the other thing can be what the other thing I can do here is I can just take these two numbers if I just take to the these two numbers then I can make everything equal to five I can make them equal to five because if I make them equal to 5 then what I'm actually doing here is I'm increasing the value of this and I can make this equal to like closest to this number because these numbers are closest to each other if I make them equal to 10 if I make this equal to 10 this is equal to 5 the number will become the difference between is actually 5 so why this is happening is because I'm stretching the number which is the smallest and the greatest towards each other and when we want to stretch these numbers towards each other what we can do here is if you bring these number close to these numbers then it will get stretched to the middle and so what I am doing actually here is I have different cases I can take all three numbers from the back converted to this number and taking nothing from this last number because I have used all these three numbers and thus the difference is just this number subtract from this number otherwise I can take these numbers and this number I will change this number to this number and I will change these numbers to dismember else I will take this one number from the back and two numbers from start oh is no number from the back and three numbers from the side okay if there are four numbers or less than four numbers as you can see the answer is always zero because I will always change all the three numbers to this are the number and the answer will be this zero so if we will do only these things for when the answer is greater than equal to four greater than equal or like greater than equal to five so that is the whole trick I will tell you how you will first sort the whole nums and if n is less than equal to four answer is vo and we have to find out the minimum is just what I have told you we will take n minus like numbers of n minus 1 minus number of 3 so what I have actually done here is Celeste in that I have taken a dislike n minus one the last number so I can take the last number which means I am NOT I am just changing all these three numbers if I'm changing all these free numbers to 10 then the subtraction is between this is the index 0 1 2 3 so the third index minus the last index value then I will take the second last index value and like this value because I am choosing the first two numbers I will change them to this number so I will take this index which is 2 and I will take the second last value because I am changing the all the numbers to this value because these numbers are closest so that's the whole logic there are 4 cases so minimum is just the minimum of this case if I am taking this the last value second last value third last value and so on and we are just finding on the minimum I open s and all those three logics the next video comes next for the last question if I still have any doubts please mention now thank you watching this video as a next one keep coding
|
Range Sum of Sorted Subarray Sums
|
longest-happy-prefix
|
You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed from 1**)_, inclusive, in the new array._ Since the answer can be a huge number return it modulo `109 + 7`.
**Example 1:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 5
**Output:** 13
**Explanation:** All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
**Example 2:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 3, right = 4
**Output:** 6
**Explanation:** The given array is the same as example 1. We have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
**Example 3:**
**Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 10
**Output:** 50
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 100`
* `1 <= left <= right <= n * (n + 1) / 2`
|
Use Longest Prefix Suffix (KMP-table) or String Hashing.
|
String,Rolling Hash,String Matching,Hash Function
|
Hard
|
2326
|
300 |
hello friends today I will explain the longest increasing subsequence problem there are two classic solutions to this problem let's first see the statement even an unsorted array of integers find the length of longest increasing subsequence so for this given example the longest increasing subsequence should be two three seven one hundred and one or two five seven 101 or two three seven eight we only needed to return the lens so we only either to return this phone so let's see let me see how to solve it just imagine if for this array ended in 101 we already calculated the longest increasing subsequence from the index 0 to index and the ending here so when we add a one element in the end we add this 18 we can directly use the previous result because this is 7 is less than the 18 so the longest increasing subsequence ending in the 18th should be the longest increasing subsequence ending in 7 plus 1 so that's the reason we can use dynamic program because we can catch the longest increasing subsequence and in the previous and element in the world for the following elements we can reduce that result so let that means we can calculate the AO is which is longest increasing subsequence and in the index I start from index 0 to the length tens plus minus 1 so we calculated dice ending in the temp which is 1 then we calculate arise ending either not is still 1 and there are the longest increasing subsequence ending 2 is still 1 and when we try to calculate the error is ending in the file we know that because 2 is less than 5 so we can reduce the AO is ending in the cube plus 1 the same thing when we try to calculate the error is ending the three we can reuse our eyes and in the 2 plus 1 so every time we can save the value of the lis ending in the index I in array named deep here in the way we child tried to calculate the following elements we can compare the previous elements and the current elements and try to reuse the previous centre value so our algorithm will be we will use a DP array to save the lis and in index I and the week for every I we will use in the loop start from 0 to the I and compare this number with this number if this number is less than the numbers I we can reduce the number and every time we update our global variable max length funny we just return it so the time complexity should be unsquare so let's write the code base number Stalin's and if he will be there we use a global variable name accident the first is 0 therefore every element I listen I understand and I plus whistle ends start from the 1 because 1 elements is longest increasing subsequence Elias for the previous element starts on there jealous then IJ plus so if the numbers J's test n numbers I you can update the length let's all the TP j plus 1 so when we out to this for loop we already get to the longest increasing subsequence ending e I so DPI will be the length every time updates the max length will be master mess max and PPI so finally just to return these magnets okay and the let's see a second a solution letter change their perspective of this question we can try to generate to the AOS what does that mean for this 10 we can generate all the Allies which is just a 10 and the fold is 9 because 9 is less the antenna can now - they cannot be a o is antenna can now - they cannot be a o is antenna can now - they cannot be a o is so the Allies will still be the length of the Elias and B in the night will still be 1 but we should update this element because if we keep this 10 the possibility to generate the US will be less then we start with this node so if this number is less than the chair we can update that even though the length of the arrow is worse still you want so that means that our current a generator cannot read cheetah my ass will be nice then for this true choice dude that's the night so we just update there will be two there for the fire we can appended this file chooser arise because they can be a is right there for them three we find the weekend at these three insert history between these two elements so we just updated this file be three that's enough then for the stable we can just append it right because these great is there all the elements and for the one hundred and oh I will just append it and for the 90 we can update this will be IT 18 so the tents will also be fine so you know that's the whole idea or the core idea is true try to find us a place that's a weekend researcher this current a number so here we can use binary search that's the reason how we use binary search we turreted these numbers and a for air every numbers we will try to find a place to insert that number in our generated or a life if that a position is at the end of our generated iOS or just that's the am excellence plus one otherwise you just update that value so let's write it and it's number stall ends that would be our generic advice which is Namita DP okay and we also need a net length first is 0 then we iterate to this numbers array for every number we will try to find the index we can use the erase binary search or we can write our own binary search function that would be deep starting at zero and the index plants and fold look for the number if their index is less than zero because when we cannot find that these numbers in the in this wrench we will get a negative index minus one so the right index were just a bit mmm the return value will be negative index minus one so the writing index will be position last one and the we get it's obvious to value so we after the index will be Neptune in that's plus one and there every time updates the DP index with this number an only when their index equal to the length that it lands plus because if this index is ego to Allen's which means we should there a penny in our arise so the whole lens will increment by one finally we'll chain this length okay thank you for you see you next time
|
Longest Increasing Subsequence
|
longest-increasing-subsequence
|
Given an integer array `nums`, return _the length of the longest **strictly increasing**_ _**subsequence**_.
**Example 1:**
**Input:** nums = \[10,9,2,5,3,7,101,18\]
**Output:** 4
**Explanation:** The longest increasing subsequence is \[2,3,7,101\], therefore the length is 4.
**Example 2:**
**Input:** nums = \[0,1,0,3,2,3\]
**Output:** 4
**Example 3:**
**Input:** nums = \[7,7,7,7,7,7,7\]
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 2500`
* `-104 <= nums[i] <= 104`
**Follow up:** Can you come up with an algorithm that runs in `O(n log(n))` time complexity?
| null |
Array,Binary Search,Dynamic Programming
|
Medium
|
334,354,646,673,712,1766,2096,2234
|
383 |
in this tutorial I am going to discuss a programming question ransom note so the problem statement has given an arbitrary and some note string and another string containing letters from all the magazines we have to write a function that will return true if the ransom note can be constructed from the magazines otherwise it will return false and each letter in the magazine a string can only be used once in your and some note for example if the magazine contain this letter a we can use only one instance of a in our ransom note and if the magazine contains the two instance of a then we can use the two instance of a in your ransom note so we can't use like three letters here so only two letters are there in magazines so at most we can use two letters in the ransom note and you may assume that both string contain only lowercase letters so now let's see the example to understand this problem statement better so in the first example the magazine contain only letter B so can we construct a ransom note with letter E no we can't construct Arend some note with letter E as it is not present in the magazine so we return false in the second example the magazine contains two letters a and B and can we construct our ransom note with two letters of a is only present once in a magazine but here we are using two instances of a so we can't construct this ransom note we return false and in the third example the magazine contain a twice and B once and in the length some note we have used a twice so it's valid we can construct our ransom note with two instances of e so we return true so this is the problem statement and now let's discuss multiple approaches to solve this problem let's discuss our first approach in this problem we can construct our n sum note if and only if the word is available in magazine so what we can do is we can first traverse the magazine is train and create a map of character and it's count then we know available character and it's count and after that we can traverse this random ransom note string and check whether character is available for ransom note or not so let's see so first let stars this magazine a string and now assume this is the input so this is the input a string for magazine and R in some note so let's traverse this magazine string and create a key value pair of character and it's count and in hashmap key is always unique let's create a map of key map of character and its count and here is the code for that so what we are doing here is so we are traversing this string and we pick each character at a time so we pick first e and then we check whether this character is present in a map so if this character is present in a map give me its previous count else its default value which is 0 and then we put them in a map so we put a with count 1 and when we move to next character and again we do the same process we check whether this character is present in a map yes so its previous count is 1 let's add 1 to it and then put them in a map and so now the count is 2 and then we reach at this character and again we do the same process and we put them in a map with B and it's count now we know all the character and its count present in a magazine so the next step is to traverse this ransom note string and check whether the character is present in a map and if its present whether its count is greater than 0 if it is not greater than 0 or if it is not present in a map it means we can't construct this ransom note and we return false so I am traversing this string and so let's say the first character is e then we have check here is this character is this map contains this key yes and is this map I mean the value corresponding to this key is greater than equal to zero if any of these condition is fail then return false else what we can do is we can take this take the value of this character and subtract it with one so we decrement its value so now the new value is 1 and now the next character is e again this condition fails and so we skip this condition and we reach at this statement and we pick its value so and we decremented it and put them back in a map so after that we came out of this loop and we return true as we can construct this ransom note from the characters available in a magazine so this is the one way to solve this problem and now let's talk about its time and space complexity now suppose if we consider the length of ransom note as n and the length of magazine is M so it's time complexity is n plus m and what about its space complexity it's a space complexity is Om we are using extra space in the form of hash map and we are putting all the character and its count of magazine in this hash map so the time complexity is n plus M and it's the space complexity is Om now let's see our next approach in which we solve this problem in constant space in our previous approach we have solved this problem by using hash map so we can solve this problem by using fixed size array so we are only using lowercase letters so we can are take a fixed size array of length 26 and based on the s key value we reach at that index and increment its count and when we draw us this ransom note a string we check whether the value is present at that index and is it greater than 0 if it is then we can construct this ransom note so let's see how so we have declared an array of length 26 so its indexes are from is from zero to 25 and then what we can do is we can traverse this magazine a string and so the s key value of a is 97 and the S key value of B is 98 and it goes up to 122 so what we can do is we have declared an area of size 26 so the S key value of a is 97 and if we subtract it from 97 it means we have to go at 0th index and the initial value at this index is 0 so we have incremented to 1 so we have used here primitive type so whenever we declare anything of primitive type their default value their initial value is 0 so initial value at each indexes is 0 and then similarly the next character is a so again let's increment its value and the next character is B so the S key value of B is 98 and if we subtract 97 we reach at first index and increment its count so now we are done with this is with this string magazine so we came out of this loop and the next step is to traverse this ransom note string and when we traverse this ransom note strings so the first character is e so we go at that index first we decrement its value and we check whether after decrement after documenting its value whether it is less than 0 if it is less than 0 it means this character is not available for constructing a ransom note and if it is greater than equal to 0 it means this character is available for constructing our ransom note so it is greater than equal to 0 so we can use this character to construct our in some node then we move to next character and it as a and we decrement its value and then we check whether it is less than 0 or greater than 0 so whether it is less than 0 no so we don't have to return false and in any case if it is less than zero now suppose instead of a the character is C so the SQ value of C is 99 and we when we subtract 97 we reach at 2nd index so the default value present here is 0 and when we decrement its value it is minus 1 and then when we check this condition whether it is less than 0 yes in that case we return false it as this character is not available in magazine to construct an ransom note but this is not the case here is a so yes this character is available for constructing a ransom note and after the complete traversal we came out of this loop and we return true now again let's talk about its time and space complexity so if the length has n and the length of this string is M so time complexity is n plus M and what about accessories complexity so it's a space complexity so we are using constant a space so it's a space complexity is o 1 so this space does not vary with the input length so that's why we are saying this is the we are using constant space so that's it for this video tutorial for more such programing video tutorials you can subscribe our YouTube channel you can visit our website which is HTTP colon slash web rewrite com thanks for watching in this video and please don't forget to like this video
|
Ransom Note
|
ransom-note
|
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_.
Each letter in `magazine` can only be used once in `ransomNote`.
**Example 1:**
**Input:** ransomNote = "a", magazine = "b"
**Output:** false
**Example 2:**
**Input:** ransomNote = "aa", magazine = "ab"
**Output:** false
**Example 3:**
**Input:** ransomNote = "aa", magazine = "aab"
**Output:** true
**Constraints:**
* `1 <= ransomNote.length, magazine.length <= 105`
* `ransomNote` and `magazine` consist of lowercase English letters.
| null |
Hash Table,String,Counting
|
Easy
|
691
|
53 |
question 53 of elite code maximum subarray given an integer array nums find the contiguous subarray containing at least one number which has the largest sum and return its sum a sub array is a contiguous part of an array okay so in the example here we have a nums array which is just an array full of integers and our output is 6 because we have a sub array here which equals 6 so that's the maximum sub rate within this nums array and contiguous here that just means that these numbers follow one after the other so let's work out a way to solve this so because it's asking for an optimal number maximum this should lead us to think of a dp solution so dp uses the smallest possible solution to carry out a larger solution to carry a larger solution until you have completed the nums array and you have found your answer so let's work through a dp solution so in order to work out the total maximum we need to work out the current maximum so we need to work out the maximum from this point so let's call this dp array we have here let's call this current max okay now what is the maximum value at nums at zero index well it's minus two right so the maximum at this point is also minus two if we move on to the next position the current max here can either be one or it could be one plus minus two because we're using this value to help computate this value so in this case it's going to be one right because that's going to be greater and we're working out the max here and minus two plus one so here the maximum will be updated to one then we move along we have minus three here so we can use minus three as the maximum or we can use one plus minus three as the maximum so we'll use one plus minus three which is minus two and as you can see a trend is growing here we look at the maximum here the maximum between one and minus two is one so we leave that the same but there is a trend and that is the recurrence relation of this dp program so current max is going to be equal to maximum between number i or current max plus num to i so current max and this will then be used to computate the rest of the current maxes and as you can see we're going to be updating the max as we go along and then we'll be able to return the maximum so let's just fill in the rest so at this point we have a maximum between four and four plus minus two so it's going to be four so we can update the max here that'd be four moving along we've got minus one so the maximum between minus one and minus one plus four is three here we don't need to update the maximum so we move along at this point we have a maximum between two and two plus three so that is going to become five we update the max here five at this point we have a maximum between one and one plus five so it's going to be six maximum is updated again to six at this point we have minus five or minus five plus six so that's going to be one and at this point we have a maximum between four or four plus one so that's going to be five so the maximum didn't update on the last two and then we can just return this value which is what we're looking for so in terms of time complexity this is going to be of n because we're looping through the nums array once so n is the integers within the nums array and we're going to be doing this in place so space complexity is going to be one okay so let's start off this uh dynamic programming solution so we said that we'd have a current max variable right and that's going to be initially set at nums at zero and then we're going to have a maxima variable which is going to also be set at nums at zero so we're going to loop through nums starting from one and the reason for this is because we already set this value here so this is the initial value which we have set so we don't need to loop through that okay i is less than nums.length i is less than nums.length i is less than nums.length i plus then we just need to update current max and maximum and current max is going to be the recursive relation within this dynamic programming solution so it's going to be the maximum between number i and current max plus number i and then we just need to update the maxima which is going to be equal to the maximum between maxima and current max and then we can just return maxima and give this a go so it's been accepted let's submit it okay great
|
Maximum Subarray
|
maximum-subarray
|
Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_.
**Example 1:**
**Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\]
**Output:** 6
**Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** The subarray \[1\] has the largest sum 1.
**Example 3:**
**Input:** nums = \[5,4,-1,7,8\]
**Output:** 23
**Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23.
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
| null |
Array,Divide and Conquer,Dynamic Programming
|
Easy
|
121,152,697,1020,1849,1893
|
489 |
A decoction from here, people have cleared the robot in the room, model is cigarette, tried to destroy cancer, visit channel, subscribe Kundan Avatar movie robot and you can make robot left and their make turn right and left hand free leg, but on this picture recovery let's move left or right and also given point robot 90s mein subscribe to main to kal doctor problems during sunrise from the top left corner its position in the right hello and good night ok but that's why they are in price movie The Box Album Sensitive And Finally Topic Not Going To The 0.5 Want The Life In A Room Using Only 0.5 Want The Life In A Room Using Only 0.5 Want The Life In A Room Using Only For 1000 Cotton Fabric And Robot 2 Hai Tu So Algorithm How Can Visit Channel Death Sentence For Investigation Will Write To Movies Using left and right direction is that till now crush in all directions or irresponsible only from late 113 cigarettes of Bihar cigarettes are already there one hair 0share one hair Baalveer 111 from haze downwards Prabh Gill from one point robot Dr AI Well Guess What Will You Marry Me To Start And They Started Acting Like Men Water When You Remember Them's Problem What's The Meaning Of This Country Is The First Movie Welcome Back Movie Left Side Welcome Back Movie Far Away From The Loot Now the downward trend, this is a trident, the donkey returned of the day, the state head Vikrant was the moving website, the right side is also a happy option, here too is tight and the option is town hall midnight, then first Guddu and width, I medium debited the like button, subscribe this All The Amazing subscribe to hua tha a text so assigned year old in one direction left or right direction in this evening all roads infrastructure in the right direction and come back and tribes in all directions of doctors in life in the The subscribe The Channel Please subscribe and subscribe the Channel You can recommend quality action from Hussain Polytechnic in one should not be any person who has not like and subscribe kar do hai f4 later behavior function is visit with sacrifice celebrity not having lots of etc. Ajay Devgan Provident Twenty20 International Nahi Aa Aadharwise Special Market And Visit Right Monday Visit Main Aarti Sunao Or Pimple Episode Se 200 For The Calling Function Adi Plus Wave Flash Light AR - 110 CC AR - 110 CC AR - 110 CC AR - Aarti - One And Plus One C Right AR - Aarti - One And Plus One C Right AR - Aarti - One And Plus One C Right A Good Wishes For Calling Function Ya Phir Kashmir And Only When Lord Of Rs.1 Is Equal To A Main Of Rs.1 Is Equal To A Main Of Rs.1 Is Equal To A Main Tujhe Sanj Reasonable Album Account Statement Is Condition For More Than CR Saying That Lets You Are You Should Not Going On That You have lots of boundary right hand side problem solved successful very auspicious loop and definition of bus lab attendant - 121 definition of bus lab attendant - 121 definition of bus lab attendant - 121 flash lights 80 plus one should be left and right and withdraw cases frend2001 turn it on then same thing applies for health word left side change 28 October The Top Samsung Price At The Bottom The Condition Loot Shabd The Hai To Issue Max Return Janapada Vitamin Govardhan Right Hand Was Turning Bluetooth Raghavendra Gautam Nice Looking Nice Pravesh Or Right In Front Of Subscribe Our Channel Please Subscribe Our And Play N Album Tarf Hua Thee Illusion To Consider All The Four Cell Death Was Tried And Tried Again Play The Song Of The Problem Subscribe And Note Se Paun Inch And Waste Oil To This Vagina And Visiting XL 100 Times Micro Posted By The Lord And 102 Others Like this trap
|
Robot Room Cleaner
|
kth-smallest-instructions
|
You are controlling a robot that is located somewhere in a room. The room is modeled as an `m x n` binary grid where `0` represents a wall and `1` represents an empty slot.
The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API `Robot`.
You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is `90` degrees.
When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.
Design an algorithm to clean the entire room using the following APIs:
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
**Note** that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.
**Custom testing:**
The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded ". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.
**Example 1:**
**Input:** room = \[\[1,1,1,1,1,0,1,1\],\[1,1,1,1,1,0,1,1\],\[1,0,1,1,1,1,1,1\],\[0,0,0,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\]\], row = 1, col = 3
**Output:** Robot cleaned all rooms.
**Explanation:** All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
**Example 2:**
**Input:** room = \[\[1\]\], row = 0, col = 0
**Output:** Robot cleaned all rooms.
**Constraints:**
* `m == room.length`
* `n == room[i].length`
* `1 <= m <= 100`
* `1 <= n <= 200`
* `room[i][j]` is either `0` or `1`.
* `0 <= row < m`
* `0 <= col < n`
* `room[row][col] == 1`
* All the empty cells can be visited from the starting position.
|
There are nCr(row + column, row) possible instructions to reach (row, column). Try building the instructions one step at a time. How many instructions start with "H", and how does this compare with k?
|
Array,Math,Dynamic Programming,Combinatorics
|
Hard
| null |
1,448 |
hello everyone welcome back to lead coding today we are solving the problem called good note in a binary tree so we are given a binary tree and we have to return the number of good nodes in that tree so how do we classify your node to be a good node so a node is considered as good if it has the maximum value among all the nodes which comes in the path from the root till that node for more clarity let us have this example in this example we see that the root node is obviously a good node then if we have this 4 so all the nodes which come in the path are 3 and then 4 so 4 is maximum so this is also good node then again 5 so this is the path 3 4 & 5 & 5 again 5 so this is the path 3 4 & 5 & 5 again 5 so this is the path 3 4 & 5 & 5 is the maximum among all these nodes so 5 is also a good node if we come to 1 so if we come to 1 the path is 3 4 & 1 in this path the path is 3 4 & 1 in this path the path is 3 4 & 1 in this path the maximum is 4 and not fund so this is not a good note similarly this one is also not a good note but this 3 is a good node as the path is 3 1 & 3 & 3 is the node as the path is 3 1 & 3 & 3 is the node as the path is 3 1 & 3 & 3 is the maximum in this path so there are total 4 good nodes in this entire tree so we can solve this problem using any of the DFS traverses so if we if you maintain a variable maximum so this can help us maintaining the maximum in the entire path so using any DFS approach with this maximum variable will help us solve this problem in Big O of n time let us see how to implement this all right so here we are having let us say our DFS function a DFS we have three node root and the maximum if not root then return zero if the value of the root if this is greater than or equals to the maximum till now then we have to increment our answer plus also could be a global variable as well but we are not going to do that we are going to return the answer so answer is zero also if the value is greater than or equals to M we are going to update M is equals to roots value now we can return answer plus the CEO function to the left side with him plus the FS same function to the right side so this should return was the answer DFS root and here we are going to pass incoming for three and one so it is giving us the correct answer we are able to solve this problem in Big O of n if you liked the video please subscribe to the channel and share the video
|
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 |
219 |
okay let's talk about contains duplicates here so in this question you are supposed to uh supposed to understand the hash map is the easy way and the hashmap should be uh you are sorting the value which is numsai and key for numsai value for index and you traverse every single l in array and if you find the key inside the map you will just follow the constraint if this is satisfied then just written true and i will just add this every number into the map at the end of the folder so this is pretty straightforward let's talk about using a hash set so in cash set you are doing almost exactly the same thing but there should be a slightly different so let's just go set and okay let's see so uh you need to satisfy this constraint right so basically it's two pointer one is i the other one is k but only like only um store the value in between i and j and not including k so what do you mean so i would say um whatever i add i will find first off if i burn the kit if i go in okay i will remove the element from one set right so i minus k and minus one because the index five so uh i need to add right so i is a boolean function so how do i make it too false if uh if the value is not in the between so if there's no duplicate in between how do i do it so i would just use the uh opposite so add the num set i and we can choose so in this if statement it will basically mean like if there is a duplicate in between i and k which not including the k position i will return true but if there is not duplicate and i would just keep going but i would still add a value into the set so in this example is definitely return both because when k equal to 01 to 3 so 3 is greater than k right so 3 is greater than 2 in this example so i would just make sure i would delete the value at index 0 3 minus 2 minus 1 right then i'll just re-add the value into it then i'll just re-add the value into it then i'll just re-add the value into it and i will just uh just keep moving okay so the idea is pretty straightforward it's two-pointer and this is pretty hard it's two-pointer and this is pretty hard it's two-pointer and this is pretty hard to understand but uh it turns out it's easy uh when you look at this example so it's ex so these guys uh this guy explained pretty well so just look over so it iterates over the array using a sliding window the front of the window is at eye the rear of the window is case step backs the element within the windows are maintained using set so basically it's just what i say right so you should be fine and the time and space you just all the time right you store the value into a set and then you traverse every single element so that would be simple and easy thank goodness
|
Contains Duplicate II
|
contains-duplicate-ii
|
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105`
| null |
Array,Hash Table,Sliding Window
|
Easy
|
217,220
|
36 |
hi friends welcome back today we are going to solve one very famous and popular coding interval question asked by amazon google microsoft facebook and many other companies it's on lead code 36 valid sudoku so as you can see from the like dislike ratio this is quite popular coding problem uh in the interviews as well so we will implement this uh problem using java in today's session we will discuss how we can solve the valid sudoku problem uh along with some examples so you will clearly understand uh you know how to the logic and the java solution to solve this problem in today's session before we start looking into the problem details along with some examples and java code i want to mention that this channel is to help people in their coding and java interviews on this channel you will find lots of helpful videos that can help you in your coding as well as java interview preparation for example there are more than 400 different varieties of coding problems solved and explained many of those problems are previously asked coding questions by google facebook amazon apple microsoft yahoo lift linkedin uber netflix and many others you will find all important coding questions varieties in those solved problems including breadth first search depth first search graph problems binary search tree problems coding questions related to binary search linked list strings optimization problems using priority queues dynamic programming questions as well as lots of logical problems so if you are preparing for any coding rounds of interviews or java rounds of interviews or you simply want to learn different concepts along with java programming and problem solving then this channel can definitely help you in doing so please subscribe to this channel now also whenever we come across any important and interesting coding problems such as this one we create videos to share our logic approach and the java solutions with others so they can also learn by watching those videos so make sure you click on the bell notification icon so you always get immediate notifications for all our upcoming interesting videos so let's start with this leadport 3036 valid sudoku determine if a 9x9 sudoku board is valid only the field cells need to be validated according to the following rules each row must contain the digits 1 to 9 without repetition each column must contain the digits 1 tonight without repetition each of the nine three by three sub boxes of the grid must contain the digits one to nine without repetition note a sudoku board partially filled could be a valid but is not necessarily solvable only the field cells need to be validated according to the mentioned rules so this is what the problem statement says they have given us one nice this example of sudoku bold so we will go there let's take a look at the constraints so the board dot length is 9 so total rows are 9 total columns are 9 and the i j is digit 1 to 9 or dot is basically empty uh empty thing right like as you can see empty cell so to understand this problem more we can go and take a look at this first example right on the white board so this is the first example i just took it from there so uh if you look at this matrix right this is a nine by nine matrix right and this is a valid sudoku board ah so what is a valid sudoku board basically we will understand this so basically what they are saying is each row like this row or this row any row right here and every row actually right every row they have all unique numbers right you can see 5 3 six one nine five nine eight six any row you take any row you will see unique numbers four one nine five here eight seven nine right so every row has a unique numbers similarly if you take any columns also every column has unique number here 5 6 4 7 8 if you go here 3 9 6 if you go here 8 if you go here 1 8 4 if you go here 7 9 6 2 1 8 so every row and every column has a unique numbers right that is the first requirement we should not get anything repeated if you have a repeated number it cannot be a valid sudoku correct so that is what the rules say now apart from that there is one other rule here right to be a valid sudoku what that rule says is there are sub grids here sub grids of size 3 by 3 right so let us read that here right 3 by 3 sub boxes of the grid must contain digits 1 to 9 without repetition so where are those sub boxes here so they have shown a sub boxes in this like a bold black color right i'll just make it red for you so this is a sub box of three by three matrix right this is one sub box this one is another sub box right this one is another sub box then this is all our three by three grids basically correct you can see it now right these are the sub boxes similarly you can go here these are this is also another sub box of three by three this is another sub box of three by three and this is another sub box are three by three right so these are all uh sub boxes of three by three size right and these are other three so total you can see that there are nine such a sub boxes here right nine such a sub boxes correct uh so what they are saying is in each of the sub box the number should be unique if you see these sub boxes you will not see anything repeated there right 3 5 6 8 9 nothing is repeated 4 7 8 nothing repeated 6 nothing repeated 3 2 3 6 8 nothing repeated 1 5 7 9 no repetitions 1 4 9 8 no repetition 5 7 9 2 8 no repetition 1 3 6 no repetition and 6 no repetition so how i have to evaluate all these sub boxes of size 3 by 3 right and we have to make sure that there is no repetition there if there is no repetition in every column and every row then it is a valid sudoku that is what the logic is to find out if it's a valid sudoku or not now see the finding each row has a unique number it's very easy basically right and each column has a unique number this is also very easy finding that right because the size is just nine by nine basically correct so size is just nine by nine let's take a look one more time to the constant c so it is not variable it is just always nine by nine size right so finding every row has a unique number and every column has a unique number is very easy how will we find out if this three by three sub groups have unique numbers right that is the question uh to solve now so how will we identify those so i will show you how to identify those so basically if you just look at this matrix now as instead of 9 by 9 you can consider it as a three by three matrix so if it is three by three matrix ah for the size of sub groups right sub boxes we will consider it so this is zeroth row this is first row this is second column right zero column first column second column basically right where the row is actually contains three rows right each row contains three rows each column contains three columns here right now correct so this is how we will solve that so we have to now identify uh so now if we look at a cell right how will we identify which subgroup that belongs so we will need two things to identify sub group right we need the which row is that and which column is that right so for example if you look at this one right if you look at this one this is the 0th row and 0th column right 0th row and 0th column for the by three sub groups or sub boxes we are talking about now right so this is zero through zero column correct now instead of that if you go here and if you look at this is a first row and first column basically first row and first column correct for the sub group okay subgroup we are talking about each subgroup is of size three by three okay so now this is first row and first column correct so but how we will identify this now so i will show you now so let us consider this cell now right this cell so which in reality which row is that 0 1 2 3 third row right this is third row and which column is this 0 1 2 3 4 right no 0 1 2 3 4 column right third row and fourth column so we will divide this by 3 so if you divide this by 3 it will tell you which row is that and which column is that right so now this is first row basically and first column correct so that is how we will identify which subgroup is that one correct if you go here if you take this cell right if you take this cell which row is this third row i'll write down here third row correct uh same row right and column is eighth column correct eighth column again if you divide this by three it will tell you which subgroup is that how we will know now this is first row and second column correct if you look at it this is first row and second column correct so this is how you can recognize which uh which group which sub group that sale belongs to right if you go here which one is this let us see so now uh this one is a sixth row right sixth row and this one is seventh column so we'll again divide it by 3 if you divide it by 3 you will get the sub group rows position so this is 2 comma 2 second row and second column for the sub group we are talking about sub group clear okay so now this is how we will recognize which subgroup that belongs and once we recognize which subgroup that belongs then we will create a map right like this it will look like that i shown you on this right side this is how our map will look like this is subgroups that i am showing you correct so now uh you understood how to calculate the subgroup right so i will remove these colors so now i will show you how actually once you create a map how the map will look like correct so let us see how the map look like so if you go to this zero comma zero sub group we will map it into the map like this so this is the subgroup right zero comma zero and it will hold these cells right three five six eight nine if you look at this one three five six eight nine all the cells we have captured in the map this is a map right for sub groups this is a map right and the key is this zero comma zero is the key in the map right so it is basically how we will map this actually as a key we will use a link list right we will use a list there as the key right and list will have two values the row and column right that's how we will identify which subgroup or which sub box is that okay so now you saw this now if you take a look at 0 comma 1 you can go to 0 comma 1 here this is 0 comma 1 it is 1 5 7 9 you can look here 1 5 7 9 correct so you are following it right now 1 comma 1 let's go to 1 comma 1 this is 1 comma 1 what is this 2 3 6 8 so 2 3 6 8 you are following it right now let's go to 2 comma 2 so this is 2 comma 2 right what is this now here 2 5 7 8 9 two five seven eight nine right so this is how we will capture all our uh sub boxes we will call that as a sub boxes here right some boxes which is essentially sub groups right sub boxes and this each sub box size is 3 by 3 right that is given to us in the problem itself and since it is a map this is a map we can easily identify if we are getting any repeated thing right because this one is actually a set this one is set so we can easily tell if it is anything gets repeated we will immediately identify if we have something repeated it's not a valid sudoku correct so now you understood the complete logic so i will show you the java code now so it's not that difficult to solve this problem once you understood the logic right so now uh let's go back to our code and we'll see the code how we will implement it in java this one so this is our code for the valid sudoku so we have created this is our is valid sudoku method is there will return true or false and they give us a bold right which is a character 2d array now what we are doing first thing here is we are creating three maps so first we will look here right so this is first thing we will look like this is a column map right it will give us the column which is zero to eight columns are there right the key is integer and we will use hash set of characters right and same thing we will do for a row map also row map is there column map is there so this one is pretty straightforward and easy right now this one is a sub boxes map that i shown you right now this is the key is a list of integer here because we need two things to identify right for example if you go here we need the sorry if you go here right you need column sorry row and column right row and column two things you need so that's why we will use a list here right list so now uh this is the list is the key and the value is again the hash set of characters right so now you understood this so far so now we will go uh in the two for loops right we are traversing through the matrix or through the grid right through the grid so zero to nine because nine by nine size is there of the bold it's a fixed size board bolt right so we will keep reading each character now the current value here we have read i j value from bold into the current value right now grid index is the one that list i was talking about this list i just showed you two comma two list so this one we have to calculate now for each cell right so we are calculating that for each cell here right grid index dot add i divided by 3 will give us row correct so this will give us row of the sub box right sub box this one is important right row of sub box and this one will give us column of sub box right of the sub box so now we got column and row just by dividing by 3 and we stored that into our grid index list right now we will check if this current value is dot then we will simply continue right dot means it is an empty cell then we don't have to do anything correct now if it is not a dot then we will check if it is a valid sudoku or not right that value should be valid sudoku what we will check in this valid sudoku thing we will check that the column like this column should not have this repeated value the row should not have the repeated value and the sub box should not have a repeated value three things we have to check basically correct so now first thing we are checking it here is the column should not have the repeating value so we are checking it here if column has the repeating value because call map dot gate j will give us set and we'll check in the set if it contains current value it is basically repeating will return false otherwise we will keep checking so column is fine then we will check into row right if this row has that value repeating how we will check row dot get i will give us the hash set and if set contains the current value it means that it is repeated repeating right will return false now this both things are okay then we have to now still make sure that the sub boxes also should not get the repeated value right so this is what we will check now so how we will check sub boxes of grid index so grid index is the list because for sub box map the key is the list of integers remember it is a list of integer is the key here right so this key that's why we have created this grid index key here right now we will use that key and we will check into our sub boxes map if that key uh we'll get a so sub boxes map dot get grade index will give us the set right set it will give us so we'll check into this set if it contains current value it means that it is repeating right will return false if nothing is repeating we are good then we will add those values into the corresponding column row and the sub group map right sub boxes map so let us go through this logic so now nothing is repeating everything is good so we'll go and add this into column so call map dot get like contains j means it's already existing column then we will just add into the column if it's column is not there then we will have to first create that blank like a new hash set and then we will add that value correct first time this is first time for that column right here same thing if the row already is there available then we'll just go ahead and add this value into that row set right if the row set is not yet created like for the example first time right then you will create that hash set and then you will add the value into the hash set here right now we have added for column we have added for row now we have to still add for sub boxes right so now we will again do the same thing if sub boxes has already created for that uh group grid index id right grid index then we will just add it into the grid index the current value if it's not already created we will have to create a new hash set first correct we will create a new hash set here and then we will add the current value into that grid sub box basically right sub box we are adding so clear right so this is where you will keep looping into this for loop right will keep each and every cell and will make sure that each and every cell the row is valid the columns are valid and the sub boxes are valid if everything is valid and we reach here we will return true if something is not valid we will actually reach here and just return false right so this is the logic uh to solve the valid sudoku problem one very important coding for questions asked by amazon facebook google and many other companies so make sure you practice this problem if you are planning for any coding interviews these are frequently asked coding problems so we are now going to test this code right so we are let us talk quickly about what is the times complexity so we are going to go through all these uh two for loops right so nine into nine so you are fixed size 81 times you will go right maximum 81 times you will go the size does not change right so always you will go maximum 81 times in these two for loops other thing is now if you talk about the space then you have like uh three maps here right so nine uh is the column map nine is the row map size maximum and sub boxes uh the maximum will be total number of elements in this map will be nine elements right total maximum correct as you can see these are nine right count it one two three four five six seven eight nine right always maximum 9 elements so um you can just say that it's kind of a 9 plus 9 so you can say 27 order of 27 is the space complexity here because you have used this map this size is not going to change correct so that's what you can explain in the interview size is maximum that much and these two for loops maximum times it can execute is 81 right nine into nine so this is how you can explain the time complexity and the space complexity for this code i hope it is clear to you now um uh so this is the way uh our valid soda solution will work so let us test this code with some test cases make sure it works so this is the first one is true we are getting correct answer let's try with the second test case this is the second test case right let's remove the first one this is the second test case now it should give us false we are getting correct answer uh let us take the first one we will just do a small modification and make it false so now as you can see first row has 7 here if we make a 7 here then it will get repeated so it should return false so we are getting false which is the correct answer we can just go ahead and submit this code to the lead code make sure it gets accepted by the code lead code so the code got accepted by the lead code it is 58 percent faster than the other submissions which are done online uh and 81 percent faster on the memory usage which is a pretty good solution for this valid sudoku problem so i hope you completely understand this important coding problems one very popular coding interview question uh by many big tech companies um if you are new to this channel has a dedicated playlist for lead code and lean code problems and solutions that playlist has more than 250 different varieties of coding problems solved and explained for your easier understanding they come with examples and java code is always shared through github repository you will find the java solution code link available in the video descriptions where you can go and check out the java code play with the java code with different test cases for your better understanding of the code you will find all different varieties of coding problems in those playlists solved and explained many of those problems are frequently asked coding questions by big tech companies including google facebook amazon apple microsoft yahoo lift linkedin uber netflix and many others apart from that if you still want to practice more coding problems on this channel there are three other playlists you can check the names are code forces code chef and add coder all and all you will get more than 400 different coding varieties of problems you can use for your coding interview preparation as well as for your in-person interview preparation as well in-person interview preparation as well in-person interview preparation as well if you like this video if you find this video helpful if you like the way the video is created with this white boarding session examples and java code and explanation then please give it a thumbs up to the video give it a like to the video subscribe to the channel your subscription is very important for the channel because that is the way the videos can reach to more people who need help in solving coding problems some people find it difficult to solve different coding problems through this channel we would like to help them by showing them how different coding problems can be solved using java programming language using different data structures algorithms so they can also learn by watching these videos how to solve different varieties of problems so if you like this video give it a like share it as much as you can with your friends and colleagues they can also watch these videos they can also learn from these videos something new something more about problem solving programming and data structures if you like the videos on this channel if the videos on this channel are helping you learning something new uh something new about java programming language data structures algorithms and problem solving and logic building then write into the comments below the description section comment on these videos and tell us about it how the videos are helping you that motivates us to create more such good quality content for others so let us know how the videos are helping you in your interview preparation process as well as in your learning process whenever we come across any interesting and important questions like this one we create videos and post it on this channel so that we can help others also i'd like understanding how to approach and solve different coding problems using java so make sure you click on the bell notification icon so you always get notifications for all our upcoming videos keep coding keep learning keep solving different problems and thanks for watching this video
|
Valid Sudoku
|
valid-sudoku
|
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:
1. Each row must contain the digits `1-9` without repetition.
2. Each column must contain the digits `1-9` without repetition.
3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition.
**Note:**
* A Sudoku board (partially filled) could be valid but is not necessarily solvable.
* Only the filled cells need to be validated according to the mentioned rules.
**Example 1:**
**Input:** board =
\[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** true
**Example 2:**
**Input:** board =
\[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\]
,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\]
,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\]
,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\]
,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\]
,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\]
,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\]
,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\]
,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** false
**Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit `1-9` or `'.'`.
| null |
Array,Hash Table,Matrix
|
Medium
|
37,2254
|
1,402 |
hey everyone welcome to Tech quiet in this video we are going to solve problem number 1402 reducing dishes first we will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I've taken the first example from the Lego website so in this problem we are given an input array of satisfaction level right of n dishes and we need to maximize the sum of lifetime coefficient value right so to maximize this I can prepare my dishes in any order and also I can get rid of some dishes to maximize the lifetime coefficient right so in order to get the maximum sum I'm going to sort the input array in decreasing order right this will ensure that I will have this maximum satisfaction level value at the front right so if I sort this input array I will get 5 0 negative 1 negative 8 and negative 9 right so here I have this sorted input array so by looking at this we can see that we have the maximum satisfaction level a particular dish that gives right so we need to prepare this dish in order to increase the satisfaction level so then I will be having two variables one is result and one is prefix some variable both will be initialized as 0 at the start so initially I will pick the first value that is 5 here I will add 5 to my prefix sum now I'm going to maximize right so before adding prefix sum to my result variable I need to check whether this particular prefix sum is going to contribute positively or not right that is the after adding the I the dish whether I am going to maximize the result or not that's what we are doing here so here it is not negative so I'm going to add prefix sum to my result so my result will become finer then I will move my eye pointer I will pick the next dish satisfaction level that is zero so I will add 0 to my prefix sum it is going to be 5 again so I'm going to check is my prefix sum is less than zero or not that is it is negative or not no it is positive again I will just add the prefix sum to my current result variable now result becomes 10. now I will again move my eye pointer so in here negative 1 is the satisfaction level of the dish right here in this case it is the third dish right so that's a satisfaction level of the third dish is minus one that is what minus 1 refers to right now I will add minus to my prefix sum so my prefix sum becomes 4 now so now I need to check whether after adding the I the dish that is negative 1 is my prefix sum that's the overall satisfaction level has been reduced negatively or not no it is not negative right so I will just add prefix sum to the result variable now result becomes 14. now I will pick the next satisfaction level right that is negative 8. now I will again add 8 to the prefix sum now prefix sum becomes negative 4. which means if I add this to my result my total maximum satisfaction level is going to reduce right that is it is going to contribute negative to this situation so whenever my prefix becomes negative I will just break out of the loop I can ignore rest of the dishes and finally I will return the maximum result right that is 14 in this case so that's all the logic here so the time complexity is n log n since we are sorting and space will be order of 1 since we are not using any space right so now we will see the code so before we go if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I will sort my input array in decreasing order right so here in Python I'm putting reverse is equal to true right then I will be taking the length of the input array right then I will be having prism and result both will be 0 at the start then I will iterate through the input array right first I will add prism to my current satisfaction level then I will check is my prism is negative or not if it is negative then that particular eighth dish is going to contribute negative to the situation so I need to ignore that in that case I will just break out of the low else I will just keep on adding the prism to my result variable then finally I will return my result video right I think it's fine let's run the code as you can see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
|
Reducing Dishes
|
count-square-submatrices-with-all-ones
|
A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time.
**Like-time coefficient** of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i] * satisfaction[i]`.
Return _the maximum sum of **like-time coefficient** that the chef can obtain after dishes preparation_.
Dishes can be prepared in **any** order and the chef can discard some dishes to get this maximum value.
**Example 1:**
**Input:** satisfaction = \[-1,-8,0,5,-9\]
**Output:** 14
**Explanation:** After Removing the second and last dish, the maximum total **like-time coefficient** will be equal to (-1\*1 + 0\*2 + 5\*3 = 14).
Each dish is prepared in one unit of time.
**Example 2:**
**Input:** satisfaction = \[4,3,2\]
**Output:** 20
**Explanation:** Dishes can be prepared in any order, (2\*1 + 3\*2 + 4\*3 = 20)
**Example 3:**
**Input:** satisfaction = \[-1,-4,-5\]
**Output:** 0
**Explanation:** People do not like the dishes. No dish is prepared.
**Constraints:**
* `n == satisfaction.length`
* `1 <= n <= 500`
* `-1000 <= satisfaction[i] <= 1000`
|
Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0). Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.
|
Array,Dynamic Programming,Matrix
|
Medium
|
2192,2193
|
140 |
okay so I'm gonna talk about 140 would break - which is a follow up a to 139 break - which is a follow up a to 139 break - which is a follow up a to 139 would break I did a video about a 100 students I a few weeks ago check out the link over there so let's quickly summarizes of what this two questions are asking we have an input string s and dictionary of words what we need to do is to shutter the string s into little pieces where each little piece is a word in the dictionary and those pieces are continuous chunk off for the input string s so for 139 it's a feasibility question so we're just determining whether it's true or false that we can do so you can see that as long as so we can find a way of doing that we can return true before 140 we need to return all the possible ways of segmenting the input string into different words with empty space part in between so let's look at an example we have cats and dog and the dictionary words cat cats and the sand so you can see that depends on whether you want to put s to the end of cat or beginning of end you have multiple ways of doing the segmentation so the result is list of two ways of doing the segmentation so as real reward interview kind of settings you code up the solution to 109 then after the fill up is given there should be just some modification to the code to have that work with 114 so I'm just gonna do that today it just quickly summarizes the solution to 139 there's a the solution that I coded up as deep the dynamic programming solution basically we have a DB table which is one theory because think of this as a function can break I which just tells us can we break s from the beginning towards the ice location was that I be inclusive so if we look at the third you know what's this number of three look at the Swedes entry in there that was capped so it tells us that yes cod is valued a word in the dictionary so in the end we just want to grab the rail last night and that tells us and whether we can break the full sentence from the beginning towards the end and the code is for every location in the array that we doing a linear scan from left to right we look back to see the previous breakable points and check the stuff that's in between the current point and the last applicable point if the stuff in between is a valid word then we can build upon the previous you know break post solution and just have that new word added to that solution that makes the current location to be breakable so that's pretty much the code here I do have a correction to make last time I said this solution is gonna be a square time but I think it's it should be cubic time on second thought the reason being that the string slicing here in Python creates a copy so in the worst case the last location last the breakable point is the zeros index where you know and this space is always pretty ball by empty space and the current location which can be the very last location in the sentence so making a copy of the full string in the worst case you know takes on earth and also you know computing a hash from the string of lands and you shouldn't really treat that as a constant I guess so but just um but that a spring slice alone is gonna increment at the time to be cubic time so I just have a quick you know question to make about that so let's copy the code through these second question to be more realistic about this as an interview setting that we are trying to modify the code to solve our follow up the quick note here is that the Bourbon is a little bit too long so I'm gonna change that can break to TP so it looks cleaner so the last time that what we store in this DP table is the control force fact whether we can break the sentence in clustering until that location now since that we are asking about all the possible ways of doing this break we just modify this as a high level design there now so instead of a boolean flag for whether we can do so we actually store all the ways that we can do the break so instead of a boolean in each slot in this DP table one Z table now it's gonna be the one dimensional now it's gonna be a list of strings which every string is a candidate ways of breaking the whole thing so I'm going to just copy comment this out and so that you can see what's actually being modified to get it working so now just make modifications according to the definition change so it says that we are storing multiple ways we're using a list and in the really the first location when we try to break the empty string at the only way to do so is by using the empty string so that's our base case here what are we gonna do is we gonna crop this to avoid making multiple copies wonderful hi we're just going to use this so if we turn to at this current location we look back in to find the last breakable point which is a list of longevity stuff in them that's the multiple different ways of breaking the sentence in frustration till the previous particular point what are we gonna do is just test the word just the same logic as last time and if it's valid the word we're just going to append that word to every possible solutions that we are triva from the previous breakable points so we're just going to extend this to be the candidates plus empty string plus a current word if the candidate is not the initial case base case otherwise I would just directly put that word there so this handles the case this if else here can handles that when we first very beginning in the scanning when we find the cat here at the certain location so we don't want to add an extra space in there since that it's now a dictionary now we don't have the negative one to access that so we have to use the N here so with this modification I think it should work it's a exactly what's being described here and under the modification you're just changing off the context of contact content in there so let's try yeah it's working the a big problem of this is gonna be that a let's analyze the time and space complexity before we go so the time complexity is going to be even though it's not super obvious by looking at the code it's actually gonna be two to the N minus one so it's basically that the between every character in the input string yes so it's a valid point that we test or whether it's a brick ball or not so the worst case input will be something like we're gonna use examples to demonstrate I think it's a little bit easier so s let's say that it's a for different A's and the dictionary it's as this then how many ways can we actually break the string as with this dictionary it's actually 2 to the 3rd it's eight so that's actually just popping it down so you just quickly go through this verse the case kind of a scenario when you have input string s to be something like this and they word deteriorate to be in this case it's as bad as you can get almost so there are one two three four five six seven eighty two different ways of segmenting the in fostering into a list of words using the dictionary and there you know there are M minus one breakable points inside the input string and in this case here every point is possible a breakable point so that the solution the time and space is two to the N is this number two to the N minus one for both time and space for four time you know you have to test all the possibilities for space for spaces actually I think it's a multiplied by that because each of this is a it's of you know it's a lens at least the end so that's time and this is space that's not counting the intermediate you know step memories so what's really bad about this here is that what if we have something like a bee we're gonna store everything something like this up to the last step but the DP this is gonna be what we saw at the EP one two three four DP for is going to equal to this thing if so if we have one extra be in there even though it's not a break ball we're gonna accumulate a lot of stuff in the in a way that we searching throughout the way so it's a this is I think it's essentially a buffer search you know all the levels we store the candidates which is kind of wasteful and I guess one quick ways to solve this kind of a relief this problem is to certain degree or still you know maybe just uncommon this part do a quick check whether we can actually do the break or not if it's not prequel then we don't go about and accumulating all this intermediaries are in there kind of just what if I change this so if it's not break ball we don't bother about collecting all those intermediate result and try to build out the candidates which is going to return empty stuff otherwise we will try to actually do this kind of a level by level traversals through all the possibilities and do that so working you know exactly the same way it's just that we can have an early stopping if the stuff is not breakable so compared to the 2 to the N exponential time this is cubic time so it's not too bad and yeah so this is a do a quick check whether we can do the break on that and then once we have checked to that we did indeed want to go about and to build out all the candidates or all the solutions or we go about do that so let's try submit this okay it's working not too fast okay so let's talk to us a lot even more about some of the four laps one thing that we can actually do here to potentially help is when we try to find the last brick ball our points if we can just do a test of the maximum length of the Wekiva right here we no longer needs to go from zero to the current location we can just test that the go back to as far as the maximum possible word and lands in there so that could potentially save a little bit here and also that once we passed certain point we can actually discard some of the DP stuff in English in the table because we no longer needs to consider those lots of breakable points once we you know surpassed certain location certain distances we can actually discard those to save some memory that's also some quick modification we can do I guess another way to do so is to actually just code up a DFS solution the effect a DFS kind of a backtracking solution that way you really save a lot of space basically it's trying to go as far as possible you know as DFS to come up with solution towards and if that doesn't work then you go back the intermedia result about being stuffed in the memory is going to be very much less than this one that we have for maybe with some pruning this can be okay so yeah the space is pretty bad time is not fast but at least there are just pink points around some ideas of further automatic optimization which you can do at the interview time so that's the question for today
|
Word Break II
|
word-break-ii
|
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\]
**Output:** \[ "cats and dog ", "cat sand dog "\]
**Example 2:**
**Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\]
**Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\]
**Explanation:** Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** \[\]
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 10`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
* Input is generated in a way that the length of the answer doesn't exceed 105.
| null |
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
|
Hard
|
139,472
|
932 |
The whole world is welcome to our channel co division in this video you will be talking about and medium type problem play list cold beautiful are its indexes 932 and width medium problem dalit code ok so one thing but it's quite noticing what is like you can see The number of dislikes is six number 56 minutes problem something like this problem fruitful subscribe like subscribe and this is like you to understand subscribe comment and subscribe this YouTube video the students to quit conflicts related to this product so let's move forward to understand this problem fixed and Validation in Tears and Norms for Beautiful Security School Beautiful Gifts for Motivation for Teachers from One Two Sexual Teachers 2nd Id Basically First and Natural Numbers of Every Distinct Which Any Subscription Listens and Did Not Exist at Least One India Key Subscribe and Norms of Key * With us of Key * With us of Key * With us switch not understanding this statement is no need to worry about my existence into her statements in very detailed weather in very simple WhatsApp for now let's move will give and elected to any beautiful exams and this also presented at one end service tab Penance for this is the suitable example This is well at a girl on this platform Let's move on to this statement of software problem with explanation and the solution in the best possible way So let's move Fateh Ki Aapke So let's focus open the problem statement of this question It is page setup switch some images and videos hum isse zamane second it is not being able to thicken the ministry should desist from every triplet panch lahsun ki list nc north eastern more this subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page that Ladies and Plus Even Number and Seven Plus and Number Office This is Gold Deposit in Elementor The Video then subscribe to the Building Not Consider Cigarette subscribe comment and subscribe the Video then subscribe to the Page if you like trophy choose any between China and is aware of this element and id 2nd id subscribe this Video plz subscribe this Video subscribe element from the quarter inch width do n't forget to subscribe and subscribe china Hot And Another Element In Even If She The Like Vegetables To Build Up The Beautiful Haryana Minister Electronic subscribe to the Page if you liked The Video then subscribe to the Ki I Am Flight Mode 2017 Se Zor To Sach Thirty One Response So Beautiful Colors Pe Ki And Let Us All So Beautiful Erring Me Office Let Me Like To Explain This In Simple Words Effectiveness Of Beautiful And Tourism Beautiful Dresses Of Type Sach Wedro Element And To Is Rumor Like Subscribe And Sequence Of Events Of The Day That Aapke Pimple Ke Naam Latest Claim That Destroys beautiful and difficult to just proven that like family to find any three index is easy and key true date this condition score inch hold day will have to say that is not tutor for waves ok so latest research and till family to do the thing will Celebrate This Is Not A Beautiful Graphics And The Like And Condition Is Like This Is A One And This Is A 2nd One Should Avoid Listening To Elements From The Is This Seven Like You Happy Sucked Eye Key Entry List Lettuce First Image-520 Entry List Lettuce First Image-520 Entry List Lettuce First Image-520 From Amazon Vitamin B2 French From This One Should Give Fool Dare Not Give Any Other Maximum Profit Chus-Chus subscribe The Channel and Chus-Chus subscribe The Channel and Chus-Chus subscribe The Channel and subscribe this Video Dekhne Ke Yahan Pe Now Udhar Comes Another Thing And Things Like They Suck One Element From National Elements From Its Destination And Displaced And Development Laxative Element And Placid And Tried To Find The Element Subscribe Indian Must Be True Blood And Development Android The Element Will Choose Between The Like Subscribe And Possible Combinations Of Change And Still Here Good At Least You After This Condition Will Hold it means pet anniversary of this type after a beautiful and research that is the combination of tourists where is the first one should forgive and second one respond so beautiful and first one will first egg sell wall which contains all elements imperative withdrawal which contains all The limits of activities and purity of any element from the first is not going to maths with apparent ease of elements from secondary OK but even it's beautiful and active is beautiful and even consider sequence of faculty element as of maintaining sequence and co pilot in the Ninth English How To Life But Such Beautiful And With The Help Of The Concept Of Electron Come Here That Your 100 Microchips Like VHP Build And Beautiful And A Half Size And So Let's Start With Hubs Like You Have Only One Elements Like Constipation Edifice One Where the Element It's OK What Do You Do That It's Point to Just Pushp Time and Developments in the Pushp The Way Element OK So Difficult Top and Bottom Printed First Tree in Life Tried Every Element in Noida Current President of Five Elements of Elements Like * - 110 of Elements Like * - 110 of Elements Like * - 110 A Must Be I * The A Must Be I * The A Must Be I * The Right and Left Medium High Belongs to OK So IS Belongs to For Every Element and My Like Plate Mein Dialogues 202 The Current Price A Minus One OK So I Belongs to This Range and For Every I V Are going to front don't like this is not fighting scene shoot have to write down what didn't listen to me in office don't get confused is another that candidate this content for a day flash light thank you tomorrow morning time someone suicide in noida for every Element and Migrant Sharing and Find out the Tubelight Current Affair * Minor out the Tubelight Current Affair * Minor out the Tubelight Current Affair * Minor and Current Affair * and Deficits Award and Current Affair * and Deficits Award and Current Affair * and Deficits Award liked The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our Channel Notes from the like Subscribe and you beautiful and doing this Beautiful edit ok sir no dues fun and youthful spirit from sequence positive for beautiful lyrics by painting for elements in paintings prohibition ok so let's take an example raghavan that and let it into words like and sharing som aaye bhuke so let's am going to build up 10.25 Okay So That's Time build up 10.25 Okay So That's Time build up 10.25 Okay So That's Time Going To Sleep To Find Out The Egg Current Affairs2013 Current Affairs In Two A Minus One Should Be Like One And Events Like 12345 Subscribe Like Subscribe My Next Time You'll Find Some Water To Avoid 203 Dutyful My Voice Of Beautiful And Wide Combination Of This Element Who Is Always Beautiful And These Elements To Always Beautiful Fix Security 13201 Sure Development Of Mid Like Sid Subscribe To New Delhi And Concrete 809 The First Published On Oct 10 Pushp Decision So This Is The Amazing Shift Authors Subscribe To 15 So Let's Look Enhancer Codes Like Ko Can Also Avoid Food Vacancy Lutab Skin 100 Talking About 10 Things You Shouldn't Talk About Already Subscribe To So Just Like They'll start with the beautiful area of Science One And Will Just Do It Man Like Me On Twitter Request Size Like And Size And For Migraine Tight National Laker Temporary Sector-17 Push Up All National Laker Temporary Sector-17 Push Up All National Laker Temporary Sector-17 Push Up All The Development Will Be Difficult To Find All The And Number System And Equal To And Equipment To Minus Point Will Turn Into Numerous Such Practice Andher City Near Boisar China Select Na Mintu And After Doing 10 Minutes Check The Next Point You Need To Change Your Pan More The Rise In Your Mind Like His Idea After First And Subscribe Aaj Mantri S Beautiful And Butter Like You For The Study Course Like Previous K Switch On The 1313 But Subscribe The Amazing subscribe Video subscribe and subscribe the Channel and subscirbe Already 2015 Upto 300 Units Generated From The One Name Do This Life Is And Previous Condition Tigresses Not Equal To A K Into to ok 100 whatsapp dance like supports multiply vice chief that witch to that and a multiply with all so to-do like a multiply with all so to-do like a multiply with all so to-do like and just multiplying every element de witch 2012 from now half toe water start me to-do list from now half toe water start me to-do list from now half toe water start me to-do list if you multiply Every element of the rebel to cigarette price is the same that Redmi to all so much cash withdrawal width if you multiply wealth like life so this condition apply condition subscribe this Video then subscribe to the Page if you liked The Video then that expression is absolutely astounded The current President of the Sacrifice there lives without some action Romantic Potential Video Avenger Street Light and Okay Savagya Masking Like This Video Share This Video and Subscribe Our YouTube Channel Health Benefits to Comment Willok Suchak Hai Don't Get Clear dacoit 100 thank you for watching this video
|
Beautiful Array
|
monotonic-array
|
An array `nums` of length `n` is **beautiful** if:
* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There will be at least one valid answer for the given `n`.
**Example 1:**
**Input:** n = 4
**Output:** \[2,1,4,3\]
**Example 2:**
**Input:** n = 5
**Output:** \[3,1,2,5,4\]
**Constraints:**
* `1 <= n <= 1000`
| null |
Array
|
Easy
|
2316
|
191 |
hello hi everyone welcome back to the channel so I hope you're doing extremely well so today we'll be solving this problem number of one bits so basically we given an unsigned integer and we have to return the number of one bits that this integer has that's the problem statement of this problem so how we going to solve this problem so what is the unsigned integer in the very first place an unsigned integer is a positive integer which lies in this r right that is a unsigned integer now there are certain noes there are a couple of nodes which are which have been given here because we have uh Java programmers as well so these notes are given for the Java programmers has to take care of certain things that there is no unsigned integer type in Java also the signed integers are represented by two's complement notation that we know so let's see how we can solve this problem so let's take an example to understand it better so let's take an example let's say 0 1 so this is five right basically we have a integer which is of 32 bits and how we going to count the number of set bits that is has we can see that this integer has two set bits how we can find it now we have to think in the bitwise terms we have to think we have to be bit we have to use some bitwise operators to solve this problem so let's see how we can do that so think about operations since we want to find just set bits how we can basically locate that we have a set bit at a particular position what are the ways to do so think observe or remember the property of bitwise operations that if I have one below one let's say if I put one below one then let's say the result that I get is one but if I get zero below one then the result that I get is zero this is the property of end operator so why I'm thinking about end operator we'll see that so this is the property of end operator that if I end a bit set bit with a set bit then it is going to give me one if I end a set bit with an unset bit it is going to give me zero this property is used to find the set bits to locate the set bits in the given number so this is a number n so let's see how we can do that so here we have a number let's take a number one let's take one so what is the property of number one we can see that in number one we have the first bit or the last bit set that is the property of number one now if I end this number n with this one what it is going to give me if the last bit of this number n is set then this is going to give me 1 0 1 if it is not set then it is going to give me a blank zero now how this thing can help us to count the number of bits that we have number of set bits that we have in N let's see that since we have we can see that if I end one with this n it is going to give me one if the last bit of the number n is set otherwise it is going to give me zero then since I also want to count this bit as well I have to somehow bring this bit this set bit at this position how I can do that how I can shift the bits towards the right position that can be done using the right shift operator that we know so what the right shift operator does it simply shifts the bits towards right position by one so if I perform right shift operation on this n like this the bits of this number n will be shifted like this the resultant number would be like 0 1 0 this will be the resultant number n right now again and this number with one is it going to give me anything it is going to give me zero why because you can see that the last bit of this number n is unset fine so this is going to give me zero so let's again right shift the bits by one the resultant number would be 0 1 this is the resultant number now if I end this number with one this is going to give me one so if I end these numbers it is going to give me one that means this we have we again have a set bit at the last position so the count becomes two so we assume that we are counting the set bits whenever we get the end of the two numbers to be one we simply assume that the bit the last bit or the first bit of the number n is set so initially I found that bit at this position when I ended this number in the very first iteration after that after right Shifting the bits by two positions I again find the end of these two numbers to be one so I count I increment my count or my answer by one again so the answer has become two at this point let's right shift the bits by one again so if I right shift the bits by one again this is this will be become 0 what does that mean that means the number n vanishes and it becomes zero fine so what does that mean that means we have to end here we have counted all of the bits in the number we have counted all of the set bits in the number n fine and the count that we have is my answer that I need so how many times I need to iterate just find the left mod leftmost set bit in the given number so let's say the left leftmost set bit is here then I have to iterate for 1 2 3 4 5 six times if the leftmost set bit is at 32th position then I have to iterate for 33 times to make the number n to uh zero after 33 iterations the number n will become zero right what does that mean that means we can simply use end operator we can simply use right shift operator and or Loop fine which runs till the number goes zero and that is going to give me my answer so let's jump to the code implementation part so let's initialize an answer variable to zero let's use the Y Loop till this n becomes zero if the last bit of this number n is set then I'm going to increment the answer by one and if it is the case then what does that mean that means the last bit of the number is set and I'm going to count that bit by one but now in the very next iteration I have to right shift the bits by one so n is equals to n right shift one fine and at the end return this answer because that is going to contain my final answer so that got accepted and let's submit this so the number of set bits are also called the Hamming distance in the problem statement so what is the Hamming distance it's the number of set bits in the given binary number right like here in this case the Hamming distance is three here in this case the Hamming distance is one here in this case the Hamming distance is 31 because we have only one bit to be unset we can see that the binary length binary string of length is of 32 means the number that we have is of length 32 bits only so what are the maximum number of iterations in this while loop that we can have the maximum number of iterations would be 33 fine and what does that mean that means the time complexity can be said that it is constant or we can also say the if let's say I want to be very specific I want to count the number of iterations that I take then how we can find the position of the last bit last set bit in a given number let's say we have five how we going to find the position of the last set pit in the number we can see that if I take the logarithmic log of this five to the base 2 what ises that going to give me is the largest power which I can raise to two so that the answer that I get is five and the largest power that I get from here is one so if I take C basically it's not one it's 1 point it's something like uh it's not one sorry it's 2 point Something 2 point something right so if I take seal of this value that is going to return me three fine so if five is this 0 1 then how many iterations that I need the number of iterations I need is three because in the very first iteration I will count this then in the next iteration this zero will come here then I will then in the next iteration this one will become will come to here then in the very next iteration the number will go to zero so it will take me exactly three iterations for the number to become zero and that is exactly equal to the Seal of log of 5 to the base 2 so what is the time complexity is log of n if you just talk about the exact time complexity right bigger of log of n to the base 2 but since we already know that since we already know the upper bound that no matter what the number is the number of iterations will not exceed 33 fine they will never exceed 33 so the test cases are generated such that all of the answers that we have are in the range from 0 to 33 all of the test cases take any binary string the test cases lies in this range the answers the output test cases right fine so that's all for this video uh also let's talk about the space complexity since we're not using any extra linear space we're not using any extra data structure the space complexity is constant so I hope you enjoyed the video you got some clarity about the binary representation and some bitwise operations from this video and I you I hope you're really enjoying this video If you really like this video if you enjoy this video then do hit the like button in the video and that is going to motivate me a lot to make more and more such videos and courses and that's all for this video I will see you soon in my next video till then take care bye-bye
|
Number of 1 Bits
|
number-of-1-bits
|
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)).
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`.
**Example 1:**
**Input:** n = 00000000000000000000000000001011
**Output:** 3
**Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits.
**Example 2:**
**Input:** n = 00000000000000000000000010000000
**Output:** 1
**Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit.
**Example 3:**
**Input:** n = 11111111111111111111111111111101
**Output:** 31
**Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits.
**Constraints:**
* The input must be a **binary string** of length `32`.
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Bit Manipulation
|
Easy
|
190,231,338,401,461,693,767
|
450 |
welcome to august eco challenge today's problem is delete node in a binary search tree given a root node reference of a binary search tree and a key delete the node with the given key in the bst so basically we want to search for the node for the given key and then delete it we want to do this in o of height of the tree so we call that h and we probably will be writing a recursive function to be doing this so this problem's simple enough how do we do it well there's a couple possibilities that can occur here right say that we are given the number two to delete so we can just traverse down our binary search tree normally go left if our number is greater and right if our number for the tree node is less and we just search down until we find the key and say that the key we're given is 2 and it has no children all we need to do is make that parent that was pointing to that node now point to a nun right so whatever we return here we can just return a nun if it has no children and make sure the parent from whatever direction we came in whether it was right or left is now pointing to a nun value now what if it has one child so if we want to delete six we would want to bring this seven up to now point to the six right we want to have this five point to the seven instead so what we can do there is just um depending on whether the value if whether it has a child of left or as a child of right just return that one and make that the parent point to that note instead now but those are only going to take care of three cases right either they have no children they have one child to the right or they have one child to the left but what do we do when they have two children and that's a little bit more complicated so we'll get into that as we code this out let's start by using this function here given to us as the reverse recursive function so what we'll do is first say if not node i'm sorry if not root was return none because there's no tree given to us otherwise we're going to do a typical binary search in a binary search tree and go left or right depending on whether the value is greater or higher so first i'll say if the root dot value equals the key given to us then we're going to do something a little different but we'll pass that for now and we'll say else if root.value is greater than the else if root.value is greater than the else if root.value is greater than the key then what do we want to do well that means our key is to the left right so we will recursively call our delete node i should write self here and we want to go left so we'll say root dot left and we'll pass in the same key which is still going to be key now one thing also that we want to make sure that whatever we return is going to be what we set to this to whatever root here is right so here we'll make root dot left equal to whatever gets returned from our recursive call otherwise we know that we're going to go to the right so we'll say root.right to the right so we'll say root.right to the right so we'll say root.right equals self.delete node to root dot equals self.delete node to root dot equals self.delete node to root dot write key finally at the end of the recursive call we'll return the node okay so that's simple enough but what if we reach our key number and we want to make sure we return the proper node right so there's four possibilities that we mentioned we said there may be no children there might be one children to the left or one children to the right or they might have both children so let's start with if there's no children's if root.left children's if root.left children's if root.left and root.right are both null so and root.right are both null so and root.right are both null so if not root dot left and not root dot right well we return a none because we want whatever direction we came from to now point to a none since we're getting rid of that we're that node otherwise if not root.left root.left root.left but there is a root.right then we return but there is a root.right then we return but there is a root.right then we return the root.right the root.right the root.right because now whatever direction we came from is now going to point to that root.right root.right root.right same thing if it's the other way if not root dot write and root.left exists write and root.left exists write and root.left exists then return root.left then return root.left then return root.left so we've already taken care of three possibilities but what if they both have children and that's kind of the hard one so say that we have this example here and we want to get rid of the number two we enter in the number two and we want to get rid of that so what's this what is this going to look like afterward well if we get rid of 2 then we want 3 net the next greatest number to now take its place right we want 3 up here and we want to get rid of this 3 here and it would be the same for like any other way if it's has two children basically want to get the next minimum number and replace that and get rid of that original number so how can we do that and to get that actual node moved up here is a lot more complicated how about we just take the value and replace this node's value with that next number and then recall this delete node to delete that node number here that existed before so we can do that sounds not too bad so if all three of these possibilities were not the case if both let's say if both children then let's move to the right once and then go left as far as possible to get the next um greatest number so we'll set some sort of pointer and we'll say all right move first to the right and we'll say while this pointer has a left keep making uh left traversals to the left to get the next you know greatest number so once we've finished that now our point is going to be pointing to the next uh lowest number so we'll say okay root dot value now we want that to equal to the pointer dot value and now whatever this route is pointing to on the right side since we made sure to move right once now we want that to equal delete node and we will pass in the uh root dot write with the root dot value since it's going to be the same value that we just replaced it with and because we just replaced this with three now remember that three existed here we're going to go down here and delete three and return the uh the current node here which is only four so yeah i mean that's kind of what we're going to do and i believe that might be it let's see if this works and it looks like it's working let's go and submit that and accept it so time complexity on this is basically the height of the tree of h we do some extra traversals here but it's not enough to make it exponential and that would be it and this is really the trickiest part here figuring out that we want to get the next greatest number and replace that node that we're deleting with that value and then delete that actual node for the next value so that would be it all right so that concludes our august challenge i really hope that helps really appreciate you watching my videos so thank you and remember do not trust me i know nothing
|
Delete Node in a BST
|
delete-node-in-a-bst
|
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_.
Basically, the deletion can be divided into two stages:
1. Search for a node to remove.
2. If the node is found, delete the node.
**Example 1:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 3
**Output:** \[5,4,6,2,null,null,7\]
**Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST.
Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted.
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,7\], key = 0
**Output:** \[5,3,6,2,4,null,7\]
**Explanation:** The tree does not contain a node with value = 0.
**Example 3:**
**Input:** root = \[\], key = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* Each node has a **unique** value.
* `root` is a valid binary search tree.
* `-105 <= key <= 105`
**Follow up:** Could you solve it with time complexity `O(height of tree)`?
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
791
|
226 |
foreign number 226 invert binary tray so you are given the root of a binary tree in with day 3 and they return its root so here you can say will be given one binary tray you need to create the image of that binary tray that means invert of that binary tray and you need to return the root of that tree so there are two approaches to solve this problem the first one is you can create the new binary tree and you can you do the all processing then written back that newly created binary tree but creating a tree is a costly process so what you can do is you can do the in place swapping operations in the existed given binary tree itself and you can return the root of the original binary tree itself so that was the best option can do so first I will explain the logic behind the solution like how to proceed with this question so 4 is the root of the tray then you have two on the left side and seven on the left side so then from 2 we have on the left one three so as of now I'm not writing the six and nine just for the time being so now what we can do is from the road we go to the left tree and left subtree and then from 2 we will go to the left again one so here we don't have any left and right so we will return this one to the parent then now we will go to the right set to right side part three so three again three is the leaf node so there is no need to process further so we will written there back that three node to the parent node okay now again we will create a new here we do this mapping part so for from the parent we do this swap so we will take this put three here and one here then this side seven so on six nine so now we swapped in the left most subtree now from here to this node it will return to the parent to now we process the left side now we will see the right side so now go to the left right side of the subtree now again seven so from 7 go to left so 6 so from 6 we don't have any further so you don't need to move further you just return that sixth node now go to this side nine so nine is the leaf node so then return that nine node now you do this mapping at parent seven root node so this will become four two three one and seven nine six so in this case it is written this second node and it is written in the this node so now at the root level now 4 is the parent for the two one seven nodes so now we swap at the root level so now four become four is the rotor now this seven will come this side the pointer itself and the four and the two goes to that side swapping so it will be three one so if we see we have the root level four then seven two then nine six three one yeah so we created the invert binary from the original tree so that's how it turned now here you can see how we are doing the swapping part so while returning at the root node here taking a left pointer and making a copy it in the temporary variable and then from the total left pointer is changing to the right pointer and the right pointer is changing to the temporary variable that we store the left side pointer address so that's how we create the invert binary tray now we will write the code in Python and Java now let's write code in the Java okay first if root equal to null then just return null now we supposed to call recursive calls first we need to process the left side then we will come to the right side then we swap it so first in what tree left we go to the left then invert tray to dot rate so now then we go to the right now we store the current node so it's a tree you know MP equal to zero dot left here storing the root dot left we are creating a new node and we are storing the pointer of that true dot left in the temporary now we update the left side m dot left equal to root dot right no root dot right equal to search not 10 dot left you have no root dot rate equal to 10 so the left and right portions are swept no return the root that's it run the code um submit so it's successfully submitted now we will write in Python also now let's write code in Python if not root just return none now you need to cross the left side of the tree invert okay root dot left now you should process the right side also invert tray or dot right so once it reads back to the parent we do this swapping at the parent level so now we have to store the left pointer of the root dot left Now update the root dot right equal to um update the root dot left first go to root Dot right so root Dot right equal to temp orary root group run this solution so it's accepted so yeah that's it for this video guys I will see you in the next video foreign
|
Invert Binary Tree
|
invert-binary-tree
|
Given the `root` of a binary tree, invert the tree, and return _its root_.
**Example 1:**
**Input:** root = \[4,2,7,1,3,6,9\]
**Output:** \[4,7,2,9,6,3,1\]
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,3,1\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
875 |
hello guys welcome to another video in the series of coding today we are going to solve the problem which is called coco eating bananas so there's a guy coco who loves to eat bananas and there are piles of bananas that are given now he has to eat them within etch hours otherwise the guards will come back so coco can decide the bananas per hour eating speed and she chooses some piles of bananas and eats k bananas from that pie if the pile is less than k bananas she eats all of them instead okay coco likes to eat slowly but wants to finish eating all the bananas before the guards return so return the minimum integer k such that she can eat all the bananas within edge hours let's try to take this example to understand the problem okay so these are the piles of banana so there is a first pile which is having uh let's say three bananas something like this okay and there is second pile which is having six bananas one two three four five six okay that is the third pipe which is having seven bananas so let me try to draw it quickly one two three four five six and seven and there is a last while which is having 11 bananas one two three four five six seven eight nine ten 11 okay there are these four piles of branas now guards will come back within eight hours right so she has to eat the bananas within eight hours okay she has to eat them within eight hours because if she eats them um like after eight hours if she takes more time to eat than eight hours guards will come back and if guards come back she'll not be able to eat the bananas guards will catch her so she wants to eat all the bananas that is her aim and she has to eat them all within eight hours okay but we have to try to find the minimum possible speed of bananas eating that she can take okay so let us start with the simplest case right minimum speed that is possible is one right so let us start from one what happens if a speed is one if our banana eating speed is one in that case how many hours will she take let's try to calculate so she will eat the first banana in one hour again so in this case she will take three hours to eat these pile of bananas if her speed of eating bananas is one let me write here let's start with the minimum possible case because we have to find the minimum answer so let us start with speed of one so for this pile it will take her three hours for this pile it will take her six hours right because she has six bananas and each banana she's eating it at one banana per hour so it will take her six hours to eat six bananas right simple this pile she will take seven hours this pile she will take 11 hours okay so what is the total speed 3 plus 6 9 plus 7 16 plus 11 27 right so she will take 27 hours okay guards will come back in eight hours right so she needs to increase the speed because if she will take 27 hours to eat the bananas before she finishes eating all the bananas guards will come back sometime and she will not be able to eat so we will have to increase the speed okay let's try to increase the speed so the next possible solution is make the speed to two because if she increases the speed then the time to eat bananas will decrease okay that's what we want because now her time is too much see if she has only if her speed is only one in that case the time she is taking is 27 okay let me write here if her speed is one then the time she is taking to eat the bananas is 27 hours but she needs to complete within eight hours so this is not a possible solution okay let us increase the speed to two and let us see the time that she is taking so if she eats two bananas in every hour right so these two she can eat right these two she will eat in one hour but this banana will be left out so for her it will take two hours to eat this pile right first part of the pile she'll be able to eat in one hour but next still one banana is meaning so she will still need one more hour okay so the answer will be two similarly we can find out how many hours it takes for this pile so her speed is two so every two pair of every two bananas every pair of bananas she will be able to eat in one hour so the answer is simply six by two right in this case it is three here in this case the answer will be seven by two okay so she will be able to eat um in three hours but one banana will be left out for example these three piles should be able to eat in three hours and one banana will be left out so she will need one more hour so answer is four okay so basically the answer is simply ceiling value so ceiling of for example 11 by two speed in this case is two so ceiling of 11 by 2 so in this case what will be the answer 11 by 2 is 5 if you take the integer but if you take the ceiling it will be 6 so it will be 6 hours for this pi so what is the answer in this case 2 plus 3 5 plus 4 9 plus six fifteen okay so if she if her speed is two it will still take her 15 hours it is still greater than h right so this is also not the correct answer because guards will come back at eight hours and she is still eating so guards will catch her okay so let's increase the speed more let us make the speed equal to three okay let us increase the speed and make it equal to three now let us quickly calculate three by three is equal to one so she will take one hours and she'll be able to take eat all the bananas in this case she will take two hours because her speed is three okay so she will take two hours in this case she will take three hours and in this case she will take one two three and four hours okay so one plus two plus three plus four plus three seven plus two is nine plus one is ten if her speed is three she will uh take ten hours okay it is still greater than the time which is permitted which is it should be within eight hours okay so still this is not the solution so in this case also we will have to increase the speed so this is also not the solution now let us increase the speed to four hours if our speed is four hours in that case what will happen this pile she'll be able to eat in one hour this pile she'll be able to eat in um two hours right this pile she'll be able to eat in two hours again and this pile she will be able to eat in three hours okay so the answer is three plus two five plus two seven plus one eight so in this case she will be able to eat within the time okay so the time is she has to eat within eight hours and in this case she will be able to eat so the minimum possible answer is four okay let's try to see how we can increase the time complexity so i have written down the answer for speed from one to a lot of values okay so first thing we can notice is that after some point the value saturates right and what is that point is a maximum element okay see because the maximum that best you can do is taking the maximum element in the array in that case uh it will take one hour to each to eat each of the piles right because maximum it's going to take this much only maximum it will take 11 a speed of 11 to eat all the piles after that if you increase speed also it doesn't matter okay always it's going to take the length of the array in this case the length of the arrow is 4 so you take 4 okay so there's no point in um trying to calculate after the maximum element so let us reduce the problem so the problem is very simple now see we have to start from speed one to the maximum element possible in the array and we have to find the time okay we have to start from one because one is the minimum possible time so we have to find the minimum possible time at which the time is less than equal to 8 in this case 8 is nothing but h so the time at which we are getting the value time less than equal to 8 that is our answer so if we do a linear search if we start from 1 and we increase our speed so at 4 we will hit the threshold okay so we are basically doing a linear search we are starting from 1 and we are increasing the speed okay slowly from 1 to m we have the possible search space where m is the maximum element and in this case slowly we are doing a linear search and we are increasing the speed and the point at which the time is becoming less than equal to h in that case we are getting our answer okay this is the logic so in this case what we are doing since we are hydrating from 1 to m we have m possible iterations that we need to do because sometimes it's possible that the answer if h was equal to 4 right in this case the answer you will get at uh this value only at the last value so at maximum you will have to run all the m iterations okay and at each of the m iterations what you are doing you are basically looping over all of the values in the array to calculate the sum right so the time complexity is o of m into n how can we increase this time complexity see instead of doing a linear search what if we did a binary search okay binary search will be very helpful here because in this case uh if speed is increasing the time is decreasing or remaining constant so what will happen is see if we do a binary search instead of going from 1 to m right we are reducing the search space by 2 every time so it will not be m into n if we do a binary search the time complexity will be log of m into n this is the best that we can do okay let's see how binary search is going to work so the low lowest possible answer is one okay highest possible answer is 11 because 11 is the maximum element after that it saturates there is no point to do this okay so low is 1 high is equal to 11 okay what will be the mid value is equal to 1 plus 11 is 12 by 2 is equal to 6 so instead of starting from 1 okay instead of starting from 1 and reaching the answer what we are going to do we are going to start from 6 at 6 we know that the time is equal to 6 right at six the time is six so we know that the time is six okay we need time less than equal to eight okay we know that six for the value six the time is six and that is less than eight so we know that the answer will be definitely less than 6 can also be a possible answer okay as of now 6 is a potential candidate because 6 is satisfying the condition 6 less than equal to 8 so the answer is can be 6 okay but it can be something lesser also okay it's possible that if we decrease the speed still we can get a time which is satisfying the constant of time less than equal to eight okay and we want to find the minimum possible value of the speed right so we can still get a better answer so but the answer will lie within this range so we need not even look at these ranges we can um reduce the search space to half because anything greater than 6 will also give a time less but what we want the minimum possible speed minimum speed will only be gotten by reducing the search space to this side okay so potential candidate for answer let me note it here potential candidate for answer is 6 as of now we don't know if 6 is the answer but 6 is a candidate for answer okay and now let us um remove our high so what will be the high value high will become equal to high will be equal to five so uh the threshold the surface space is reduced so we have low is equal to one high is equal to five and what is the mid value is three one plus five six by two is three okay so now we will look here so at three what is happening is if we see a 3 the time is 10 now what we need time to be less than equal to 8 but 10 is greater than 8 so this is not satisfying this cannot be the answer okay this is not the answer if this is not the answer right anything less than 3 can also not be the answer because if we reduce the speed we will increase the time if 10 is greater than 8 15 is also greater than 8 27 is also greater than 8 okay all these values will be greater than it but we want the time which is less than equal to eight okay so if we take this search space this is definitely not the answer so again our search space has reduced to only this okay our search space has reduced to this so let me increase the low is not the answer that means 1 or 2 can also not be the answer so low will become equal to 4 high is equal to 5 and what is mid will be 4 so in this case when mid is equal to 4 we are getting the answer okay we will get the answer in which time is less than equal to eight okay time is equal to eight for the case of four and eight is less than equal to eight so eight is definitely a potential candidate so now next case what will happen since this is satisfying the answer okay we know that anything less than 4 can be the answer but already what we are seeing is low is also 4 our mid is also 4 okay so in this case high will also become equal to 4 next time and finally we will stop the iteration so now let's move forward to coding it so we have to first of all declare low is 1 what is the high is equal to the maximum element in the array max element of files dot begin to files dot and now let us do the usual binary case binary search code so first we will declare um load should be less than high till that we can keep on iterating so we will take mid value is just low plus high by 2 okay now we will take a function to calculate uh the time that we are getting okay so let me take a time function okay let's write time function we are going to send our mid we are going to send the piles um vector to that function and that function will let's say calculate the time okay so let's say in time it will give the time now this time should be less than equal to um less than equal to h for it to be the answer okay so if this time is less than equal to h right this will be a potential candidate so let me take answer so let's initially give answer equal to zero and let's say if time is less than equal to h right so in this case then your potential candidate will become equal to mid okay but this does not mean that this is the answer for example in our case when we started with 6 was also giving us the solution okay but it doesn't mean that 6 is the right answer that can be some other lower answer which can give a better uh possibility so we will have to reduce the search space okay so we are storing it storing the candy rate and answer and we will also reduce the first place so high will be equal to mid minus one okay else you can increase low is equal to mid plus 150 that's it now let us call this time function so let me declare this time function here and that will return the sum okay so we are sending mid value and we are also sending the piles so let me take some equal to 0 and for end i equal to 0 i less than files dot size i plus so all the elements of the array we are going to iterate and we are going to okay basically what we have to do we have to take the ceiling value of okay the element that is currently there right piles of i okay for example if let's say your speed is equal to um 5 okay so in this case suppose 7 right 7 is the banana number of bananas you have so the answer will be 2 in this case because see what you are doing is basically you are doing 7 by 5 okay but if you do 7 by 5 the integer value will be 1 right so but you have but the answer in this case should be two because you will eat five bananas in one hour and remaining bananas also you will eat in one hour so the answer should be two in this case so basically uh you have to not simply do piles of i divided by mid but rather this is the case okay this is the case uh which will give you one okay seven by five will give you one but you also need to add another one in case you have a reminder you need to add another one and make it two so we will check if we have a reminder so if piles of i mod made not equal to zero okay if this is true then we will add another one so then this will give us the proper answer okay so this is the condition that we can check okay that's it and finally we can return so this will calculate the sum and if the time is less than equal to h this will be the answer so finally you can fit on answer let's check and see if this is working this working let's submit and see it's working that's it thank you for being patient and
|
Koko Eating Bananas
|
longest-mountain-in-array
|
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours.
Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_.
**Example 1:**
**Input:** piles = \[3,6,7,11\], h = 8
**Output:** 4
**Example 2:**
**Input:** piles = \[30,11,23,4,20\], h = 5
**Output:** 30
**Example 3:**
**Input:** piles = \[30,11,23,4,20\], h = 6
**Output:** 23
**Constraints:**
* `1 <= piles.length <= 104`
* `piles.length <= h <= 109`
* `1 <= piles[i] <= 109`
| null |
Array,Two Pointers,Dynamic Programming,Enumeration
|
Medium
|
1766,2205
|
374 |
hey folks welcome back to another video today we're looking at question 374 guest number higher or lower the way we'll be approaching this problem is by using binary search the way binary search works is that you have a lower bound and an upper bound and you choose a number in between these two bounds to figure out how close or far you are to the actual gas so let's get started the first thing you need to do is actually set your bounds so let's say set a lower bound to one because that's what the question States and the higher bound is n awesome so once we have the bone set up the thing that we need to check is actually have a while loop that keeps checking whether the low is less than or equal to the higher value so this keeps the while loop in track and we need to get the current value that we're actually testing for right and how does that work um the way that it works is we get the middle number 100 pin at the low and the high bones and the way it's calculated is using this formula awesome once we have the number that we want to examine we send it to the API which in our case is guess you send it off and then once you have the result you actually check if the result is equal to 1 is equal to zero basically means that we have guessed the right number and you return the current number as is because that's the thing that you need to return uh you have to guess in which number I picked it right so if the result is not equal to zero the result could be equal to one and we need to do something here um and if the result is equal to -1 we need to do something is equal to -1 we need to do something is equal to -1 we need to do something here as well so what exactly does this mean when uh the result is one your guess is lower than the number that I picked so this basically means that once you have you guess it's lower than the number I picked basically the number is higher so it would be you're setting low to be equal to current plus one and when it's negative one your guess is higher than the number I picked that means you need to reset the high value to be car minus one awesome so once you set up these values this will keep uh looping through until we actually get zero um and then in the end we just need to have a dummy return statement and the reason why I say a dummy return statement is because uh we know that the result should be returned at some point within this while loop because for sure we have a result um and in the end we just need to have like a dummy return statement because as a signature of the method awesome so let's try compiling this and see if it's okay the first test case is okay everything else is okay as well awesome so let's talk about the space and the time complexity of this entire solution the space complexity is of one since we're not really using any additional space and the time complexity is log n because we are using binary search uh that's the reason why it is login if we went through the numbers from 1 to n um at that point the time complexity would be n uh but for the solution since we use my research it's log n awesome if you have any questions about the solution please let me know in the comments below don't forget to like the video and subscribe to the channel I would really appreciate that it keeps me motivated to make more videos thanks so much and I'll see you all in the next video peace
|
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,060 |
hello guys this is um thomas right here and today i thought i'd go through another um excuse me um i thought i'd go through another binary search this question actually facebook um likes a lot because in the solution section somebody from facebook i think had it for on-site as a question right for on-site as a question right for on-site as a question right back in 2021 so i guess um without further ado i will get into this question but before i get into this question it may seem easy to the people who was making the videos oh they just coded up in front of you but this question actually took me um i think it was a it was around it was a little under 40 minutes to code up the for the first time i did it right and um so it just shows that even though people make it look easy but you know a lot of times the reality is it's not that easy as it's not as easy as they made it looks like you know it's actually a little bit more you know challenging but um without further ado or get into the actual question part right so i'll get rid of all these comments that i made to debug and guys by the way it's good practice for you to you know write your code within the website itself instead of your local ide and use okay do not use this debugger okay use system.out or print out it okay use system.out or print out it okay use system.out or print out it because in a real interview concept in the context that's what you know the most likely you would be using so without further ado we'll get into the actual question so it says given array um of you know integer array noms which is sorted in ascending order and every element is unique so this just means that you know we don't have to deal with four and four a lot of you know a lot of the duplicates um because you know with duplicates it makes it hard to count um the number of i guess elements um that are missing right which i'll mention right so um and they want you to find the case missing number so whatever you see this top casing right what should come out of your mind is using a heap right that is correct normally with these types of questions the case whatever's element or whatever you can normally use either a heap or a binary search so if you know just sink along the lines of these you'll be doing fairly good for these type that's a big giveaway for the type of question right as we can see it's a binary search but um yeah so yep that's that and um i guess so input right is obviously you know a number array you know as we could see 4 7 9 10 right the full array without any missing elements right should be four five six seven eight nine ten right so they want the what is the first missing element within here right obviously it's five if we know right because five six are missing eight is also missing right so there are three elements that's missing can we observe some sort of c right is that if we look the let's say the index the ice index right we can do it's similar to prefix sum right for any index if we minus let's say if we want to find between you know this here how many elements should we have right it's this value which is 10 minus wherever you wanted to start right 10 minus 4 plus 1 so that's seven so technically we should have it seven values was in here right and how many values do we actually have we only have four within this range right so if we go seven minus four we get the number of missing elements which is sweet right uh-huh you see where this is uh-huh you see where this is uh-huh you see where this is coming from right boys because if let's say you know it's between you know four to ten let's say if it's between four to nine how many elements are missing right we could compute it right it's nine minus four which is five right but we only have three right so we have two missing elements oh do we have three i think we have three missing elements hold up so it's nine minus four plus one yep we have six yep six divides six minus three is three so i have three missing elements between nine and four right this we could form was a binary search right but what are we actually looking for in this binary search this is a crucial question with any type of bond research is what are we trying to look for you know when we conduct the actual search itself right what are we trying to look for essentially we're trying to look for i guess the sort of the we could say the smallest index that has a missing value of three right or whatever value we're looking for right so in this case if i'm missing the value we were looking for three missing integers right then obviously we want to we wanted to look for the index right between this index and where and the starting in that and the start of the array um you know between whatever index we pick at the start of the right this interval to have the missing value of 3 which was a target right but we want this value to be as small as possible because 10 if we imagine between 10 and 4 right we also have three missing values right so you see where this is coming from right so we wanted essentially we wanted the first bad version right that's pretty good because with binary search where your pointers will be sitting at will be crucial and that will like determine i guess you know um yeah determine what solution you pick right so let's say let's pretend if we're searching for nine we're gonna be looking for i guess 8.5 we're gonna be looking for i guess 8.5 we're gonna be looking for i guess 8.5 right we essentially agree with that right if we're looking for eight point five right so any anyways the one the pointers will land on seven while the pointers will land on nine right because the left pointer will land online the right corner orlando seven after we've found these because it's pretty straightforward right we could just do a binary search for whatever to determine if you know between let's say whatever index we pick and the origin how many missing elements we have if it whether or not if it's smaller or equal to well whether or not it's larger or equal to you know the missing value the case missing value we're looking for right to i guess pinpoint the region right that's all good right so after we found these two pointers right um left and right we actually we don't need this missing left okay it's not important right because this is this value itself the let's say the nine here right that means um between four and nine there are three missing index right we wanted to be looking at the index before nine right and see how many missing values it has between you know start um between that interval between you know the index before the one before nine to see how many missing values it has right so let's say if it has two missing values if we're looking for the certain missing value right then we obviously we what we do is we just go um no noms right the value of this one right plus you know k minus however many missing values that one has right and that's you know what we need to do so yeah that's basically that it is a binary search and it's not that hard but you know if it's your first time doing it you know you may be bogged you know again with the details of one research and um all these indexing you know look at this all this you know all this index you know this minus side this motorcyc by the way here is um dealing with a corner case guys so what this does right is essentially we're saying that you know because if it doesn't exist if you know if we're looking for the hundreds missing value right it doesn't even exist between here then we just we will just work out um you know how many missing values is at the end of the array and then we just basically with that value minus however many more we're going to be looking for so if we're looking for the hundreds uh missing value and a 10 we have three missing value we'll just go 10 plus 97 and that'll be the 97's missing value so that's pretty much that very straightforward um yep that's it i guess um for me from today and um i just want to let you know i guess my friend you know all these friends who's you know watching these videos occasionally and i guess giving me support for the lead code grind you know the game is never over it's a never-ending marathon right so we're a never-ending marathon right so we're a never-ending marathon right so we're gonna be working through the race racing through other people not other people racing with ourself because it's not a competition with anybody else it's a competition with yourself because they are you know there are a lot of people and if you look at all the elegant you know top solutions it doesn't mean anything right you want to be racing yourself you are you know you're stronger than who you were you know five years ago two years ago you're doing good right because life is a never ending marathon you've always got to move forward but um yeah and i actually enjoy these questions but um i will attach a video of you know a time lapse of me actually doing this question and you would be able to see the struggle i went through as i was doing and i came from a software engineering um honors degree so you know i supposedly i should have uh okay amount of coding background compared to people who is switching to cs or who is not even a cs grad looking for a software engineer job you know doing all these leak code i have a little bit of the advantage but that mainly came from just years of you know university i guess we learned c we learned java we learned python you know i guess we learned all these so i was fortunate enough to be able to you know just sort of pick up and pick a language and just you know do lee code wizard but yeah um i do indeed thank you all you guys for watching and uh never give up so so foreign
|
Missing Element in Sorted Array
|
longest-repeating-substring
|
Given an integer array `nums` which is sorted in **ascending order** and all of its elements are **unique** and given also an integer `k`, return the `kth` missing number starting from the leftmost number of the array.
**Example 1:**
**Input:** nums = \[4,7,9,10\], k = 1
**Output:** 5
**Explanation:** The first missing number is 5.
**Example 2:**
**Input:** nums = \[4,7,9,10\], k = 3
**Output:** 8
**Explanation:** The missing numbers are \[5,6,8,...\], hence the third missing number is 8.
**Example 3:**
**Input:** nums = \[1,2,4\], k = 3
**Output:** 6
**Explanation:** The missing numbers are \[3,5,6,7,...\], hence the third missing number is 6.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 107`
* `nums` is sorted in **ascending order,** and all the elements are **unique**.
* `1 <= k <= 108`
**Follow up:** Can you find a logarithmic time complexity (i.e., `O(log(n))`) solution?
|
Generate all substrings in O(N^2) time with hashing. Choose those hashing of strings with the largest length.
|
String,Binary Search,Dynamic Programming,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
207 |
hey everyone in this video let's take a look at question 207 course schedule only code this is part of our blind 75 list of questions so let's begin in this question there are total of numb courses that you can take labeled from zero to num courses minus one so given an array prerequisite where prerequisites of I equal a i b i indicates that you must take course B before you want to take course a for example if the pair has zero and one this indicates that in order to take chord zero you have to take course one first we want to return true if we can finish all of the courses well let's take a look at the examples that we have here you can see that there's two courses zero and one and what can we have well here in this case it means that in order for us to take course one we have to take course zero first and so what we can do is we can take chord is zero and then course one after and so we're able to do it in this case over here we can actually see that we have like a kind of like a cycle here right like because what we have is in order for us to take course one we need to take course zero but in order for us to take core zero we have to take course one so really we can't take any of them because they rely on the other one so in that sense like that's a way of looking at this problem now notice here that we have the prerequisites and we have like some sort of dependency mapping here right like in order for us to take a we have to take B so whenever we have something like this it's often easier to think of this in terms of a graph type problem well why graph type problem because in graph type problems specifically directed graph type problems we can illustrate this dependency for example for something like a to B if you think about it what this essentially saying is that we have a mapping as follows we'll have B will have a and we'll have a node or Edge between them notice that the edge goes from B to a indicating that a has a dependency on B it shouldn't go like this because this would mean that B has a dependency on a which it doesn't in the case for the second example what ended up happening is actually something like this be at a dependency on a and also a at a dependency on B so if you really think about this like how can you go about doing this problem well in the normal case right like let's just assume we had something like maybe we have something like this maybe there's like a note here C and maybe something like this right so in this case what can we do well we can take C and then B and then a right because a depends on both C and B so we can't take C and then a so what's one thing we could do and maybe here I'll hear it there's actually like d and maybe this maps to something like e for example well what we could do is we could like do a DFS score right since we've Illustrated that this is the graph problem we can maybe do a DFS call and what can you do in DFS well we could go ahead and we could start off at every single node why every single node because there has to be there might be nodes that are not even connected to like the main graph right like this d e is nothing connected to this main graph so we have to consider every single node possible and so what we can do is like for every single node that essentially like doesn't have any prerequisites so we can start off at this one over here and this one over here because these two do not have any prerequisites for every single one of the nodes here we can basically take a look and we can try doing a DFS call to see if we can visit every other node and essentially if we can do that then we will return true now this is one way of doing the problem but actually it's not the best way and the reason is because like here you're visiting every single node right and so if the graph was like very big then you would visit every single node in order to determine that yes it's possible to take this graph um like take this schedule now what's another way we can think about it well we can think of it and turn to the opposite right way right instead of visiting every single node how about we think about it in the case where like what would break the schedule what's the case and that if we find it would break the schedule well if you think about it and I'll go back over here maybe let's say we had something like this let's say add something again like this so in this case would it break the schedule it would right because if you think about it in order for me to even take like C and then B in order for me to take B I would have to have taken a first but in order for me to take a I would have to have taken B first so in this sense I can actually like even solve this schedule here anyway and really if you just think about like What's Happening Here notice here that we have kind of like a Duo dependency right dependency on both side and so kind of like what you convert to this as is a cycle this essentially just a cycle in the graph so what we can note here is like if we have a graph which is perfectly good but like somewhere Downstream we have like some sort of cycle then we know that the schedule is impossible so maybe we have something like this maybe this is good maybe here we have something like this then maybe here we have let's say something like this right something like this if we have something like this then notice that there's a cycle down here and so in order for us to take like any one of these three courses like we have to have a cycle like in order for us to take this one we have to take this one but then for this we have to take this but for this we have to take this so it's essentially a dependency that keeps going and so in this scenario if we go ahead and we formulate a problem as a cycle detection type problem and we figure out there's a cycle then we know our answer is false otherwise our answer will be true and notice that in this one we don't actually have to visit every single node right there might be like nodes like all the way down here somewhere that like we don't even visit there might be like an entire graph down here that like we don't even need to visit because we already concluded that there's a cycle here so it cannot be solved okay so we have that so now how can we solve this problem well if you think about it like what is a cycle right a cycle is in one DFS call like for example maybe there's a DFS call over here you somehow arrive at the same node again so from here we can go here but notice from here we arrive back here and so if you ever notice that in our DFS call then we know that there has to be a cycle okay so let's take a look at how we can make that happen so first thing I need is I'll actually go ahead and rename this to prereqs to make the thing shorter and let me just name this to courses okay actually no I'll keep it as num courses all right so first thing notice that here prereqs can actually be zero right so if there are no prerequisites then I'm completely able to um like finish this right so if not prereqs then I would just go ahead and return true otherwise well now we need to make adjacency list right I need to make my adjacency list such that the B here which is the this part here points to the a over here how can I do that maybe I can do something like adjacency list is default dictionary of list this is how we always created in Python and then we can have for a b and prereqs then prereqs at B dot append a so here I'm essentially forming an edge from B to a indicating that there's a connection here a has a dependency on B that's what it means okay so now once we've done that what can we do well in order for us to determine whether it's a cycle or not again we have to like go through all of the nodes right we have to go through all of the nodes and so what can we do we can do something like for node or for course in range there are two num courses and then I can do my DFS call which I just call self.helper and then I can check if this self.helper and then I can check if this self.helper and then I can check if this helper function actually returned true anywhere if it returned true then this means that there's a cycle so I will return false indicating that we cannot finish our algorithm otherwise I'll return true now notice here that I'm doing a DFS call from every single position right and that's actually fine right if you think about it like because for example let's say we do a DFS call from over here then this will eventually reach this like site this will eventually like Reach This cycle over here right but maybe I start my DFS call from instead of here maybe I started from here well this will also reach the cycle okay maybe instead what if I don't even want to consider this one graph over here what if there's like another graph something like this what if we have something like this maybe there's like f over here f and you can notice that this is also a cycle right so really if we start off at like any of the nodes in the cycle then we will arrive at the answer again and so like these two are not connected graphs right like these two are not connected but they're still part of the same graph they're still part of the same schedule but you can see that like by starting off at any of the nodes and like we have to consider each and every one of them because if we just consider the ones here and there's a cycle like somewhere here then we'll never arrive at the answer right so that's why we have to consider every single node and if we consider any of the nodes in a cycle really then we'll arrive at the answer in which the cycle repeats and so that's what we're just doing here so we're considering every single node and if my recursive call here returns true it means there's a there is a cycle okay so how can we go about finding a cycle let me Define my helper here what are some of the things I need to know which course I'm on I need to know adjacency list and what else well if you think about a cycle right how do I determine whether I'm at a psycho or not well let's see let's say let's start over here if I want to determine whether I'm at a cycle then if I start over here I have to somehow Reach This node again right so I need to keep like a visited or like a set of like C nodes okay so maybe I can have like a scene set over here now what can I do well first of all I'm seeing a node here for the first time right so I can go ahead and I can add this node to my list so I can do for scene.add course and then I can actually scene.add course and then I can actually scene.add course and then I can actually just do a code here I can check here um actually maybe we can skip that call for now I was going to check it at the front but I think we can just check it in the DFS call itself so let's just ignore that for now but basically now I have a node right now I have a node what can I do well now I need to visit like the neighbors now I need to visit the Neighbors which in this case is actually just one neighbor but let's assume that instead we're starting over here so we actually have two neighbors to visit okay so now I need to visit my two neighbors so I can do for a neighbor in adjacency list at course what can I do here well here I can go ahead and I can call my helper function on what on this neighbor a JCC list scene and if this somehow manages to return true if this returns true then it means that there's a cycle starting from neighbor and downwards so here I'll actually return true indicating that there is a cycle so before we actually do this we actually want to check here right like we want to check if we visited this neighbor in the past because if we have then there's already a cycle right so we don't need to like do another recursive call here so I can do like if neighbor in scene then I can also just return true and similarly I could have just done this at like the start here like I could have done like if course and scene then return true I could have just done that instead of like doing it down here but it's the same thing I just moved the condition downwards okay so now we have like our true cases which basically indicate whether there's a cycle now how do I know that there is not a cycle well I would have to return false at the very end right because which means that like I've gone through all of this and I haven't found a cycle and but so in this case I would return false now we're almost dysfunction but there's actually a hidden bug and really if you think about it you have to draw like a couple of examples like one example but here is the bug and let's see like if we can figure out what the bug is let's say we have something like this let's say here are our nodes maybe we have something here and then something here now notice that this is not a cycle right we're going to take this node first and then we would take this one and then finally we would take this one here right so let's say we go ahead and we start a DFS call from here and for every node that gets appended to scene my set I would just append it with s here so this will be appended to set and then let's say I visit this one this will be appended to set now notice that this doesn't have any like neighbors right like no children so I would go back same thing here I would go back now here notice that in the first part we actually went down the left hand side right we went down this node here but actually I have another child or I have another dependency or like another like node another Edge so I can actually go down this one as well but notice here that if I go down this one our condition here will return false right because if neighbor is if neighbor in scene well that's true right because I've already seen it before and so here we would actually calculate that there's a cycle even though there isn't one so we would be incorrectly calculating that there's a cycle so how can you fix this well we can note that every time we visit a node and we add it to our scene if that node has no other children no other notes to visit then I know that from this recursive call that started off over here I can basically finish that this node has no other calls from this recursive call so I can go ahead and pop it and so now if I pop it what does this mean well it means that from this left hand side here I was able to visit this without any cycle but maybe I can still visit it on the right hand side and so that's why I have to remove it from my scene because in this case if I visit it from the right hand side then I should be allowed to right and so now I can add it to scene and then again I can pop it off and then actually here will also like end up just finishing the algorithm here but we can notice that like if I hadn't popped it off then we would be incorrectly returning that there's a cycle but what we have to do is like once we are finished a recursive call then for each one of the nodes that we visited we should pop them off because it's possible they might be visited from another location so after this we actually have to do something like scene.remove course like scene.remove course like scene.remove course and so this is pretty much all we have to do in this question so let's take a look here what do we need to pass in what course will be course adjacency list seen here will be a set so let's take a look at this I'll go ahead and submit it see if we arrive at the answer so notice here that okay I need to find this as a set so notice here that if my helper returns true then I will return false in my main function here so let's take a look at that okay so I realized what we're doing wrong here um this here should actually be adjacency list not prereqs so that should be the problem and so now let's go ahead and run or we can just go ahead and click submit actually I think this already works so this will actually get a tra um it will get a time limit exceeded so how can we somehow optimize this well notice like one thing we're doing right so let me actually just wait for the tle here notice one thing we're doing so if I go back here and let's see I have a bunch of these nodes so maybe I have a node here and maybe like there's like a set of nodes down here right and maybe like um something like this let's just assume now when I'm doing my initial recursive call let's say you have something like this maybe I have something like this and maybe just links to somewhere like this right and let's assume that we visit like all of these actually just in one recursive call when we're doing all of these recursive calls then notice that like for each one of these nodes that we visited this one all of these nodes that we visited if you think about it like from this one DFS call we're actually traversing all of these nodes right like maybe this thing has a connection somewhere here so we're also traversing like every single one of these nodes so really instead of doing a DFS call from these nodes again and again even though like we've done it from the central location here and we verified that there are no Cycles if we visit like a node again here in our new DFS code then it doesn't really make sense to like do it again because we've already visited it from our initial DFS call over here this initial DFS code will visit all of the nodes down here and so there's no need to do another DFS Co in our for loop from this location here or this location here Etc how can we improve this well maybe we could do something like this let's have like a global visited and we'll call it this also set and something we could do actually is whenever we do a helper function we will actually add to Global visited as well we will add this course here and so I need to append Global visited here and now what well one thing we could do is if my neighbor isn't scene right then obviously like that returns true but if we've like visited this neighbor in the past like maybe we've like visited this um like we've already like visited this node in the past so if we can check like if neighbor in global visited then we've already checked this neighbor before right maybe in another recursive call it's like for example maybe we had something like this let's assume we had something like this and then maybe we had another node here something like this right so whenever we process this one we'll process this one as well and so the next DFS code when like in a new DFS code when we go ahead and process this one I don't actually need to process this anymore because this was already processed in this DFS call here and so in that sense if neighbor is in already in global visit it I can just continue I don't want to process this neighbor anymore so that's one thing we could do now another thing we would have to do is like over here right like when we're actually doing our for Loop call again we can check like we can check of course not in global visited then again we can consider this if it is in global visited then we won't consider it because we've already visited in the past so now let's go ahead and submit this to see if it works and I am missing put it here so notice that we have like two sets of like visited two sets of scene right we have the scene here which is like for the initial stack frame and then we have the scene here for like the global stack frame so that's kind of the point of like these two variables here now it turns out that like we can actually extend this algorithm one more time like even though this is like basically o of V plus e if you think about it but we can still extend this algorithm one more time V plus e being liquidity C plus edges we can still extend this algorithm one more time using something called a topological sort and so I'll go ahead and do that but yeah if you want to kind of stop the video here you can but topical logical sort is another win which you can we can approach the same problem so I do want to discuss it in this video so let's go ahead and discuss the topological sort algorithm okay so what is topological sort and so I'm actually going to go ahead and look at the Wikipedia article here because I think it has a very good definition but essentially topological sort is something you can use in a directed graph and you want to use this when you have some sort of order to follow right for example here such that every directed Edge UV from vertex U to v u comes before V in the ordering so for example if you kind of think of this right maybe this represents something like tasks to be performed and the edges might represent constraints that one task will be performed before the other one so maybe here like for tasks eight we have to actually finish task three first if you think about it we can apply the same thing to our question basically here the eight over here instead of a task you can think of it as a course to take and this node here represents or this edge here represents the constraint such that you must take this course here before you take this one here and so topological sort now I can talk about like how I can actually go about doing this algorithm and essentially what we want to do is first of all note here like let's suppose all of these for courses right all of these were courses well first of all topological store instead of using a DFS we use a BFS a breadth first search and what do we do what do we need to add on to the queue initially if you think about it for all of the nodes right like the node 11 8 9 2 all of these have dependencies right they're dependent on courses you have to have taken in the past so really if you think about it for topological sort the things you want to add into the queue are the courses that you can take that have no dependencies and basically for example maybe there's three over here right so let's take let's actually go ahead and copy this maybe I can just copy for me let's go ahead and copy it and so we have over here what do we have so for eight here looks like we have two dependencies the three and the seven but this ten here again it looks like we have two there's nine here again we have two uh for this two here just one and then etcetera right but basically notice that the three doesn't have any dependencies so we can start off at the three and basically for all of the nodes that we can visit from the three every time I visit a node we will decrease the dependency count by one or decrease the dependence account by one and notice that maybe like eventually if when 11 goes ahead and visits this 10 here then or maybe instead of 11 we can consider the seven here because 7 actually has no dependencies so when seven goes ahead and visits this eight over here this dependency count here becomes zero and so what does it mean it means now we can actually go ahead and visit node eight so we can keep going in this graph along this route and if it's in if it's a graph in which everything we can take every course and all of these at one point will be the value zero all the t's will be the value zero and so we will visit every single node and so we can keep track of like all of the courses that we visited if we have a cycle anywhere then at any specific point once we break out of the loop or once we are finished and we can't visit any more of these items in the queue then we can understand that we visited x amount of courses but if x amount of course is it does not equal the number of courses then we know again that here we cannot arrive at the answer which means that it's impossible to do the ordering so let's take a look at how we can do this oh actually just go ahead maybe I can keep the helper but clean up a lot of this so first thing I need is I will go ahead and I'll keep my prerequisite list just as it is and now what do I need a cue right and what do I need to add to the queue well I need to key I need to add in the values that have no prerequisites right so for example here the five the seven the three I need to add all of these because they have no prerequisites what can I do how can I keep track of that maybe something I could do is after the adjacency list I can you can kind of just think of this like this value here this um this value over here for example this two this is the in degree of 10 which basically means that there are two nodes coming in two edges that are coming in and so we can maybe create a list here in degree and this will have number of courses the size right number of courses exercise and what we can essentially do here is if you think about it when we have this connection here then the in degree of a increases by one right because we know that a is dependent on B so there's an edge from B to a and so the in degree of a increases by one and so in order for me to add on to my queue what I can do is I can go like index item and enumerate um actually I guess I can just go to the courses right I can just do four fours in range 0 to some courses and I can check if in degree at course if this is equal to zero then I know that this is a course that has no prerequisites so I can go ahead and add it to my queue and actually in this one we don't even need a scene like a visited array so you might notice that over here in this algorithm like we don't even have a visited array anywhere so we don't need to keep track of that so even if we have like even if we have Cycles in the graph so that's something we want to note about so let's take a look at what happens here so we can just take a look at this so while s is not empty so s what is s here SSL nodes without no incoming edges so this is essentially our Q so now that we've added in this we can just follow our normal Q approach so I can do while Q and so then what am I doing well then I'm going to remove a node so this is like my curve is equal to 2. pop and I'll pop from the front now what well now I need to selects we don't need to really worry about this one now but in this one we'll go through out of our neighbors so now we can just do this is a normal Q approach I can do for neighbor and I just see less stack curve and then what well notice here that we want to remove the edge and we want to check that there are no other incoming edges and if that's the case then we will insert that neighbor into the queue what can we check here well first thing we could do is we can do in degree at neighbor decreases by one right because it's like maybe we're on the seven here and you process this eight here so this eight if it had initially two edges coming in now it has one Edge and then I can actually check and I can check if in degree and neighbor if this is equal to zero then it means that 8 is ready to be processed because we've already processed all of the prerequisites of eight so I can do Q dot append neighbor and that's it that's essentially all I have to do here now if you take a look at what's happening here every time we run our queue right every time we have an iteration of this we're processing one course right we're processing uh courses so you can we can maybe keep track of like num taken or I guess like num courses taken let's just call it numb take it or maybe just take it we'll just cut it here then the first time when you process it we'll have taken one course and so we will continue to do this and in the very end I just want to return that taken is equal to num courses and if this is the case then what it means is I was able to process every single one of these nodes here otherwise I was not able to do that in which case we can return false so let's take a look at the test cases here and we can go ahead and submit it and so we can arrive at the answer so this is actually a breadth first search approach and we don't have to worry about cycle detection or anything essentially always start off by doing is just adding the nodes that have no prerequisites and then for each of the nodes that it links to we decrease their in degree by one and then we can see if we can add them on and so if we can process everything then we know that it's a valid schedule and so this video is probably on couldn't be on the much longer side but we're going to discuss two algorithms here DFS and the topological sort and so this one is topological sort is often very useful for these ordering type questions when you have some sort of order and for the time it's basically just vertices plus edges and for the space kind of same um just the size of the graph in terms of the number of nodes
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,743 |
hello and welcome to another video in this problem we're going to be working on restore the array from adjacent Pairs and in this problem you have an integer array nums that consists of n unique elements but you have forgotten it however you do remember every pair of adjacent elements so you're given a 2d integer array of adjacent pairs where you have every single adjacent pair in the array and you are asked to rebuild the array from these pairs so basically they're saying that one is next to two three is next to four and three is next to two so you have every single pair so like in this array we can even make it a little bit bigger so the pairs would be one and two and three and four and that's what we have and they can be in any order so you don't really know which one comes first so if one and two are pairs you can write it as two and one or one and two uh they don't really tell you which one it can be either one right so that's what they right and essentially for this if one and two are pairs three and four pairs and three and two are pairs that means the array has to be either 1 two 3 4 this is valid and also this is valid so either one of these is fine essentially and let's go to the next one so four and -2 are pairs one and four so four and -2 are pairs one and four so four and -2 are pairs one and four and3 and one so kind of the same thing four and2 are pairs one and four and3 and one and finally you have this one here where these two are pairs so you can write it the way word the other way so essentially for every single array if you have some array like this notice that whatever the array is the reverse is also valid because if you write the array in reverse order like this 54 3 2 1 actually bigger there we go so if we write 54 321 this is also valid because the pairs are the same right five and four are pairs four and three are pairs three and two are Pairs and two and one are pairs so now given some list of pairs how do we actually make the array so let's say we have this array we don't know that this is the array we're going to write down all of our Pairs and then we're going to try to figure out like how do we actually build it so let's say we have you know and we can even have it in the right order it doesn't really matter too much because we're not necessarily going to have it in the right order but let's say actually let's say we don't have it in the right order so let's say we so these are all the pairs let's say we write them in some order so let's say maybe three and four are Pairs and then we can write like three and two are pairs right because they can write in any order they want and then maybe five and four are Pairs and two and one are pairs so let's say you're given this list of pairs and how do we actually make their array so first of all what you can notice is two of the numbers are only going to have one pair right the end over here and the end over here because they don't have like this five doesn't have a right side pair and this one doesn't have a left side pair so you can see two of the numbers are only going to appear once so we can basically think of this as a graph and so let's actually draw this out as edges so let's do that so let's say we have four and three so we first of all let's write down all of our stuff and let's uh yeah so let's say we have four we have three so three and four have an edge we have two we have one and we have five now I just drew this like this because it's going to be easier to visualize but obviously you can have whatever so for three and four we make an edge for three and two we make an edge for five and four we make an edge and for two and one we make an edge so you can basically create a undirected graph of all of your edges right so you would just store and the way you would store it is for every single node like five you would store all of the edges in a list so you would have like a list of you know four and then for four you would have like uh actually make this I think this is big okay so for four you would have like three and five and then for three we would have uh two and four right the order doesn't matter so we' basically store it like this one and we' basically store it like this one and we' basically store it like this one and three and finally for one we would have two right so you just go through your edges you make like a normal adjacency list like a graph right that part pretty straightforward how to do just normal graph problem so that's how we do that now how do we actually use this information to figure out how to make our result so like I said notice we have two edges here that only have uh or two nodes that only have one Edge and so these two nodes have to be the start and end so we're just going to we're going to make this graph right we're going to go through all of the edges we're going to make this adjacency list and we're going to find the two nodes that only have one um one uh Edge right so we're g to in this case our two nodes are going to be five and one and we're basically going to just do like a traversal from one of them until we hit the other one so we're just going to say like okay let's just start at five maybe and we're just going to have some kind of Cur that's going to be five and what we're going to maintain there's few ways to do this you can either have a visited set or we're just going to keep track of the previous node we were at so for example just to show this in this graph picture we're going to be at five the previous node is going to be uh is going to start off being um null and this is kind of like a link list traversal but not exactly right so essentially what's going to happen is we're going to say okay we're going to start at 5 and then from five we're going to go to any child that is not a previous trial so we can go to and by the way once we are at a node we're also going to add it to our list right so let's say we start at five we can pick either one of these two it doesn't matter which one so we start at five we add it in and then we will Traverse to any node that's not maybe uh the previous we will just Mark with this color so previous right now is none and current is five so we can go to four because four is in our children so we're going to update C to be four and then our previous node is now going to be five right the node that we came from and we're just going to keep doing this until we get to the very last node and once we get to the very last node we know we're at the end so we're going to say okay at four we can go to any child that's not previous so from four we have three and five so we can only go to three so we're going to first up write in the node that we were at so we'll write in the four and then we will Traverse to three and we will Mark the previous to be four now if this is it's confusing you can just use a visited set and you can do the same exact thing right anytime you Traverse Mark your note as visited and only go to Children basically one of your two children will always be inv visited and the other one won't be so if that's confusing you can use that as well so for three we are going to write in three and then we're going to check in the children of three so we have two and four is previous so we're going to go to two and then we will update previous to B3 then we're going to write in two let's actually write it in the right color so we're going to write in two and then we are going to Traverse to one because we can't go to three because three is previous now we will update our previous when we Traverse to B2 then finally we have our end condition so we're at the so we're going to pick one of these to be the start node and we'll just have a while loop saying like while our current node isn't the other one and so now we have the break condition where we are at the other one so now that we're at the break condition we just exit out our Loop and finally we add our end node to the end right so you have a start node that's your current node and then you keep traversing keep reversing keep traversing until you hit your end node and that's pretty much it so all you need to do is make an adjacency list find the two nodes of one child those have to be your start and end and then Traverse either way and you just either keep track of a visited set or a previous node to make sure you don't go backwards right so you want to keep making sure you only go forward and yeah that's pretty much it and that's how you do this problem so now we can code it up so we are going to make this like graph of edges or whatever so we'll call it graph and it's going to be a default dick is pretty con uh convenient for graph because then you don't have to check if things are in there you could use get method as well but I like default dick so we're going to say for start and end in these edges so this adjacent pairs otherwise known as edges first start and then in them let's just do so for a uh for a graph that doesn't have a direction right I'm losing my words all of a sudden for a non-directed graph undirected graph you non-directed graph undirected graph you non-directed graph undirected graph you have to add the edge to both right so for start and end you have to add a path from start to end and from end to start so we'll say graph start. pen end and graph and do pend start okay now what we are going to do is we are going to get our like once we have our graph we're going to find our two nodes that could be the start or the end and I'm going to call one of them c as in like the starting node we're going to start at and then the end node and we're actually going to do a dictionary comprehension uh I was actually asked to do I guess no it's kind of like a yeah I guess it's kind of like a list comprehension and dictionary comprehension I guess it is a list comprehension technically but kind of cool I was actually asked to do this on an interview and I didn't know how to do it so actually was asked how to do a list comprehension interview too and I was so nervous that I didn't know how to do that one either so now I've been going overboard with these comprehensions to make up for it so what we're going to have is we're going to have a key for and then basically we're going to iterate through the items in the graph so we're going to say key for key value right this will be the node in maybe we can even have a better name like node and then node maybe this can be called like children or something in graph. items so graph. items will be a list of key value pairs in the dictionary if the length of the values I guess in this case it's children is one so meaning to kind of explain this essentially so we're going to have our graph uh kind of like we have here in this picture and we're saying let's take any key whose list of children is only one item and so there should only be two nodes here so that's how we do this graph that item is going to be a list of key value Pairs and we say okay if the value is two that means the length or if the length of the uh values is one sorry then we're going to add that node into our into these two nodes basically so what's going to happen here is this is really going to be a list of two nodes so this will be a list of like two nodes like one two and then we are basically destructuring it into say okay the first one's going to be the current node and the second one will be the end node so we're saving uh some I guess code there okay so now we have our two nodes that are the start in the end and we're just going to start from current and go to the end and I think this kind of stuff is kind of cool in Python you might as well try to write a little bit fancier code instead of using like really basic stuff so I think doing like list and dictionary comprehensions and all these things is a good practice to learn okay so we're going to have our result array and we're going to have a previous and we'll just make that none you could use the visited set as well and essentially so a cur is going to be our starting node and we're going to keep going until cerr is our end node so we'll say while cerr does not equal end rz. pend her and then we're going to have two numbers in here right so we'll say four num in graph Cur there's going to be always two numbers so if num does not equal previous and that's the one we want so we'll say previous C equals Cur num right so we update C to be the new number that we found the new like the new node we're going to and then previous will be the old Cur and we can break here because essentially if we found it we don't it doesn't really matter this is only going to be a for Loop of two items but whatever okay and so uh once we go through this Loop then we added our start node which is curve and then all the rest of our nodes and now we just we are on the end node so now we need to add the end node so we'll say res. aend end and return PR try that now and there you go and you can see it's pretty efficient but more importantly we have fancy with comprension Okay so let's talk through the time and space complexity for this one so essentially we're going to be going through uh all of these adjacent Pairs and we are going to be adding them to the graph so that's going to be o of n where n is length of adjacent pairs right and as far as uh this part we're going to be traversing our like graph one more time so that's going to be ENT as well um and then we are going to be traversing our graph from node to node and this is also going to be oven so we have like oven this is oven where n is the number of adjacent pairs or the length of list adjacent pairs is going to be the length of list minus one so they're basically the same and for the space so for the space we're going to have n unique uh nodes and then every single node will have two edges so basically the space of the graph is O of n because we'll have n keys and every key will have two edges or one and then this is a constant and we don't count the result and previous is constant as well so the thing that really we need to have is the graph and we can't really avoid this we need to have a graph or like a visited set or something that's basically going to be open and yeah it's going to be all for this problem so not too bad as long as you realize like it's a graph and how to figure out what Edge to start from also to realize that you can start from either end and the connections are going to be basically the same it doesn't really matter where you start from the list or the reverse list will both link so that's going to be all for this one and uh please like it if you like it and please subscribe to the channel helps grow it a lot and I think we're at like 550 Subs so thanks for that and I'll see you in the next video so thanks for watching
|
Restore the Array From Adjacent Pairs
|
count-substrings-that-differ-by-one-character
|
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`.
You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`.
It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**.
Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_.
**Example 1:**
**Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\]
**Output:** \[1,2,3,4\]
**Explanation:** This array has all its adjacent pairs in adjacentPairs.
Notice that adjacentPairs\[i\] may not be in left-to-right order.
**Example 2:**
**Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\]
**Output:** \[-2,4,1,-3\]
**Explanation:** There can be negative numbers.
Another solution is \[-3,1,4,-2\], which would also be accepted.
**Example 3:**
**Input:** adjacentPairs = \[\[100000,-100000\]\]
**Output:** \[100000,-100000\]
**Constraints:**
* `nums.length == n`
* `adjacentPairs.length == n - 1`
* `adjacentPairs[i].length == 2`
* `2 <= n <= 105`
* `-105 <= nums[i], ui, vi <= 105`
* There exists some `nums` that has `adjacentPairs` as its pairs.
|
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
|
Hash Table,String,Dynamic Programming
|
Medium
|
2256
|
508 |
so hello everyone so today we are having another problem the problem is like this suppose you we have given a tree or difficulty and this is another decision other tree so the problem that we have given it so this is the tree that we have given and we need to find so the thing that we need is most frequent substrate and what exactly that mean I'm gonna tell you in a few minutes you need to find the sub tree some say that what exactly the maximum frequency that is happening all the way around this tree so here you know what is there are sub tree of they supported this is null so 0 so what is this is 1 and if you go here 0 so the sub tree sum will be minus 3 if you go over here so what it does of 3 so 4 plus 1 5 minus 3 2 so this will be 2 so the frequent maximum sub tree sum will be all one two three why because one is present exactly one time who is present exactly one time three is present exactly one time so 1 2 and minus 3 you have to print all those things alright but if you come over here if you came up here 0 so it will be 2 so this will be 0 this will be minus 4 and if you come over here so 4 plus 2 6 minus 4 2 so you can see here 2 is present twice so you need to click twice here so in the same way if you come over here so here for 1 so 4 plus 1 what did that PI plus 2 7 if you came over 3 1 and if you came up here 3 plus 1 4 plus 3 7 and after that so 4 v 7 sorry 7 plus 7 1414 1125 or you can see here 1 is present how many time 1 is further to time 7 is present to time other thing up I don't exactly want so you need to print what 1 and 7 so how to solve this is quite an interesting problem and I wanted to think a bit more about it so this is the point very easy problem if you see that so all you need to do is if thinking how can I solve this problem where to put all this value or tell where to put all this count I support you if I came over here 77 I need to the moment if I get one more time if I need to increment that so that particular time you need to think of map all right so you need to think of map how if you came up here if you are able to get this so this map thing and also on 90% of the problem map thing and also on 90% of the problem map thing and also on 90% of the problem is done so let me solve so first I need to write what exactly the base case or base cases like this if it is not or like if the root is equal to G goes to not right so what I'm going to do is max frequent root so if it is none so what I'm gonna return is zero so I did two writer integer 0 alright else what I'm gonna do is this approach if there is a node present so what I'm gonna do is I will add the root of it and if there is a left nor present I will add that if there is a write node present I will add that all right so what I'm going to do that so let me do that so let's say integer wreck and I need to store that max frequency of root dot left what I'm going to do is so you here for either so I will go over here then I will take care of this one so I will go over here so it will return zero it will so integer X will be zero so after that I will go to the right side so integer Y max frequency root dot right oh it came up here and it will go of zero and it was eight and zero so the moment if you see here come over here so all you need to do is integer total is because two you need to route whatever the route that you got routed out of an plus X plus y all right now you need to check whether this total is already present or not whether this one that whatever you have got here all right whether you have come across with this one before or not if you have not come across it the one put into that map if you have already come across with this one so all you need to do you need to increment the count so for that what I'm going to do so this map let me say map integer so this will be a global variable I'm taking a so if you want to go for local you can do that so what I'm going to do M of total so I need to check if M of total not is equal to 0 which means that if it is product if I'm of total is present for that particular time what I'm going to do a more total plus okay if there is a if one is already present so support say you came up here in the first time seven is present not present so you need to push that supports a for the second time suppose day seven is already one so for the next time if you encounter this seven again so all you need to do seven eight equal to two all right if it is not present else I am off total is equal to one all right if it is not present you need to make this H one or as simple as that so now what this thing is done this whole thing is done now let me clear this up so I came up here so 11 why I came up here nothing so you need to go from here so this is zero what this is it's a for first time for will be one and the moment you will go to the next time so one will be one so you need to come over here and you need to add this side four and this side 1 4 + 5 + 2 7 side four and this side 1 4 + 5 + 2 7 side four and this side 1 4 + 5 + 2 7 is not present so you need to add here so you need to go this side 3 so 3 will be a 1 the moment you came up here 1 is already there so you need to come over here and to the moment you came back here so that particular time so 3 plus 1 4 plus 3 7 so you need to do this - all right and if you came up here 7 - all right and if you came up here 7 - all right and if you came up here 7 plus 7 14 so this X will be 7 and Y will be 7 so we need to 14 so 25 is not present so at that moment so what you gonna do so when the main function the moment from where you are calling this so from the main function what you're going to do or you need to iterate this array all right so here you need to find which element what is the maximum of it all right what is the maximum or else you can do it a year or okay so iterate through the map they trade through the map and find the maximum and after that traverse through the map and find which are all print all the element and Traverse through the math and print all the element whose value is max or as simple as that so this is very simple all you need to sub if you don't know how to use this map here then this problem will be a disaster if you can able to know how to use this that it is very simple problem
|
Most Frequent Subtree Sum
|
most-frequent-subtree-sum
|
Given the `root` of a binary tree, return the most frequent **subtree sum**. If there is a tie, return all the values with the highest frequency in any order.
The **subtree sum** of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
**Example 1:**
**Input:** root = \[5,2,-3\]
**Output:** \[2,-3,4\]
**Example 2:**
**Input:** root = \[5,2,-5\]
**Output:** \[2\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
| null |
Hash Table,Tree,Depth-First Search,Binary Tree
|
Medium
|
572,2126
|
1,202 |
so for this problem we're given an input string and an array of pairs where each pair is an index in the string and the requirement that we need is to return the smallest string possible that can be changed to after using the swaps and the way we swap is using the pairs that were given in the area of pairs so for an example here if we were given the string dc ab we know that this is 0 index so it's going to be zero one two three and the pairs that we're given is zero three one and two and then we know we can swap the d and b and we can also swap c and a so once we do that uh we know we have to swap zero and three since b is smaller than d so the first swap is going to look like this and similarly we know we have to swap a and c since a is smaller than c so the next swap is gonna look like this and we can't swap um anymore so this ends up being the smallest string that we can return and we just return this so whenever there's a something like a pair array that relates to the inputs like in this case it's almost always that we could use some sort of graph like data structure here because what this ends up being is these are sort of like edges in the graph so really it almost always works out that way so i guess what i'm going to try to do is sort of work backwards from like what's an expected like what's the final state for the data structure that we could use here that would be able to give us a solution so in this scenario we can think of it something like this we want to end up with a data structure that we could have uh that has like an entry like so we know that zero these are all the components that we can swap with the zeroth element so we can swap it with itself we can swap it with the third element and for the first element in the string we want to know okay we can swap it with the first element we can swap it with itself or we can swap it with the second element so this might quickly look like a dictionary to you and that's right that's because it is and the reason why having some sort of state like this would be helpful for us is what we could do is we can grab each value in this dictionary and simply sort based sort the characters based on the indices here so we have this sorted in this scenario as 0 and 3. and we can grab the zeroth elements which is going to be d in the third element which is going to be b from our string and we sort it to get b d and what that looks like is essentially we did a swap and we're allowed to do a swap because we know that this dictionary held the values for all the elements that can be swapped so once we do that we can sort of merge it together with the value that we have here which is zero and three and once we merge it together we can sort of do something like this so b goes into the zeroth index in the string and d goes into the third index in the string and similarly we can do this for the second element so for one and two we're going to start off with the original string which is c and a once we sort these characters we end up with a and c and merging it with the value in the dictionary which is one and two we're going to do a similar approach where a goes into the first element in the string and c goes into the second element so what this ends up being is it if we have like an empty array of four elements since we've calculated the b would go into the first element it's going to look like b like this and d goes into the third a goes into the first and c goes into the second and that ends up building the final string that we're looking for where it's the smallest possible string i just realized the right side is a bit cut off but essentially this is what's good it's going to look like hope that was already clear from what i was talking about here uh so what can we do to end up with like a dictionary that looks like this one way that we can do it is to use the union find where we start off essentially with an array of parent nodes where each element is its own parent so in this case we start off with the array uh since we have four elements each element is its own parent so it's essentially zero one two three and that means like zero is its own parent one is its own parent two is its own parent and three is its own parent and what we can do is we can use the pair that we're given to run a union on both of them so for example once we do a union of zero and three we essentially have the uh the way this would look like in the appearance array is it would look like this zero is its own parent one is its own parent two as its own parent but then we did a union on zero and three so for the third element zero is its actual parent now and similarly once we do union one and two it's gonna run a similar algorithm where one is its own parent and i'm just arbitrarily choosing that the left element is gonna be the parent and for the second element one is it's gonna be its parent and zero is the parent since we already did union 0 and 3. so once we do that you can sort of see how this is going to relate to our dictionary that we defined up here we can already see the keys 0 and 1 and the values we're going to be able to grab that using the find algorithm and how we could do that is once we iterate through every element in the parent here we can simply run a find on each element so since we know that this is uh let me just clear things up here so we're gonna have a parent array that ends like this so we know this is zero index one index two three and once we run a find on zero we know that zero is its own parent so we return 0 for that and we have a dictionary uh it's going to end up very similar to what we defined up there this starts with 0 and it has a value of 0 first once we run a find on one is its own parent in this case it's gonna have one first and for the second one we find that one is its parent for the second element so we actually build it like so and for the third one the third element zero is its parent so in the dictionary the key with zero it's gonna have three and once we end up with this final dictionary we can simply run the algorithm that we discussed here to get the final result i hope that kind of made sense i think the toughest part of this question is just making figuring out how to write the union find algorithm but do another video that goes into detail on how that works but for now using this let's see how we can code this up so as we mentioned we need an array for the parents and it's going to start off with just each element being its own appearance for each element in the string so that's going to start like so and we can just start with the boilerplate for the union and find we're going to need a union function and a find function and again if this doesn't make sense once you have a solid understanding of how union find works reading this is super simple and for the union we always want to find the root element like which is the parent for x the parent for y and if they're not the same then we know we can connect them together p of y is equal to p of x p x and once we have that let's quickly go through each pair and run a union on them as we discussed and let's just print the final parent array just to make sure that everything looks good expect that to look like how we had it initially which is 0 1 0. looks like we miss i mistyped this so it's a py here instead and running this gives us what we'd expect now in this case we in this step now we want to build the actual dictionary that's going to hold it hold the structure that we can iterate over so in python we can do a default dictionary which essentially means whatever key you add it's just going to default to an empty array so you can keep appending to that array so in this case we want to iterate over each element and its index in the parent array and we want to add this to the dictionary so we said earlier we want to find the element's parent and we essentially add the index so that we end up with a structure similar to what we discussed which is going to be this and let's just quickly make sure that's expected we have zero three one and two and finally we can just run the algorithm that goes through each of the keys you want to get the character list and the let's start off by getting the index list which is essentially just the value in the dictionary and the character list using that index list would be each element in the string for i in index list and this is the important part is we want to sort this list for the characters we don't necessarily need to sort this because we already let me actually show the cursor so that it's easier to follow so we don't necessarily need to sort this list because we already sorted it's already sorted here since we iterate this dictionary in order but in this case now we can use the python zip function so that we can build the resulting string and what zip is going to do for us is uh let's run this one by one and this like for the first iteration we're going to have the index list being 0 3 the character list being after we sort it's going to be bd and once we zip it's going to be 0b to the array of 0b then 3 d and that tells us okay for the resulting string we can add it in the zeroth uh spot we can add b and once that goes through each element in the dictionary we end up with a string that we need and we just need to have a list of the string itself in this variable that we're turning and over here we just need to join it so we can return the string itself once we run that and there you have it we get the expected results and this is how we can solve the smallest strings with swaps as for the union find i can go into more in depth but i wanted to keep this video as short as possible but once we understand how this works it's very simple to incorporate it in a lot of graph questions
|
Smallest String With Swaps
|
palindrome-removal
|
You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be changed to after using the swaps.
**Example 1:**
**Input:** s = "dcab ", pairs = \[\[0,3\],\[1,2\]\]
**Output:** "bacd "
**Explaination:**
Swap s\[0\] and s\[3\], s = "bcad "
Swap s\[1\] and s\[2\], s = "bacd "
**Example 2:**
**Input:** s = "dcab ", pairs = \[\[0,3\],\[1,2\],\[0,2\]\]
**Output:** "abcd "
**Explaination:**
Swap s\[0\] and s\[3\], s = "bcad "
Swap s\[0\] and s\[2\], s = "acbd "
Swap s\[1\] and s\[2\], s = "abcd "
**Example 3:**
**Input:** s = "cba ", pairs = \[\[0,1\],\[1,2\]\]
**Output:** "abc "
**Explaination:**
Swap s\[0\] and s\[1\], s = "bca "
Swap s\[1\] and s\[2\], s = "bac "
Swap s\[0\] and s\[1\], s = "abc "
**Constraints:**
* `1 <= s.length <= 10^5`
* `0 <= pairs.length <= 10^5`
* `0 <= pairs[i][0], pairs[i][1] < s.length`
* `s` only contains lower case English letters.
|
Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too difficult to deduce.
|
Array,Dynamic Programming
|
Hard
| null |
66 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 66 plus 1. you are given a large integer represented as an integer array digits where each digits of i is the ith digit of the integer the digits are ordered from the most significant to least significant in left to right order the large integer does not contain any leading zeros increment the large integer by one and return the resulting array of digits so if we look at an example we're given the digits 2 1 2 3 and we should return 1 to 4 why well we add 1 to our digits here so that would simply be you know incrementing this three to a four which is how they got you know one two four so that one's quite simple but let's look at another example if we're given the digit nine well what happens here we need to return one zero why is that well if we add 1 to this 9 then you know it becomes 10 but obviously we can't have 10 in a single slot the 1 needs to go to the next position and the 0 needs to stay at the current index so we need to carry over the one and add it to the next value here there is no next value so we simply have to insert a one at the beginning of the array but if there was another one so let's just say we had the value nine right what would happen here well we add a one to this nine and it becomes ten right and we recall that we need to carry over the one now so we have nine zero and we still have to carry over the one so now we have to add a one here as well so this becomes ten also so now we're going to have nine zero we have to carry over the one and again we do the same so we're gonna have zero but remember now we have the one carried over so we have to insert a one in the beginning and therefore we get our answer of one thousand right because nine plus one is a thousand so that's the algorithm that we want to do essentially uh if the current digit here on the you know on the left or sorry the rightmost digit here is less than nine then all we have to do is add one to this and then return you know whatever the array is and we're done it's quite simple the only problem is when this number equals to nine because that forces us to make it zero and then deal with carrying over a one to the next one and then if this one's also nine then we have to keep going so we just have to keep track of the carry and if you've seen my problem on adding strings where we essentially do the same thing um very similar and then we're adding strings and then we have to deal with the carry we're going to do the same thing here except instead of initializing carry to zero carry is going to be one in the beginning and what we want to do is essentially we're gonna have an index i starting at the end of the array and we're gonna say you know array of i you know plus the carry right so that's gonna be plus one or i'll just write it out i'll get this i here plus carry is what we want to do right and if this is greater than or equal to 10 then what we want to do is you know keep the zero and then the carry has to continue forward so that's the algorithm that we want to use hopefully that's clear if not once you see the code you'll realize exactly what we're doing and it's super simple um we just need to make sure that we're doing the right thing uh with the carry and that you know if we're 10 or greater then we just want to keep the zero and then carry over the one and keep doing the addition and in the case that we've processed the entirety of the array and we still have a carry then we have to insert that one or whatever the carry is at the beginning so let's do that and we'll go over to the editor and write the code for this so i'll see you there we're back in the code editor now let's write the code remember that the first thing that we need to do is set up our carry variable because this is going to represent what we need to add to the next iteration if we have a carry so the initial value of carry is going to be set equal to 1. that way when we process the very first index we can just add the one that we're supposed to add because remember this problem is about adding a 1. so we're going to add that carry and we're going to continue going from right to left through our digits if we had a um you know a sum that was greater than 10 greater than or equal to 10 because that means that we have to carry over a one to the next level so let's set up our i pointer so we're going to say i equals to len you know digits minus one and we're going to say while i greater than or equal to zero because remember we're going from right to left we're going to say that the current sum is going to be whatever digits of i is plus the carry and we're going to say that you know digits of i is going to equal to the current value that we just calculated modulo 10 so this will basically if it's greater than 10 we'll keep just the ones element and if it's less than 10 we'll just keep whatever the value is because modulo 10 will just return us the value if it's actually less than 10. so now what we can do is calculate the carry if we still have one so we're going to say carry equals to the current sum that we just calculated um integer divided by 10. so this will tell us you know the tens position of our values so for example if you have something like 11 integer dividing will give us the one that we need to carry over at this point if we don't have a carry um we're done we've already added our one and we don't need to do anything more so we can say if not carry we can simply break out of this loop we don't need to go any further if we do have a carry what we need to do is we need to decrement our eye and then go to the next digit that we need to add our carry for so this is you remember if the case was like 999 obviously we add the zero to the first nine it becomes sorry we add the one to the nine it becomes a ten so we make it a zero and then the one carries over and then we have to add it to the next line this becomes a zero we have a one we have to add it to this one it becomes a zero and then we have to add the one at the very end so we're gonna do that until you know we get to a point where we don't have a carry anymore and then we can stop if we get through the entirety of our while loop and at the end we still have a carry that was that case with the 999 where we just need to insert a 1 at the beginning of our digits and we should have our answer so we're going to say if carry so basically if carry is non-zero carry so basically if carry is non-zero carry so basically if carry is non-zero we're going to say digits dot insert 0 and carry so and then we can simply return digits and that should be our solution let's just submit it make sure that it works and it does cool so what is the run time complexity of our solution well in the worst case you know we would have something like 999 where we need to go over the entire digits from right to left to process this and do the summation and then we're also going to have a carry at the very end which means that we have to insert a 1 at the beginning of this solution right because 999 plus one equals a thousand so we're gonna have zero in our digits and then since we have a carry after our while loop ends we'll have this one and remember that inserting something uh into an array at any point that isn't the last element is actually going to be a big o of n operation so we're bounded by big o of n on the time space complexity wise um it's going to be big o of 1 because we're not actually defining any space we're just modifying digits in place um so that part's fine uh i guess um it could be big o of n if you if we're in this case carry where essentially we have to insert one and then basically you're kind of just copying the array in order to insert it so it could actually be big o of n here in the case that you do the carry although i'm not sure because we're not technically defining a new data structure it might i think it will happen in place so i want to say that it's big o of one on the space although i could slightly be wrong on that and it's big o of n but i think it's going to be a constant space solution anyway that's going to be your solution to this problem as you can see it's a relatively straightforward one if you've seen my other videos on how to do you know adding string uh ones or adding binary uh it's basically the same idea we're just going from right to left and we still have this pattern of like cur modulo 10 and then the carry is you know the current sum uh integer divided by 10 and you're just going through the um the digits from left to right so pretty standard pattern you see this a lot on leak code so definitely one to know this is one of the easier problems to kind of get the hang of it and then you can use it in more complex ones so if you enjoyed this video please leave a like comment subscribe let me know if there's any videos you'd like me to make topics you'd like me to cover or just general interview tips um please leave them in the comment section below i'll be happy to get back to you i just need to know what you guys want to see and i'll make those videos for you guys otherwise in the meantime happy elite coding and bye
|
Plus One
|
plus-one
|
You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.
Increment the large integer by one and return _the resulting array of digits_.
**Example 1:**
**Input:** digits = \[1,2,3\]
**Output:** \[1,2,4\]
**Explanation:** The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be \[1,2,4\].
**Example 2:**
**Input:** digits = \[4,3,2,1\]
**Output:** \[4,3,2,2\]
**Explanation:** The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be \[4,3,2,2\].
**Example 3:**
**Input:** digits = \[9\]
**Output:** \[1,0\]
**Explanation:** The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be \[1,0\].
**Constraints:**
* `1 <= digits.length <= 100`
* `0 <= digits[i] <= 9`
* `digits` does not contain any leading `0`'s.
| null |
Array,Math
|
Easy
|
43,67,369,1031
|
239 |
That Welcome To My YouTube Channel Today Will See How To Place It Means To Technical Problem That Don't Know What Medical Protection Is Bill Planning For Loan Tours Great Detail My Technical Interview Questions For People And Well-Wishers Been Spreading In To Approach Well-Wishers Been Spreading In To Approach Well-Wishers Been Spreading In To Approach If You From Scratch Practice Name Problem And Will Finally Bluetooth Setting Metro Technik 3000 Something New To Identify And Mental Problem Can Be Solved By Tuning Sliding Window Technique On This And Point Se Tiffin Almost All The Questions For Wedding Indore But As Way No Exception Samay Share Na Network Problem description number one click was 1/2 inch return maximum sliding was 1/2 inch return maximum sliding was 1/2 inch return maximum sliding window gold electronic question for example 151 Hey and click subscribe button on the side and subscribe my channel doo Do Subscribe And Listen Let's Move To The Point That Should Be Brot To Sab Log Chor Ban Nahi To Kuch Positive And They Will Try To Watch Minute Of Science And You Will Find The Maximum Element In The Twin Sons Were Pushed To the maximum element in are sona play list me kinare sincere bhi hai pet element and questions page no personal chat start the length of the giver na re minus plus one to three liye subscribe minus plus minus one hai question mantu Leo Joint Maximum Element In Front Of 2016 Subscribe To This Channel Like And Subscribe To Torch Light Was Not Tried To Submit Code Ya Yuvak subscribe and subscribe the Channel Please subscribe and subscribe Stamp And Why Dispersing Proposal This Specific Lots Of Medicinal Method With Distinct Presidents Of Cost And Lost From Last Remove Subscribe Inter College Of The First Subscribe Like Comment subscribe Video then subscribe to the Page if you liked The Video then subscribe to the Lord You Have Willpower Element Adverbs of You And Insult Greater Element Position But In The Standing Labs Of The Giver Simply In The Current Index In The Land Of The Lambs subscribe and subscribe the Channel And subscribe The Amazing Element Don't Forget To Subscribe 1201 Electrification In This Album Is Greater Than Any Of The Elements In The Sense Greater Than 250 Lage Dilli Does For Nice and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to Loot Na Hussain Pyaar Online Text 300 Years In More 232 Subscribe Now To Receive New Updates Subscribe Who Is Better Than Life Will Remove Intact's Weakness Why And Events At Index Point You Can Increment आप subscribe to the Page if you liked The Video then subscribe to The Amazing spider-man 2 * More Quota Ray Nave let's move to the point he commented on record in very simple manner so that you can understand very easy water fall co difficulties and the best country from Tiffany of the club will be the issue of direct return paper of science and minus plus one and activists to Interior Element Na That Tweet Over All Dirt From Equal To Zero To Equal To One Minus One In The First Verification Ride Animated One You Must Be Current Window Gift Download The Current Window PM Delhi Mein Indian Oil That Back Is The Value Of The Current Indices Present last validate your father and after its controlled and satisfying close loop condition in third element and front of dispute in directory continue this procedure for all elements and after doing this Vikram of the dog and finally returned from back side na latest close do chanod sample Test Cassette Write Name Strive To Submit Code Life Is What Is The Space Complexity Of Algorithm Fix Figure Of And What Is The Time Complexity Of Algorithm In These Big Toys Between Element Support And Remote One Should Unite Video Please Friends Like Button Has 300 Grams In The video witch plans
|
Sliding Window Maximum
|
sliding-window-maximum
|
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the max sliding window_.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[3,3,5,5,6,7\]
**Explanation:**
Window position Max
--------------- -----
\[1 3 -1\] -3 5 3 6 7 **3**
1 \[3 -1 -3\] 5 3 6 7 **3**
1 3 \[-1 -3 5\] 3 6 7 ** 5**
1 3 -1 \[-3 5 3\] 6 7 **5**
1 3 -1 -3 \[5 3 6\] 7 **6**
1 3 -1 -3 5 \[3 6 7\] **7**
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `1 <= k <= nums.length`
|
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
76,155,159,265,1814
|
920 |
hello everyone welcome back here is when I'm saying today we are tackling an exciting political problem number 920 number of music played so this problem is rated as hard uh but we will try to solve it so our mission is to determine the number of unique playlists we can create given certain conditions so this condition makes this problem a fascinating one to solve and the code for various languages will be in the description below so make sure to check it out so let's start by understanding the problem statement we have music player with and different songs and we are going on a trip and we want to listen to go number uh during our journey however we want to avoid a burden so we will create a playlist with a couple of rules so every song is played at least once and the song can only be replayed if key order song have been paid given end goals and key our task is to return the number of possible playlists that we can create since the answer can be very large we will return it module of 10 to the power of 9. plus seven so to illustrate uh let's consider a couple of examples so if n is free goal is free and key is one and the output would be six because there are six possibilities so one two three uh three one three two uh two one three two three one uh three one two and three to one and uh if our n is two and go is 3 but key is zero we can have also six a playlist but the possibilities are different so for example we have one two so uh because K is zero we have one after one and same for example two one or one uh two cases as we don't have uh houses between uh songs Okay so let's dive into implementation so this problem can be cracked using dynamic programming a powerful technique that allows us to break a complex parallel into a simpler sub problems and our dynamic programming solution is based on a 2d table DP where dpij stands for the number of playlists of length I weave J being unique song so we use the modular operation tend to put the power of 9 plus 7 to avoid overflows and we will use uh also a special trick to optimize the memory so we will use I modulo 2 and also I minus 1 model 2 and in our DP table so this is a memory optimization technique called rolling array or a sliding window so since our current state only depends on the previous state we don't need to store all the steps so we only need a two row a DP table so one row for the current state I and one row for the previous state I minus 1 and by using a i modulo 2 we ensure that it always map to either 0 or 1 effectively keeping our deep table within just two rows so now let's start implementing and I will explain step by step so modulo int to the power 9 plus 7 DP 0 4. in range and plus one or in range of 2 and dp00 will be one-fifth so uh one-fifth so uh one-fifth so uh we first initialize our DP table with zeros and the size of the table is two times n plus one and we'll also set DP 0 to 1 since there is one way to have a playlist of length 0 with 0 unique songs so which is an empty place so next we will populate our DP table row by row and our goal so is to make outer loop Traverse from 1 to our goal Okay so or I in range 1 to goal plus one and then DP I modulo zero and 4 J in range one minimum i n plus one okay so inside the outer loop we first set DPI module or two zero to zero so this implies there are zero ways to create a playlist of length I uh with zero unique songs then uh the inner loop Travers from 1 to minimum of I and N and inside the inner loop we will first calculate the case where the playlist add a new song to our playlist so DPI module.2 j d p i minus 1 modulo 2 so DPI module.2 j d p i minus 1 modulo 2 so DPI module.2 j d p i minus 1 modulo 2 J minus one n minus J minus 1 modular modulus and the number of ways to do this is DP I minus 1 modulo 2 J minus 1 times n minus D minus 1. as we are adding just one of the new song not yet included in our playlist and then if J is greater than key we also consider the case where we add an old song and the number of ways is just DP I minus 1 modulo 2. from J times J minus K as we are adding one of the old song that hasn't been played in the last key song as we are allowed to use key so if J greater than key then DP I modulo 2J will be DP I modulo 2 J DP I minus 1 modulo 2 J minus key modular mode so yeah and in this last part so dpij modulo 2 of J times uh J minus K and we are adding one of the old song that we didn't add and finally what we do we return DP of goal modulo 2 n which represent the number of possible playlists of length of gold with n unique song so let's return DP go module 2 and this is our implementation and let's run it to verify everything work so yep all good so for and free Go free q1 output is six so oh it's good so now let's submit it to verify everything work so yeah I hope it's working so we beat uh 89 with respect to uh runtime and also 81 with respect to memory so uh all good and yeah so this is implementation and there you have it we have successfully solved lead code daily challenge 920 number of music playlists using dynamic programming so dynamic programming might seem uh part at first but once you get the hang of it become a great tool in your coding toolbox so I hope you found this video uh insightful and if you did please give it a thumbs up and subscribe for more coding problem solution uh tutorial explanation and much more and don't forget to check out the code in other languages in the description below and remember uh keep practicing stay motivated never stop learning happy coding and see you next time
|
Number of Music Playlists
|
uncommon-words-from-two-sentences
|
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
* Every song is played **at least once**.
* A song can only be played again only if `k` other songs have been played.
Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 3, goal = 3, k = 1
**Output:** 6
**Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\].
**Example 2:**
**Input:** n = 2, goal = 3, k = 0
**Output:** 6
**Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\].
**Example 3:**
**Input:** n = 2, goal = 3, k = 1
**Output:** 2
**Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\].
**Constraints:**
* `0 <= k < n <= goal <= 100`
| null |
Hash Table,String
|
Easy
|
2190
|
1,869 |
okay let's do Lee code 1869 longer contiguous segments of ones and zeros in JavaScript what we're doing here is we're looking through this input string and we're seeing are the ones in a row longer than the zeros that are all in a row so then we want to return true or false from that so uh this one there's more zeros then one so we're in return false for that and this one will return true because there's uh two ones in a row and there's only one zero in a row okay let's uh let's code this out so we're gonna need a couple of uh storage variables here to keep track of things and we want to set them just to be zero to start with and then we're going to use a for Loop to Loop through this string and we're going to use a couple of if checks inside the for Loop to check to see if we're a one or a zero and we'll add logic from there so let's code out this for Loop thank you and one thing I just noticed I was typing out window n we actually aren't really using a sliding window here so we don't need to uh we don't need to use that we can just use I there we go Okay so if I equals 1 we're going to do some logic else if I equals zero we're going to do some other logic so what we want to do in here uh let's start out by doing some console logs in here so I can show you let's do this right here we'll do like this we'll go s I okay then we want to grab this guy throw that in there so we can take a look uh and see at how this is going to operate here so let's run this it's going to give us a fail because we're not actually returning or doing anything we're just doing some logs here so you see one zero one okay that's working great what we want to do when we find an eyes we want to add to the count right so we're going to go count plus equals one and that's count one and then down here we want to do uh count zero plus equals one so we're going to increment the counts every time we go through so what we need to do is we need to remember this is like the trick of this when we're going through this and we're adding these counts we need to check the max of the count and the max length that we're storing here we're going to add up a count and when we run out of consecutive numbers we're going to push that count or I should say store that count in the max length whatever that max length is then what we're going to do is we're going to reset the count to zero but we don't want to do that in the wrong spot in here so when we run into a situation where we'll say in this case we have 1101 let's change this 1101 so to run through this for Loop we run into a situation where we've run through one two Loops we run into the third loop we're at zero now so we've incremented the count one twice right count one is now two what we're going to do is we're going to end up hitting this else if right here so s i is zero right here what we're going to do is we're going to go count zero plus one then what we need to do is we need to check the max length of the one right here because we're in the other section of the lcf and we have now run out of ones so what we want to do is we want to check the max length of the one of the count of the ones we can use math.max for that math.max for that math.max for that and we'll see is the count of the ones bigger than the current max length of the ones and we'll just assign whatever that is to Mac max length one then what we need to do after we reassigned that because we've run out of ones and we're now looking at a zero we have to reset the count one to zero so at this point we've come through here we said okay what's bigger max length one which is zero or count one which is two and assign that to Max length one so now that will become 2 and count one would become zero and when we come back through this loop again we're going to do the same logic right here just checking max length zero and count zero and that's pretty much it so let's grab these two here and we're going to change this to zero that to zero and then the other thing to note that's kind of tricky is that when we exit this Loop one of these two will not have completely run so when we hit this one right now s i equals one will do all this logic we'll never hit the else F which means we never check the mat the math.max we never check the mat the math.max we never check the mat the math.max that's down here for max length one so we need to check that after we've exited uh all these this if else logic here before we exit the loop so what we just need to do here is we need to grab these throw them in there can move them over a little bit so now we've set these Max lengths correctly here and all we need to do is return max length one is if it's greater or not of the versus the max length of zero and we're supposed to return true uh if this one's bigger we're basically seeing are there more ones than zeros just to recap that so let's run this all right we have successful test cases there we submit it make sure I don't have any typos okay and accepted um I usually don't worry about this stuff in my videos and also we have a bunch of console logs that's going to affect our speed and I'll leave this on the screen so you can view it and that's 1869 longer contiguous segments of ones than zeros in JavaScript
|
Longer Contiguous Segments of Ones than Zeros
|
longer-contiguous-segments-of-ones-than-zeros
|
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_.
* For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest continuous segment of `0`s has length `3`.
Note that if there are no `0`'s, then the longest continuous segment of `0`'s is considered to have a length `0`. The same applies if there is no `1`'s.
**Example 1:**
**Input:** s = "1101 "
**Output:** true
**Explanation:**
The longest contiguous segment of 1s has length 2: "1101 "
The longest contiguous segment of 0s has length 1: "1101 "
The segment of 1s is longer, so return true.
**Example 2:**
**Input:** s = "111000 "
**Output:** false
**Explanation:**
The longest contiguous segment of 1s has length 3: "111000 "
The longest contiguous segment of 0s has length 3: "111000 "
The segment of 1s is not longer, so return false.
**Example 3:**
**Input:** s = "110100010 "
**Output:** false
**Explanation:**
The longest contiguous segment of 1s has length 2: "110100010 "
The longest contiguous segment of 0s has length 3: "110100010 "
The segment of 1s is not longer, so return false.
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
| null | null |
Easy
| null |
39 |
Previous Welcome to My Channel Short Today Will Start With and Backtracking Foundations Combination Series and the First Problem Hui to This Thirty-nine Combination Samudra to This Thirty-nine Combination Samudra to This Thirty-nine Combination Samudra Appointment Se 10 Gives Enough Heat in Teachers Candidates Need to Get Into the Target Return List of All Unique Combinations of Candidates Where Frozen Number Even Target Human Returns The Combinations In It The Same Number Also Swelling From Candidates Unlimited Number Of Times Two Combinations Of Unique Battle Frequency Of At Least One Of The Number Is Different Is Guaranteed The Number Of Units Combinations Tenth Up To Get So Stand 150 Combinations For The Given In Food Subsidy Se In Giving Nethya Ne Work Number To Three 6 7 8 And Give One Target Sit To Find All The Communications Possible By Using These Numbers Which Will Have To 7 Cities Then Check To Three Layer Together For Sit And Sit Alone Jobs For Win7 Surandisanh To If Combination Possible Using These Numbers Which Will Sum Of Two 70 To Return This Ajay Answer Second Example Se 235 And Attractive Seth Show The Missions Fast Bowler Court Which Can Take Ur Right The Tourism 2812 Days To Three Little Also Contribute To 8 Or Else Way Can Take Three Love Affair Truth Will Do It Surya To Find All This Combination Is A That He Is Now Tourist And Target Number And Have To Use This Number Unlimited Number Of Times And Where To Find Such Special Worth Backtracking Problem Oil Check How They Can Solve Question It Will Ask How They Can Solve This Kind Of Problem Will Obviously Is Back Tracking Mins But Bluetooth No Like How To Use Back Tracking And How To Create A Cream Records In This Series Same Line Problem Liberation Vacancy For The Time And - Problem Liberation Vacancy For The Time And - Problem Liberation Vacancy For The Time And - Tweet Clear Back Water Supply And What Time Travel Festivals And Problems Like This Hair Oil How To Create Some Target Bhailu The Time It's Good Ek Hi Ling To Shot This Is First Widows Se Award Target Is Five Instead Of 9 7 The Time This Thought This is at least to know the best and the result will be lying between this is the boy Duke Hello can only create 5th to my daughter in law greater than five has not been used for it so they can stop to author John is for some time I don't have tried Every Combination Slide Swift 600 Will Get Some Advantage Sovan Singh Sadhe Left To Find Such Kind Of Things That Now You Will Talk About The Akshar Trick Reaction So What We Can Do Is Science First Battle Number 21 Suggestion Number One Day How Many Targets Is Remedy Seven - 25 OK Day How Many Targets Is Remedy Seven - 25 OK Day How Many Targets Is Remedy Seven - 25 OK Let's Get Another To Do S One Of Which Backem Two Plus Two For You Have Still 361 Andar 2 And Came Chhe In Total Steve One To Flirt 1021 Vikram Seth Means The Tribune Targets Udhar Twin Tower Result 100 Debt Solution News In Another To Is Not Possible So They Have To Think About Something Else From This Point Favorite Song Hair Tips And Grasshopper Benefits Using Too You Can See This Going Beyond The A Study Means Using 360 Updates Reviews And Should Not Go To The Truth Should Be Stretched Hair Less Hair You Have Choice Have Already Used 30 News A Fear Because They All Love You Too Good Night Subah Remaining Two Three 6 7 Stars Switch You Two Plus Three Lalit Vikram 700 Gram Tower First Answer Ajay Combination Remedies Two Plus Husband Right Nor From Where U Can Go Ahead With news6 But Not Required To Answer From History 123 Click Like Button Now Liquid Number To Go Beyond Attributes Toe Stop Thumb Back Toe Flash Light Less Hair Oil Use To Accept news3 Right That Sweater Begum 5 Day Update Vigyan User Cpiyan But All Of Them Will Go Beyond The Result History Also Will Not Leave Group Starting With To And Unlimited Using The Thing Should Go To First Result Similar Thing 238 383 Lar Start R Journey Prati Vikram 634 283 Lottery Result 2018 Ki End From hair and needle controller tree because effects of this going beyond the result will obviously teach surveillance knowledge wisdom hair so I can add servi now we start the calculation for there city plus six going 961 which hair fall shift veri control one question also come in Your Mind Like His Wife Were Not Including To Hair Because When They Start With To Do You Have Option To Choose Between 360 Numbers Right To Food Grain To Hair Day You Will Get Prosperity Result So Let's Oil They Never Supported I'm Starting From To The Time Ooo have the option to choose from two to three 6 7 4 p.m. to three 6 7 4 p.m. to three 6 7 4 p.m. Starting From Three Live Option 223 6 7 Chapter One Rate 100 Feet Six Shabuddin Hue Options To Chus Between Educated Services 60 And 70 16120 Distributor Kand Ko Yeh Baingan Jo Hai To Start With 760 Just 6300 One Result Light Admit Card Royal Suite God Par Results Two Three Layer And 79 Will See How To Code Scanner Problem Light Sudhir One Function Given To Aadat Is Ghatol 17 16 List Of In Tears From And Punishment Output Slide Show Fear Without U All Guys 231 List Of Indian Andar List Of Centers 786 Points Really In Shirdi Sai Love You Too Short Dresses For Better Performance Night Software How To Define Your One Stop In Teachers Result Will Contain The Ultimate Result Day Year Old This Person Just Dua Add Hotspot Of This Candidate Spot Eastern Not Doing Enough To Call The fighter place with it's a three-day notice is a three-day notice is a three-day notice is ok so they have to define one in the third chord public boy davis torch light show hair inside this method how to write the body and dasharan function and win this tree this cold be done to have To Simple E-Return This Result The Answer Write The Thing Simple E-Return This Result The Answer Write The Thing Simple E-Return This Result The Answer Write The Thing Is That Parameters Subscribe This Candidates Are Doctor Drowned In Other Records These Directions Calculation In This Wednesday 10th Result Subscribe To What Is You To Forward Under This Target Fix Every Time You Please Check For My Current Running Length The Values Are For My Current Running Length The Values Are For My Current Running Length The Values Are Equal To The Target And Not So Here To Path Stargate Is Next Point Next To Specific Artist 2347 And It's An Order Form This 2381 List Of Interior Sites On Which You Hold Like Entrance Result Bihar To Keep All Happened In Third Experience To Remove From Date Of Jewel To In Wedding Backtracking 100 Robbers Who New Are List From That And Will Update On This Point Forward Lately Likely Stop Interior That It's Sewing Okay And One More Thing Minute Details From Where To Start Fennel And Other Late Hui How To Three Layer 6 And 7 Rate So When Will Start From To Life Term To When Will Do The Tree Information So Next Time Viewers 2367 10 But Will Start From Thriller Time Will Only War Number 67 They Will Start From six will only you 6 7 8 9 238 index position where to maintain sagar right show will pass one index position let's start listen 200 phone and here you will take it a gin viewers start white is used oil airplane mode main nachoon aa hear what you To is first call aa 2367 using between now and everyone for him will have to create the day factory so good night fall on here i surat to right to follow this year we will start from integer i equal to 0 0share viewers the start any time Passing on that now what we will do this tool kill the length of the candidate candidates for telling you day laddu i plus 9 may first job stuart the current number indore list ok net current number is this candidates is position current result is no it Is Holding Say To Do It Is The Meaning Of What Is My World Is 0 - New My World Is 0 - New My World Is 0 - New Delhi Out of 110 My New Target Navodaya Ko Forward And Want To Make The Face Check Anything New Laptop Not It's A New Target Is Greater Than 10000 Me and Ko at a Distance Vote UP Set Sumo Asli All Things Will Be Seen Only Through Parameters Wheel Chair That Shows Candidates Will Be Positive Result Target So Instant After Target You Have To Pass The New Target Fix Hunted 3D Just Now You Can Check For Five Times Tuesday Has Five New Target Tak How To Find History Of Skill Yes And Stop This A List Will Have To Pass The Cardamom Now Some Contact Us And It Will Start Things Not The My New Start Will Be That Bigg Boss Flex Late Say Next Time When It's On The Point 30 From Want To Start A New Tool Used Only 3 6 7 The Real Husband That And A Positive A Back Tracking Call Date Means From Where Ru Instituted After And So One Day We're Going Inside Like You This another 2 and next they are coming back and lag checking for the part of the tree condition only after this oil for this will have to remove it is well the new entry however they are making big boss view too often for the number emergency so how Can remove this and last element view to remove early morning list size - 1m size - 1m size - 1m ki naav hotel my best ke shloka hindi shri krishna will stop sleeping during enter in edifice call find my target is equal to zero find the right shot my answer right sleep in the Main Result Are I Have To Date Path Bus Result Saw Her One Thing You To Things 225 Reference Person Destroyer Reference Of The Previously Created List Show Will Create A New List Outfit Ok To That Hand Will Simply Write On That Nav Itni Ramdish Program It's Working For The Given In Photography Submit This Addition Working Listen If You Have Any Doubt I'll Show You All The Structure Of Side By Side City Then Check If You Don't See Social Side-By-Side In The Morning In The First Time Side-By-Side In The Morning In The First Time Side-By-Side In The Morning In The First Time Started Date For His Call For The Time Difficult To Start High School Means Zero Till The Length Devil's Dish Total Sapoch To Go For 2367 Everyone Another Everyone Individual Can Form A Tree Torn Shoes Doing Difficult In Between Morning Yourself War Next One It's Foreign Ministry First Setting Of The Combination Starting With To Dene Tourism Pathri Light So Acid This Decision Is Deficit At Women From To-Do List Will Keep On Women From To-Do List Will Keep On Women From To-Do List Will Keep On Growing And Seeking For Each And Every Solution Right Tomorrow Morning To You Doing Wedding Two Days In Next Level 100 Passing I Equal To Zero Hair Date Means That Aishwarya Starting From Two 10 Hum Option To Call Using 2367 Ok Subah First Date With Two And Which Two Same Thing With Two Three Way Can Go For The Same Thing 2nd Annual Summit Its Results Will Go Deep Into Vikram Seth Sudarshan Voice Call Apps How To Turn To cross this day toe come back and me to check and hadith root in this possible note pure it's two plus 3 vikram7 saw hair in this country and to get equal to zero size courier - singer get equal to zero size courier - singer get equal to zero size courier - singer target and going forward without you To elected as a result when we are collecting the result day were going and to plus 358 doing from this free leg in which can go further 67 birthday time was unfavorable v6 plus 280 a which from 18 moh it started with three leather call v83 top Vikram No Cord Co Shampoo For Hair Oil Safar Se Valid Option Co Ru Girls Ru Not Possible Love You Understand This Part Like Oil I Don't Drink Because Dating Sites Like Share And Now Going With Solution Floor But I Feel So Far As The Can Come Back And formed junction point where to find for the solution rate so hairy then check when you hear her into two plus two three four day war heart about adding another to instituted of 300 grams this part two plus two of four plus Vikram six and field hear you Not able to make 700 to come back but as we are maintaining a single list hair pack to remove decide times Friday in life but computer knowledge tight 12th edition and will welcome to three to that heard whenever we are coming out of this day the schools Will have to remove the last time today are moved into every month and comes a point when im getting new number history lendu this entry arindam list and vishwayudh got success in just 120 days where results were collected and what is the advantage of doing what year it is possible Because here you for the two plus three war results 7th to here from this to an option not going to each rate for six and here for 7th house of world its two plus two only giving result day obviously puja 6 7 minutes uber Result A Study Needle Note Such Target Switch Can Stop Group Using This Condition Is Neutral Kidney 120 Date To Go For Android Apps Call Me To That's The Thing They Achieve In Giving Dots I Hope You Understand Explosion Dadar Problem Simple 7052 Change We Logic Hair And Hair Day Milk Problems Vitamin Thanks for Watching A
|
Combination Sum
|
combination-sum
|
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40`
| null |
Array,Backtracking
|
Medium
|
17,40,77,216,254,377
|
21 |
welcome to leak codes blank read 75 where I'll be solving the top 75 lead code questions this questions called merge two sorted lists and we want to merge two sorted linked lists and return it as a new sorted list so basically this is a two-pointer solution we want to start at two-pointer solution we want to start at two-pointer solution we want to start at the heads of both linked list 1 and linked list 2 and just check to see which value is less if the value of 1 is less we'll add that to the next nodes value and then we'll increment the pointer on that linked list and repeat the loop while both linked 1 linked list 1 exists and linked to exists at the end of that loop once we are able to add the full linked list of one of them we'll just add whatever is left on the other linked list to our output so the tricky part here is getting that head to point to the right place but otherwise it's a pretty standard problem so let's start with our first some base cases like if linked 1 doesn't exist we just want to return linked l/2 right because there's return linked l/2 right because there's return linked l/2 right because there's no linked list on a 1 so we'll just return the head for L 2 and if not L 2 then we want to return L 1 so that's just some base conditions otherwise we want to create our loop right so while there's an L 1 and L 2 what do we want to check to see if linked ones value is less than linked to and otherwise the opposite is true linked tubes value is less than linked ones value then we're going to add that to our next list so first let's generate like something called current that's going to be our current node and how about a dummy pointer as well and this is to ensure that we could return the head later and I'll show you what's going on here in a little bit because at first it's a little confusing but I'm just going to generate a dummy pointer or dummy list node in the beginning so that we could create our new linked list so while L 1 and L 2 if ell ones value is less than L two's value what everyone do we want to add to the current next node L one right and now we want to increment our one pointer to the next and otherwise we're going to do the opposite when say turns out next equals l2 and l2 equals incremental two instead and to make sure that our pointer is also incremented we'll make that equal to X so once this is finished all we need to do then is make sure we add the rest of l1 and l2 depending on which one remains so if l1 then we'll just add to the current thought next equal to l1 and otherwise if l2 then we're gonna add to current on next equals l2 finally we want to return our head and luckily we have our dummy pointer but make sure point to next right because when we first begin this it's pointing to like a porn that doesn't actually exist on this linked list right we just created this empty node to begin with it's the one after that's actually gonna be the head so let's make sure that I didn't miss anything up okay so our test case looks good yeah let's submit that and there so that's my solution obviously the memory usage isn't ideal you might want to figure out a way to do it like in place and stuff but you know what like for my casein purposes I think this is totally fine solution so thank you
|
Merge Two Sorted Lists
|
merge-two-sorted-lists
|
You are given the heads of two sorted linked lists `list1` and `list2`.
Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.
Return _the head of the merged linked list_.
**Example 1:**
**Input:** list1 = \[1,2,4\], list2 = \[1,3,4\]
**Output:** \[1,1,2,3,4,4\]
**Example 2:**
**Input:** list1 = \[\], list2 = \[\]
**Output:** \[\]
**Example 3:**
**Input:** list1 = \[\], list2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in both lists is in the range `[0, 50]`.
* `-100 <= Node.val <= 100`
* Both `list1` and `list2` are sorted in **non-decreasing** order.
| null |
Linked List,Recursion
|
Easy
|
23,88,148,244,1774,2071
|
174 |
Hello Guys Today We Are Going To See Problem Cold Danger Game From Its Elements Let Me See The Problem First Give The Matrix 800 Likes And Tried To Bottom Corner Subscribe Points Subscribe My Channel I Will Get A Sort Of This To Financial Minimum Health Should Not be able to rescue the British rule it can only move to any point of time subscribe to have to govinda matrix and light bill also pregnant 1000 accessibility present time hu 200 initially in which tips knowledge in the problem night will represent 80 accessibility are not ask for Night Studio Inch Add This Point Without Disclosing This Helps 205 Weather In Right Direction And Gautam Direction That Also Access Point Time The Health Of Night Can Win So They Need To Take Some Initial Positive Number Communicate Positive Health And Candy Near Voice Of Solid Evidence To Reach At this point is so let's see how for this matrix delich so initially I will take help of night s 720 less hair 80508 vikram 572 not want to right direction that shell earthquake two sister two plus three 500 600 - 05-01-13 sister two plus three 500 600 - 05-01-13 sister two plus three 500 600 - 05-01-13 minimum Through which can here we will solve this problem using dynamic programming for practice You can solve this problem using decoration for the time complexity will be I so let's see how we can solve problem Share created AP matrix that city DPFI will store minimum Health required to move from dead cells if white is white this year that I need to pillar number 67 they can you from this cells to fight with the help morning positive and this point is to isi danger matrix - five percent danger matrix - five percent danger matrix - five percent no I will be at least 60 At The Rate Health Swimming Network10 Ki Wylachi And Budding Self Batidaar From Top And Beautiful Length Hai How To Fill Vishwa Ayush Required 6 - How To Fill Vishwa Ayush Required 6 - How To Fill Vishwa Ayush Required 6 - Unmarried 522 Maintain This Health Number Travels Field Se Losing Similarly For This Channel I Will Par 6 - Daily Speaker Channel I Will Par 6 - Daily Speaker Channel I Will Par 6 - Daily Speaker Health 281 Health A Improve And Move Forward A Visit To Find From Where They Can Maintain Minimum Health To Pure Cell Bissell Can Go Into Direction In This I Will Update Using One And Five How To Maintain One I Will Need One - - 10th How To Maintain One I Will Need One - - 10th How To Maintain One I Will Need One - - 10th Date Means at least 11-day share so that they can come to Date Means at least 11-day share so that they can come to Date Means at least 11-day share so that they can come to one and five 125 I will need at least five - - 0 five - - 0 five - - 0 that petrol Vikram Team so I will take minimum of the two and that similarly they can feel whole matrix from this and P 500 Answer is A Hua Hai So Let's Seedha Cold Have Declared AP Matrix M Feeling Right Most Bottom Corner Use This Line Not Feeling Last Column in Last Row of Baroda Hai One Direction To Come From 10am Feeling Press The Matrix Hair Ki Sugar Time Complexity of Dissolution Belief and Square
|
Dungeon Game
|
dungeon-game
|
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step.
Return _the knight's minimum initial health so that he can rescue the princess_.
**Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
**Example 1:**
**Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\]
**Output:** 7
**Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
**Example 2:**
**Input:** dungeon = \[\[0\]\]
**Output:** 1
**Constraints:**
* `m == dungeon.length`
* `n == dungeon[i].length`
* `1 <= m, n <= 200`
* `-1000 <= dungeon[i][j] <= 1000`
| null |
Array,Dynamic Programming,Matrix
|
Hard
|
62,64,741,2354
|
856 |
Hello Win World Cup 2015 Four Inch And Apologies For Missing After Few Days Setting Perspective Unfortunately He Has Not Well Today I Am Feeling Button The Video then subscribe to subscribe this Video plz subscribe and subscribe to subscribe that and they never be seen at That Time From String Were Stranded 22181 More Subscribe Luta Doon Jo Alarm Jo Side Slideshow Hain Lemon Juice Ek Pan Hai And Click Subscribe Button On Left Side And Subscribe To My Channel Liked The Video Then Subscribe To The Amazing Hai Ko Selected This Cream And Use This And Gives A Specific Playlist Rhythms Something Like This And Avoid Subscribe One Plus One To Take Another Similar To What Is The Score Of District Subscription Lata Mangeshkar's Dhai Anda Gram 500 I Year Old Traveling In Closed By Foreigners Opening And Closing Mandsaur And School Difficult Times Square Of The Inner Strength Dos And Subscribe Button Subscribe To I Want With A Case Where In The String Something Like This Per Apne Baikunth Recording Rocket Seerwali But Even In The Further Substring d2h Is To-Do List Subscribe Is To-Do List Subscribe Is To-Do List Subscribe Must Aa Ki Aaj Bhi Bollywood Video Stock And With General Type String Subscribe To This Select Processes To Bring Back At Preventing Gold And Whitening Difficult To Be With U Ke Din What Is The Next Elements Element Of But Remember Your Willpower Letters Video Please Subscribe Middle Class 10th Have Experience 2DS File Decoration And A Greater Opening Of Its Opening And Do n't Want To Talk Fuel President Understand What Is COD Pull Element Subscribe Like Share Thursday Don't Forget To Subscribe And Subscribe 210 Tak Sambhav Vikram Something Like This And Bring Back And Should Be Worn In Quest For Electronic 210 What Is That Looks Like And One Vihar To Cigarette Se Zila Id Wood Elements Of Obscuritism Remove 10 Way Subscribe Video Please Subscribe And Subscribe The Amazing And 0.9 Lut-Lut And Subscribe The Amazing And 0.9 Lut-Lut And Subscribe The Amazing And 0.9 Lut-Lut Will Remove Difficult Will Be That I was handed the ball to this image of my heart opening date of birth distance of the year two to two subscribe to and ping that point element hind sir time don't see a banquet sauvir one plus one the five districts of Bihar Desk Minutes of Mother in More Products subscribe to subscribe Video then subscribe to the Page if you liked The Video then New Delhi Will Be Amazed To Do And Border Distic Do Subscribe To In Stockport Tight Ring Hai Ko Speaker Chun New Stock Jo Alarm This Thank You Saad Aur K Ishwari Ban Fast Train Live Status Post Tractors Loop Control Printer Stock Of Distic On Loot Ki Naxalism Se Character Episode 518 Aaye End Time Stockpiles Paint E I Main Item Porn Element Superstar Dot Posts On That Contributed To Convert Into A String Not Wick Director Excel Has A Sense Of Security Deposit 21 Top Mother Can Enter The Stock And Let's Check Status Not Empty Subscribe Now To Do Subscribe To The Person Who Was Robbed By Robbers That SP Laut Is not empty stomach and not empty loot and tasty Dot pic ki roti question is not equal to Anup Anoop student mein chalenge tomato turn off science and value the limits of acid MP3 ki in naresh goyal chicken shop last hai loot wait dots leaf hai The ring wali hoon VPN small hai is contest read whatsapp morning aarti porn removing element and the time I don't know insomnia that different things with just the opening racket string with saffron removed from the distic and water will do willard universe on the table competition boss Want to the stock cafe day meaning it you a strip immodest rich and intermediate tree values for this simply 1008 one to the world with me to two that these nurse quickly volume of universe cars price eighth lift *must talk back cars price eighth lift *must talk back cars price eighth lift *must talk back door e want side There opulence and two strings of equal two and opening rockets fired this will simply art element yes thank you with sexual video and hydration over all elements will calculate school using water in the voice of paintings with a this is all for you time Rakesh not Imty will calculate us revolving elements from this thanks oo ai dsp dot cn oo loot hai next point sheel etc sects ke sva and vihar elements spring like this and stock play store 1kw 1.28 and you all elements of store 1kw 1.28 and you all elements of store 1kw 1.28 and you all elements of chronic and you will be able To reduce few lines on school co ki raksha in the formatted text that accepted what is the time complexity best drawing for kids with chords of anywhere and transport cylinder different and space complexity again with exactly to the order of in of the cases where bihar oil in Phase Number of 20 String Restriction on the Number of Single Balance Point subscribe to The Amazing Audio and Video Up
|
Score of Parentheses
|
consecutive-numbers-sum
|
Given a balanced parentheses string `s`, return _the **score** of the string_.
The **score** of a balanced parentheses string is based on the following rule:
* `"() "` has score `1`.
* `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings.
* `(A)` has score `2 * A`, where `A` is a balanced parentheses string.
**Example 1:**
**Input:** s = "() "
**Output:** 1
**Example 2:**
**Input:** s = "(()) "
**Output:** 2
**Example 3:**
**Input:** s = "()() "
**Output:** 2
**Constraints:**
* `2 <= s.length <= 50`
* `s` consists of only `'('` and `')'`.
* `s` is a balanced parentheses string.
| null |
Math,Enumeration
|
Hard
| null |
41 |
Examination is required, whether tobacco or code, Smallest positive way, Singh number is a very important question about the question which is talked about in the international media, a new kind of technique is going to be seen in this, some more different processes, we will discuss in this video, without any Delay, let's post this video, now let's come up with a question, give you a. Okay, in this situation, your nineties and in this it means that whatever may or may not happen, apart from this, there can also be negative numbers, now we will include this in this. Want to tell which is the smallest Club Scotland deposit machine number? For example, if you look at this one here, 12345 is true, okay, you consider zero as not positive, Himanshu from Next 9 News Room will not do it, okay Aman to 60 that we See, the bun is to is free, the whole fabric is in these were clip in till all here is the highest next is the smallest which is save the positive number educated we have vitamin six here the next which we will see is this one in this so I have this number 20 so 14 channels in it are closed, 3 - 20th can be watched and 10 closed, 3 - 20th can be watched and 10 closed, 3 - 20th can be watched and 10 minutes have been removed for text. In this, you ca n't even take a tempered glass and stress while passing time, let alone let it keep you from numbers. This was an example of having Christmas. All this is fine, so first of all we will approach your mind, care, make one hand smart, okay, then a container, that means where is the sperm problem, only we are going to do it quickly, yes Malaika, darkness means that we should store the frequency of each number. Made it a career, here meeting with inauspicious people seemed like a way to collect, you must be storing it mute, then I will store it, 100 is two is for animal, now you must be saying by adding plus one to it that we should not do zero account. If everything remains then I will remain as a plus in your index. This is the tube. This is 485. We are doing it on 1, except that he grew up, here he turned down its volume, but you did not get anything, he kept it at the same free stop. I closed it and that number 90 will be mixed, then I will go in and do it quickly, okay again so that I can put it to the test and see that everything has been done on it. Yes, it means that the add here is fine, then I will check okay, it is not so, please return on time. Will give because I got the first number, the account is missing, we are trying to figure out what happened, whether the element is pregnant or not looking at the even negative numbers, I have to find the smallest positive, this is my house, I have to find the smallest positive. There is no need to include it, ok so it has crossed, there is a problem in the big support that I am using express piece, ok Mexico and if you are using it, then every child has got extra space, what can be the next approach, now we will take Let's dry it, we are at episode 1 inch, make it soft, fold it all, so what has happened to you - Bunty - you - Bunty - you - Bunty - 01, we will start trying in it, till I get positive, as if we get positive, then we will not see, we will start. Well, now you have got the next number, let's see whether it is there or not, if you are not there, don't worry, this is our machine number, it will be broken, what is the problem in making it fast, then the best 257 login can be generated and the many techniques which we had read, health. He keeps us in the mode of inquiry, so what Dalits want is that we keep using these things on which we create obstacles. Now we can take extra but if we can change, asking questions is a very important thing, we ca n't do it. Guru says that a little compulsion is needed, accused Rochak will work now, this will be the problem, apart from this, there is no other way to use speech without meaning and here I am not using this but it is technical but it is important to see. Whether I can plate it or not, what do we do in this, we travel through it all and whatever number comes, we go to that index and multiply it mentally - that is, we multiply it mentally - that is, we multiply it mentally - that is, we forgive it, that is the right way to remind. Have to get it done, this is two, this is three, this is the whole path, don't get confused, here we have stopped the index plus, even if the investment is not happening starting from biological number one, then Joint one is our general contradiction, husband is that but we are like ourselves. This is how we are doing this for us, we get this gram admission set up and those who are getting the number go to the index and give it to us - album playing to bandh urban par - - album playing to bandh urban par - - album playing to bandh urban par - Duplicate hai tu par maine han kar diya aur hai to floor par. Jayegi - blinded, if there floor par. Jayegi - blinded, if there floor par. Jayegi - blinded, if there is six, then there is six, if there is six, then there were women outside that house, that - multiplied were women outside that house, that - multiplied were women outside that house, that - multiplied that we should tower again, saw closed - 02 - Minister Language - Mother saw closed - 02 - Minister Language - Mother saw closed - 02 - Minister Language - Mother means passive a for it has been a center For education saw that negative is not positive it means that slippery leg cigarette tobacco SIM on 12345 we saw our smallest positive number one method of Sangh if you do it positive then we are not doing the problem which is most important meaning - we are appointing the meaning If you meaning - we are appointing the meaning If you meaning - we are appointing the meaning If you use it here, then you will subscribe, then check the number from which it is yours, if it has an index, then it is correct, but you will go to the next one and if you find this number is not in the soldier, we will return from there. What you have to do is that we have to make them equal, in this we will not minimize the negative numbers and zeros, plus these above are great, we will not calculate those numbers as well, we will withdraw from the ATM, one twos, find out from these numbers, then find out which one is positive first. Number Subscribe here Number Need Number First do a run Subscribe - Verb - Because tell me this Index - Verb - Because tell me this Index - Verb - Because tell me this Index Page Number 2 Either mash it up then the thing about pleasing him is that when we talk about index then zero 1234 He is talking about, now we will do it - we will do whatever we now we will do it - we will do whatever we now we will do it - we will do whatever we say, we will do our connected 100 system, if we do not accept the medicine, then the percentage will go and will make it, we will say and that who will die, ax and ax, what should be its position, Bengali Pade One - Bengali Pade One - Bengali Pade One - 102 I will not just ignore you, we will set a reminder for you, after this, what will we do now? Boil, what do we have to do in that, till the morning, let's do this work. If your off eye is sand, yours is big, okay, yours has increased from zero and yours. There is a break from them, if there is an angry turning point, then your work will be done, decide as long as you have to run till the end and from the middle, the correct index's equal end definition in Jabalpur, listen, this is our FI right now. Have read that Pimples were killed on our side Pin tax rate on our side Be your friend Cricket Player Talker Like and share and subscribe the video Subscribe or submit Whether it was to appoint or subscribe Like and that came that Baalveer wala Baalveer change Should be Grade 1008 Greater 20 should be and the volume of the year should be a and equal to benefit international music should be done The value of the friend should be finished I am so much that not hand it over, just after this Come and give or withdraw current index and subscribe to Roy and do not forget to subscribe the channel and do if you want to subscribe plus minus plus and if not then it is wrong and giving that we even if and by I If it is not equal to our own Lakshman's plot means meeting, then now I return it to you I plus mummy and only if all the elements are found then return is not hit. Do this by reminding these questions that next. Positive-Positive Missing Number VPN Krishna Let's Positive-Positive Missing Number VPN Krishna Let's Positive-Positive Missing Number VPN Krishna Let's boil it and see it's ok Expected toe Now let's submit all the dust that we have got or do we pick it up at school and repair it directly from the driver This hair pack is zero - For the minister, we said, let's start Gulab, let's check, if you zero - For the minister, we said, let's start Gulab, let's check, if you subscribe to us like a disgusting person, then - - - 11th, just - - - 11th, just play the previous ones again or let's check, are you the epic of Meghvansh and the channel and that C0? Subscribe to this and like it and we will do 2012 here and again village gh all this is correct and quality will not go inside, we will check now our fix here which will become our element to clean. - 01 2013 - 08 Have to be - 01 2013 - 08 Have to be - 01 2013 - 08 Have to be updated in 2012, what is the offer, friend, the office is interesting, will you enlighten me - will friend, the office is interesting, will you enlighten me - will friend, the office is interesting, will you enlighten me - will make it - will make it, now we will make it - will make it, now we will make it - will make it, now we will come up and boil it again, brothers will do it for me and affair 505 10 Margaret, then go out. From that to the form, we will go to the naval version next, activate is capable, tight list index is our three and element with should be 12 free from here, if it is free - will break, will bring the fax number free - will break, will bring the fax number free - will break, will bring the fax number two and give it to the form again, will check that we are moving towards Friend, is there anything, send the fail, it is good, ours is three and its record, click on accept you two and if you come, you will do it, then what else will you do, fix the last date, it will be here against Edison - Sonu will go, friend of this, I have become against Edison - Sonu will go, friend of this, I have become against Edison - Sonu will go, friend of this, I have become capable. This disease question, we will check the lump above, this condition will spread, if we go for verification, then if our fog is fine there, then finally Bigg Boss will be made there - in three leaves - 1384 What will we do, we are will be made there - in three leaves - 1384 What will we do, we are will be made there - in three leaves - 1384 What will we do, we are lowering the flame of gas, we do, we Let us do it Use Rashtra Sangh, otherwise there is no time for this, many questions can be asked to you in the interview, so search and understand, if you want to do it, then master yourself once again, try and see accordingly watching this Video 1 Week Most Liked Video Must Have Been Expressed
|
First Missing Positive
|
first-missing-positive
|
Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
|
Array,Hash Table
|
Hard
|
268,287,448,770
|
42 |
Hello guys welcome back two decades and this video will see the trap in rain water problem with juice from list no-42 problem with juice from list no-42 problem with juice from list no-42 show latest reader problem statement in this problem given in negative entries representing elevation map with and this time this one computer how much Water after subscribe button example in order to get better understanding subscribe and subscribe the rain will happen and will be sufficient water to maximize the amount of water in the elevation to unite to find what is the maximum water which can be trapped inside a celebration medicine problem Solve Calculated In This World Can Happen In Relation Me Shift 203 25 So They Can Individually Calculate Vote subscribe to the Page if you liked The Video then subscribe to subscribe Celebration After Running Water Level 400g Otherwise Will Not Be Able To Absolute Subscribe Water Level Will Calculate The area of the area of the area of the get it is not doing any water because it is equal to the water level date for the time voters in more plants in the country will see the water level sports and the city to the difference in itself is equal to water level - subscribe The Video then subscribe to the Difference Is The Difference Between Two Water Levels - - 04 I Will Be The Difference Of Water Levels - - 04 I Will Be The Difference Of Water Levels - - 04 I Will Be The Difference Of Water Levels Similarly Placid Kunwar - Creative Will Be Equal To 4 - Kunwar - Creative Will Be Equal To 4 - Kunwar - Creative Will Be Equal To 4 - Tubelight To And For The Last Few Vs Pet Will Not Be Able To Water Because It's Great The Water Level The Trap For Love You Will Find The Total 10 Interrelation Subscribe Problem Seems Very Simple To Understand Subscribe Now To The Question Is The Best No One Can Not Be Able To All Of You To Love You To The Possible Combination PM Videsh OK End In Here Of This Combination Shiv K Not Attract Water In Order To Trap Water You Need At Least Three Box Unit Blog Sirvisu 310 How Can Form A Pocket Inside The Grate You Can Store Water Liquid Form Of The Best Never Be Able To Water Unit Subscribe Button To Know The Box In Descending Order Will Not Be Ready For This Is Not To Moderate Rain Quaternary Fear The Current Lockheed Darkness Twisters Begin R Current Lockheed So That You Can Track Water In Between Ok To Box Must Make Profits To Water This is the mission that Navodaya amount of water will depend on the minimum boundary height okay so let's see from the side you want to find what will be the trap water add block to the blanks with me to go for example the water The level will be to the maximum left to the maximum set the water level subscribe and subscribe the Video then subscribe to the and listen and with Navmesh well if you have three blogs and if you want to draw 10 back to the What is the water level minimum of Mercedes for a rich with nothing but water level - The Amazing - 21 A 200 But Your Doctor Year Will Be 29 In The Second Example Developed Countries Will Fight For Right Countries Having 896 But Still Water Level Will Still Remember SIM Vikas Different from the minimum of the left and right boundary OK dates where the water is stored will still remain the same will be the water level spot height of the box to the example of the country which is the water level subscribe to the Difference Water With Simple Examples of How Pocket Strap Water This is the Question OK Member Example Which Indicators That You Want to Find Attractive Water 252 Nothing But You Need to Find the Water Level Which Will Be Minimum Level Will Be the Water Level - 2 - Do love you two Will Be the Water Level - 2 - Do love you two Will Be the Water Level - 2 - Do love you two you will see you can find the minimum keep on Hussain defined the water level enemy this is not happening with doctors sea on which is the daily a sorry this fruit is absolutely maximum and minimum of minimum Maximum 66 bulb school know what will be the water level to minimum of the country which is the largest Laptop maximum value to the a special - to special - youtube 6 ok pure a special - to special - youtube 6 ok pure a special - to special - youtube 6 ok pure new and tractor to will be 6 know what happens if you again after this all the notes but that no what will be the Water Twist To You Need To Find The Maximum Really Matter What Position Maximum Age Limit For B Id Maximum Minimum Of Co Maximum Navi Message Send Part OK And Again It Will Come On 281 Surya Welcome To Vishishtha - Current 281 Surya Welcome To Vishishtha - Current 281 Surya Welcome To Vishishtha - Current Height 21 You Make This Right Here In a normal water level and water level for the maximum give example in order to understand this topic from this article you have decided to follow this blog and what you have decided to go in this is the structure ok so issue of Finding the water stored and from this point left side one and left side 3 to 4 subscribe button more candy crush and another maximum element to the Video then subscribe to the world will be minimum subscribe 2525 water level minimum maximum minimum level will be Minus Forest Department Well It Surya Water Level Can Be Equal To What Ever Sure Water Level - Equal To What Ever Sure Water Level - Equal To What Ever Sure Water Level - Your Current Hit OK and how you find water level that you will find by using this formula Minimum of Maximum Dual app to get maximum to the right such option OK Khush will define the water level in just one official Water level with current You can get the area of the physical Suvan You can get the area of the physical Suvan You can get the area of the physical Suvan * Multiple with weight members Suvan * Multiple with weight members Suvan * Multiple with weight members formula to front rock water for single nor patient when you can repeat for all you can keep adding the values and what ever you find the adding the values and what ever you find the adding the values and what ever you find the sum of all the best on Thursday Solitaire Just See The Process How To Get Solved Sudhijan Example Which Will Be Singh Ko 2032 500 And Travel Travelogue Exactly Minimum Of Maths Left Ko Max Rate - Who It I Hope You Minimum Of Maths Left Ko Max Rate - Who It I Hope You Minimum Of Maths Left Ko Max Rate - Who It I Hope You Understand This Formula Of This Coming Late May No I Will Want To Solving This Problem Solve Waste The First And Last Love Will Never To Drink Water Level Cannot Be The First To Last Element Away From Water Cannot Be First Channel Subscribe From The What Is The Laptop To Subscribe Nine Maximum To The Amazing To The Bluetooth 59 Minimum of these two values and Bluetooth 59 Minimum of these two values and Bluetooth 59 Minimum of these two values and define the water level Water level will be equal to two for this to-do subscribe to the equal to two for this to-do subscribe to the equal to two for this to-do subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to the world will be four water level will remember and subscribe - 1000 2000 similarly maximum Dual app - 1000 2000 similarly maximum Dual app - 1000 2000 similarly maximum Dual app report and max M2 alright will be F and so you absolutely minimum of this 222 for separate Vidharbha current value that is the current hit draw them to be Similarly for this maximum to the five 14 - 225 will maximum to the five 14 - 225 will maximum to the five 14 - 225 will not to give the total inter-relationship not to give the total inter-relationship not to give the total inter-relationship plus 610 very simple process for married at one time complexity of elements who want to travel in time limit traversing the quarter final date for elements of very Dar Fans Ko Ok No One Else Can We Make The Time Complexity They Spend Most Of The Time Of Elements Which Requires To Left Side Click Subscribe Button On Left Side Thursday Just To Get Over With It Will Increase Video Pimpri Calculate The Maximum Dual App Test Max M2 ride point intact and will again repeat the previous process in the city will be highly optimized so let's see how do you know will know the first element Element 2011 The Element 208 Swift and they will be able to take away from the Movie Say Thank You Left May Will Be Compared With Current Values Are Turn Left Max Current Values Are Turn Left Max Current Values Are Turn Left Max In Fact Will Get Updated Soon That Is Not Through Any Specific Office Battle Service To A Wicked Element 2004 Values Will Come Again You To Three For Subscribe Values Will Come Again You To Three For Subscribe Values Will Come Again You To Three For Subscribe Maximum To 409 Against Loop subscribe to The Amazing Sauce Subscribe And This Bell To Maximum Element If You Want To Know From Right To Left Right Left With No 1 Inside Right Because Soil Into Rate Items Will Stories Phone Will Again Take All Right Mix Vegetable Witnesses Phone No before moving to the left for moving next element will be compared with it is the current elementary school get updated with the five elements no will to fight for right to subscribe my channel 9980 eager subscribe to 209 this maximum right victory time criteria will b containing for any given index what is the maximum value to the rate ok morning to * traversal switch to all rate ok morning to * traversal switch to all rate ok morning to * traversal switch to all the values for indian international jewelery the values for indian international jewelery the values for indian international jewelery next9 news room se technique video withdraw from first element loot element to minimum level on monday water level subscribe water level You Will Get The Thanks Of The Trap Dr Sudha To Loot 2482 Similarly 180 The Great Values For Just A Similarly 180 The Great Values For Just A Similarly 180 The Great Values For Just A Minimum Of Water Level In More Minimum One Five 14 - The Video then subscribe to Five 14 - The Video then subscribe to Five 14 - The Video then subscribe to the Page if you liked The Video then is so this is highly optimized Time Complexity Of So Testing Extra Space 100 The Time Complexity Will Be And Of And We Are Doing Traversal Preorder Traversal Stock Split Thermax Loop Yovan Service To Calculate Mix Writer And Thought Ravana Service To Calculate The Prime Inverter Ok Sudhir Widening And Subscribe Loot The Way Can and will work for interview but still not improve the time but will improve the situation in the country canteen Thermax Loop Tenth Maths Guide on Those Who Don't Actually Need Two Years in Order to Mental Maths Left and Right OK Look at this example the The Time Complexity Improves Does It Will Have To Calculate Move Was Appointed And Will Always Be Feeling From The Bridge Between To Subscribe 158 Tablet Boundary So You Should Have Taken 3 - Tablet Boundary So You Should Have Taken 3 - Tablet Boundary So You Should Have Taken 3 - All Of This Will Always From Mumbai To Clear Of Wave Solution Is The Meaning Of This Is The President Of The Difference Between The Subscribe example2 Points Quote And Will Be Converting From The Left And Right This 2.5 Inch Left And Right This 2.5 Inch Left And Right This 2.5 Inch Extra Water 2012 Start With Affordable Cost Limit Want To Avoid Last Element Storing Water But Will Give You Want To Give Back To The Best Way To Give The Second Maximum 285 OK So Which Helps Lower And So Poisons And The F4 Contra Voucher Set Will Be Free From All Over The Country Will be feeling and will examine the water level deposit it already in the list the value of water before you already know the to the Page if you liked The Video then subscribe to ki vo kya No Will Move To The Next Value Select Will Get Updated Log In Developed Countries Subscribe Must Again Will Be Feeling This And Again Will Be 420 and 406 420 Subscribe This Channel Will Not Be Able To Water Level Subscribe Now The Giver Water Level Will B & C The Level Will B & C The Level Will B & C The Max Loot Value Will Now Be Updated To 6 And It's Not Doing Any Water OK To Left Or Right Now This Train Will Give Me The Way You Want To Know What Happens When You Will Come With Me And It Will Start Feeling Subscribe Button Two Three Idiot Subscribe Quintillion Thing As Long As Later Request You're Okay No Hero Wasn't Be Able To Understand Its Total Time Complexity This Is The Name Of The Rain Water Problem Let this is the number of elements and subscribe The Amazing Maximum Amount of Water in a Very Simple App Chapter 2 Second Wizard Office Notice Cases and Will Take subscribe to the Page if you liked The Video then subscribe to The Amazing Please Click on the link for detail view So This Necklace Birth Otherwise Will See The Difference Between The Water Levels Subscribe - He Will Give The Subscribe Ajay Devgan And Bill Check Photo Condition Only The Current War Comment Box Is Greater Than Max Ride Difference Inko Suicide Note So You Can Type In Water In this block premises x-ray will get updated with Islamic x-ray will get updated with Islamic x-ray will get updated with Islamic advice this extra water and different water level with current will give The Video then subscribe to the Page if you liked The Video then subscribe to the Page if you interested please like share and Subscribe our channel thank you
|
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
|
1,253 |
hello so today we are solving the second problem of this late code we click on test 162 and the first problem says that we get a sorry the second problem which is one two five three construct reconstruct a 2d row a to rule binary matrix so it's a matrix with them with n columns and just two rows all the girls and it's a binary matrix so the products are only 0 and 1 and the sum of the elements is given in the first row in the zeroth row which is the first row is upper and for the second row which is the lower row the last row it's given as lower the sum of the values and the sum of the elements for in the in each column the overall sum of elements in each column is given in this array called somewhere the column I is the column sum of the of an array of length and in the column at position i right and when I construct this matrix we don't get it as input 1 is constructed from scratch using only the upper I which is the sum of the first row in 0 index is the zeroth row and lower which is the sum of the last row and column sum which contains the sum of each column and here with an example over here we get an example what the result should be this that there may be multiple result we need to just return any correct answer and if it's not possible at all like the sons don't match we need to return empty lists and that's pretty much it for this the constraint is that you can have a lot of columns so it can go up to 10 to the power of 5 and we just have 2 rows that's important for this problem and it's binary so it's only 0 and 1 so let's see how we can solve this problem okay so let's see how we can solve this problem so the first thing to know is that we have so as we said there are a couple of things that are important from the problem which were that we have only two rows and the values are just 0 into 1 right and we have to sum so it's like this so we have this road and we have this road these are the only rows we have and then we have the size of the columns that's n columns and we have the sum of each row like this is column sum I so the sum of the values here is given by this the sum of problems here is given by upper and the sum of values here is given by lower and we want to reconstruct the matrix so because the values are only just 0 and 1 so let's just come up with that some observations here so the values are just 0 and 1 right so what are the cases for a column right we know that a column can be only of size 2 because we have only a two rows right so it's either one end one right or it's 1 and 0 or it's 0 & 1 right or it's 1 and 0 or it's 0 & 1 right or it's 1 and 0 or it's 0 & 1 or it's 1 & 1 right sorry 0 & 0 these or it's 1 & 1 right sorry 0 & 0 these or it's 1 & 1 right sorry 0 & 0 these are the only possibilities we have right so in this case the value of column sum would be so we would have column sum that I would be loss maybe just put this like this so here column sum at I would be in this case it would be 2 in this case it would be 1 in this case it would be 0 right so for this case it's very straightforward right we can just say okay if column sum is equal to 1 we have 2 equal to 2 we have to put 1 in the first row and one in the right there is no other way around it so we have to put let's say D G is the because G is usually what you know it's a column right so then at that point we know that we have to say that the first row position J has to be equal to one and the second row position chain has to be sorry the second row so that would mean one here has to be equal to one right now if it's zero they also have to be zero all right so if the so this here means the column sum so if column sum is equal to zero then we do know here that both M 0 G has to be equal to 0 and M 1 J has to be equal to 0 right so these two we handle don't know it's just the case of 1 0 and right so for 1 0 1 the case where if the column sum J is equal to 1 then in that case we could just say well if let's say if the sum of the if we had something like this were the sum of let's say we have column sum is equal to at some position I J is equal to 2 maybe 1 right and then we have upper equal to 2 and lower equal to maybe 0 for example right we know that we have to put this one here in the upper row right because putting it in the lower row means we won't get a negative it's not possible to sum is 0 even if it's if alpha is 2 and lower is 1 it's still more beneficial to put it in the upper low because then way means that well if the column sum down the road let's say in some column it's 0 so it's not possible to put a lower we can still like make paper the bigger value to make sure that we get to have a solution right and so same thing here we could just put in first row so in the in this way basically what we are doing is kind of a greedy way with what we can do is just say if the lower portion is all say it the upper portion it's bigger than the lower then what we will be doing is we'll place the value in the upper because that maximizes our chances of finding solutions is down the road right because yeah basically and so we say basically in the case where each one has value one it doesn't matter we can't place in whatever position we want but in the case where this one is 0 and this one is 2 we can't put here and so by doing this we make sure that we don't have that problem and so we could say M zero position J is going to be the upper lower row so this is the upper row so that's will be one and then position one will stay as zero so what we can do is initialize the matrix in the start with zero values so we can initialize it with zero values right that way we don't need in this case to initialize to zero and in this case centralized to zero right you can place the values only when we need to place one right now otherwise that means if they are equal or lower is um or lower is bigger right so in that case if lower value is bigger same thing we need to place the one in the last row and we don't need to put 0 because we said we will initialize the matrix with zero there is one last thing because maybe what if with the value of lower was zero both ones you know like upper and lower itself and I see that they are equal so I put one in the second solution but actually that means that the second prong now needs a sum of one and I don't have that and so I will still return the solution even though there is no solution because that's violate the constraint that the row sum has to be equal to upper sum the sum given by upper and the sum and write this sum given by lower right so what the way we can do that is just well when we consume one subtracted from the sum right so that at the end we know did we consume just the sum that we had or did we consume more so that would mean that what we'll do is basically in this position here since we subtracted from the so we added we put one in the first row which is the upper row we need to subtract from the sump right so we don't leave so we just use what we have and here since we added one to the last row we need to subtract from the lower which is the last row sum right here is zero so we didn't add anything so we shouldn't do anything here we add one to the first row the upper row so we should subtract from that sum and here we add one to the lower row well the last row so we should subtract from that so and at the end if we have upper is not zero all we have lower is not zero basically either there was one value remaining which means we didn't choose the entire sum so we didn't construct the matrix that satisfies the constraint that we got or the same thing happened with lower all the body is minus one which means we have more than what the sum allows then the solution we have is not valid and the problem says if the solution is not valid we need to read and I'm jealous and so that's what we do here otherwise we just return the matrix that we construct them and that's pretty much it so one question you could ask is why didn't we check that column some also is not like we didn't use more we didn't use less than the value of column sum that we need or we didn't use more than to come sum the value of each column that we have that's a valid question but the thing is by construction here of what we did here of the further matrix with we did it according to the value of column sum we had so that we use exactly the number of valid of the values in that like the number of ones in the column sum value because of the ifs that we did here you can see here we consume it only what is in the column sum exactly what isn't there and so we don't need to check that because by construction of our ifs cases here we it does satisfies the condition so we took one condition we constructed our construction here with the if conditions so that we can always satisfy that condition and then we checked if the if using that two conditions were still valid if not then that means we didn't have a solution because it has to be that case because of the way we were constructed it okay so now let's just type the solution and make sure it passes a bit code okay so now let's type the solution that we just talked about so she's at this and so what we need okay so the first thing we need is just to get the length of the number of columns right and then we need to construct the matrix as we said in the overview which is zero values so we would have number of columns here and we have only two rows so this can be range of two and we need to say that we go through each column and then check if the column sum of J is equal to two and then I'm going to do it in two separate passes but you could do it in one pass it's just easier to let us know about in two passes so in one pass for column sum equal to two and one class for column sum equal to 1 and at the end we could return do the return here but if the count some value is two as we said we need to put one in each row right in the first row in the last row so this one is going to have one and this the second row needs to have one and when we place one in the first row that means we have one less value right so we subtract it from the Sun and one last value here so it's extracted from the Sun if this is one as we said we need to check which one is bigger to be able to subtract from it and so if it's bigger the upper is bigger we subtract from the first one and so we add we put one in the first row and then we subtract from the sum of the first row otherwise we do the reverse which would we do it's basically for the last row which means we put the one value in the last row and subtract one from the Sun and we check here that we really did satisfy all the conditions so that our upper is if it's different than zero or our lower sum is now different than 0 that means we don't we didn't satisfy all the sums conditions and so we need to return that we didn't find the solution otherwise you return the solution that we found in terms of time complexity you could see here we are just reversing the columns once and so it's o of n basically because how often is in terms of Big O is just over in terms of space we are using the who are using this matrix here to construct it we have to there is no way around it and that one is just two for two rows and nth for the number of columns which ends up being just open right okay so let's run this yeah there are multiple different solutions that can have so in yeah let's just film it okay so that passes yeah so that's pretty much the only solution I can think of for this problem and thanks for watching and see you next time
|
Reconstruct a 2-Row Binary Matrix
|
sort-the-matrix-diagonally
|
Given the following details of a matrix with `n` columns and `2` rows :
* The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`.
* The sum of elements of the 0-th(upper) row is given as `upper`.
* The sum of elements of the 1-st(lower) row is given as `lower`.
* The sum of elements in the i-th column(0-indexed) is `colsum[i]`, where `colsum` is given as an integer array with length `n`.
Your task is to reconstruct the matrix with `upper`, `lower` and `colsum`.
Return it as a 2-D integer array.
If there are more than one valid solution, any of them will be accepted.
If no valid solution exists, return an empty 2-D array.
**Example 1:**
**Input:** upper = 2, lower = 1, colsum = \[1,1,1\]
**Output:** \[\[1,1,0\],\[0,0,1\]\]
**Explanation:** \[\[1,0,1\],\[0,1,0\]\], and \[\[0,1,1\],\[1,0,0\]\] are also correct answers.
**Example 2:**
**Input:** upper = 2, lower = 3, colsum = \[2,2,1,1\]
**Output:** \[\]
**Example 3:**
**Input:** upper = 5, lower = 5, colsum = \[2,1,2,0,1,0,1,2,0,1\]
**Output:** \[\[1,1,1,0,1,0,0,1,0,0\],\[1,0,1,0,0,0,1,1,0,1\]\]
**Constraints:**
* `1 <= colsum.length <= 10^5`
* `0 <= upper, lower <= colsum.length`
* `0 <= colsum[i] <= 2`
|
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
|
Array,Sorting,Matrix
|
Medium
| null |
260 |
Launcher madigol Seven Jessy Colosseum cow 6516 Wik KW version to gytuan one touch the should learn to lovers I juicery I trace Riau Oh yes bio.one juicery I trace Riau Oh yes bio.one juicery I trace Riau Oh yes bio.one Sopo Jarwo Adit Syaikh Syuaib OK Wih Whenever you are single Speed Up Racing Shop Whenever you are single Speed Up Racing Shop Whenever you are single Speed Up Racing Shop and Drive Hi good yitong FC you halsey-sorry use Hi good yitong FC you halsey-sorry use Hi good yitong FC you halsey-sorry use napeni fwsm Where you can often 3G replace Alis and the first it seems that They're ready in [Musik] midnightmovie21 walked away Oke the number of Awards and the Disco p3din n Carry On I could you so much Sony
|
Single Number III
|
single-number-iii
|
Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
**Example 1:**
**Input:** nums = \[1,2,1,3,2,5\]
**Output:** \[3,5\]
**Explanation: ** \[5, 3\] is also a valid answer.
**Example 2:**
**Input:** nums = \[-1,0\]
**Output:** \[-1,0\]
**Example 3:**
**Input:** nums = \[0,1\]
**Output:** \[1,0\]
**Constraints:**
* `2 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each integer in `nums` will appear twice, only two integers will appear once.
| null |
Array,Bit Manipulation
|
Medium
|
136,137
|
101 |
Now in this short we will see the trading approach. In the previous short we had seen the recursive approach, so in the Italian approach you will have to make mistake many times, everything will be correct only then you will make the return true. Okay, now look, you have to do a check, root no. If you take root then take two stock and take three more left and right now see if root dot left is not equal to null but if root dot right is null then return false advice push both left right into stock now this There is a tap but it is not equal to the tap even then you will return the water and till the time there is no such empty item you will go. Now even if the stock size is not there then you will still return the water. In the other vice if you do it on the right then you will do it on the left again because This tag is right and left will come then return it if not then left is right no ok then what will you do, you will go to the left of left and you will go to right. If the value of both is there then you have to ask for it in the stock, similarly left and right. Whichever value is on the left of the right one, then enter it in time and return the other vice versa, everything is correct.
|
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 |
763 |
in this video we're going to take a look at a legal problem called partition labels so a string as of lowercase english letter is given we want to partition the string into as many parts as possible so that each letter appears in at most in one part so return a list of integers representing the size of these parts so here you can see we have given a integer input we want to partition the string into substrings as many substrings as possible where each letter appears in at most one part so you can see we split it here right you can see a appears most at this part b and c as well d e f g appears mostly at this part and h i j k l um a pairs appears mostly at this part so we partition the string um this way we're uh if we given this it's not going to work because we can still continue to partition this part okay so what we can do in this case to solve this problem one way we can do this is we can use a brute force approach and try to basically iterate each and every single character and try to find the last appearance of each character in this case the last appearance of a in this case is here it's right here right so we do is for each character we want to find the last appearance and if the last appearance of the current character that we're on is equal to the current index then we can partition the string so what do i mean by that well here you can see we have a the last appearance is here b last appearance is here right c last appearance is here and in this case the largest um the largest last appearance index is going to be here right because you can see all the characters that are less than this character all the characters that are before this character all appears before um before this character right so in this case so the largest last appearance character right index is going to be a so we're going to partition here so all we have to do is we just use a proof force approach and for each character we're trying to get the um get the maximum last appearance of this current character and then if the current character is equal to the maximum last appearance then we can just partition the string right so this is one way we can do it but if we were to do this the um the time complexity is going to be bigger up in sorry a big o of n squared so it's not the optimal solution so what we can do instead is we can use two pointers to optimize the time complexity down to linear so let me show you how to solve this problem using 2.2 pointers to solve this problem using 2.2 pointers to solve this problem using 2.2 pointers technique what we're going to do is we're basically first going to iterate the entire given string and then keep track of the last appearance for each and every single character so in this case a last appearance of a is 2 right index two in this case zero one two last appearance of b is one last appearance of e is index five last appearance of t is index four okay once uh once we've done that we can basically keep we can be able to get the last appearance of each character in constant time right then what we're going to do is that we basically figured out what's the last appearance of this in this case the last appearance of this character is 2. then what we're going to do is we're basically going to move forward in this case the maximum in this case a lot the um the last appearance the maximum last appearance i should say is in this case is equal to two then we move the pointer one to the right in this case the last appearance of this character is one so it's less than the max then we're just going to continue in this case the max appearance of a in this case is two and where current index is two is equal to max then we can just partition this string so it's pretty simple um so let's try to do this in code so to do this in code uh what we're going to do is we can either use a hash table to store the last appearance of each character or we can use an array to store the last appearance of each character so let me show you how first i'm going to use a character array instead of a string i'm going to convert the string to a character array then what we're going to do is we're going to use a integer array to cache the result to cache last appearance of each character so in this case we have a we initialize a integer array and we call we give it a size of 128. um that's going to be the total of the um ascii code right total characters last code and then what we're going to do is we're going to iterate so for integer i 0 i is less than array.length what we're going to do is we're basically going to first get the current character which is array i and then we're going to do is for cache at character right for that specific index we're going to assign the current index of the string onto the current of that character in the array right so at the end when we iterate we're going to get the last appearance of each and every single character then we're going to do is based on the data that we have here so we're going to do is we're going to have a left pointer basically points to where this partition starts and we're going to have a right one that points to where the partition ends and we're going to have an index that traversing that just iterates each and every single character and every single iteration we're going to redefine we may or may not redefine our maximum the maximum last appearance of the current character right so in this case we're going to have the left corner starts at zero the right pointer also starts at zero and we also have an index that basically um traversing the um the string right so we're going to say while index is less than the um the length of the array right so in this case array.length we're right so in this case array.length we're right so in this case array.length we're going to do first is going to get a current character so currentcharacter is equal to array at index right and we're going to do with it is that we're going to find the last appearance of the character so what we're going to say is this um in this case the right pointer right is equal to the last appearance so is equal to the is the mass maximum either the current maximum appearance right current maximum appearance of the of this uh of the character so far or the maximum appearance of cash at um at the current character in this case the last appearance of the current character or the last the largest last appearance of the character so far the characters that we have been traversing so far right and then we're gonna do is that if the right pointer right if the right pointer is equal to the current index then we know that we're on the last appearance uh we're on the last appearance of the characters that we've traversing so far so what we can do is we can partition the string so what we're going to do then is we're just going to create a array um sorry my back uh we're going to create a list integer and we're going to call a result we're going to use link list because we don't know how many items we're going to insert into the list so what we're going to do is we're going to create we're going to define the size right in this case the size is equal to right minus left plus 1. the reason why we do plus 1 here is because it is zero based right the array is zero based we just have the plus one you can see it's nine and here to here is going to be nine characters right so one two uh my bed this one right here so in this case we have nine characters one two three four five six seven eight nine and this is the eighth index this is zero index um a minus zero is eight so we have plus one to give us this real size right in this case nine and we're going to do is we're going to add it to the result so at the size to the result then we're going to do is we're going to basically get the right pointer is going to increment by one we're going to move on to the nest um nest partition so the next string right in this case what we're going to do is we're going to get left is equal to right so that we can have left and the right both start at the same position then we're going to worry about our index we're going to get our index increment by 1 for each and every single iteration so at the end we're just going to return the result now if we were to run the code um let's see okay let's try to submit now here you can see we have our success so basically this is how we bring the time complexity down into a linear time complexity and the space complexity in this case is going to be big of one and because we have only 20 128 um size for the uh for total characters in the um so this is it for this video and thank you for watching
|
Partition Labels
|
special-binary-string
|
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`.
Return _a list of integers representing the size of these parts_.
**Example 1:**
**Input:** s = "ababcbacadefegdehijhklij "
**Output:** \[9,7,8\]
**Explanation:**
The partition is "ababcbaca ", "defegde ", "hijhklij ".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts.
**Example 2:**
**Input:** s = "eccbbbbdec "
**Output:** \[10\]
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1).
A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached.
Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached.
If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is:
reverse_sorted(F(M1), F(M2), ..., F(Mk)).
However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
|
String,Recursion
|
Hard
|
678
|
387 |
hey everyone welcome back and today I'll be doing another lead code 387 first unique character in the string this is an easy one given a string find the first non-repeating character in it and first non-repeating character in it and first non-repeating character in it and return its index if it is not exist return minus one so in lead code L is the first unique character in love lead chord he is the second unique character and so let's get started so we'll be making a map first which will be our dictionary for every character in as we will put it in map like this and add it by one so math get I and putting the default value of 0 okay so for I in math now if map at I is equal to 1 what we will do is just return s dot index and passing it that I to return as the index otherwise we will just return minus 1. so that's it let's see if this works yeah this works and that's it
|
First Unique Character in a String
|
first-unique-character-in-a-string
|
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
**Example 1:**
**Input:** s = "leetcode"
**Output:** 0
**Example 2:**
**Input:** s = "loveleetcode"
**Output:** 2
**Example 3:**
**Input:** s = "aabb"
**Output:** -1
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
| null |
Hash Table,String,Queue,Counting
|
Easy
|
451
|
116 |
The aim of the early pension survey was only to go till the last, we asked very good questions on the method, I hope you all are driving the placements of history and I am learning a lot from you, if you spread the word and keep watching, then as far as I am fit. I am getting that brother, the body is going very well, many people are understanding it, then you too must be understanding it well and will behave while taking this series forward, but if you are liking the series, then there you go. Friends, please do share, friend, I just keep the matrix on the left side and they get very good response, so it feels very petition toe, then Rasta Azad questions, watch the butter, then I say quickly, watch your questions on my channel. Before this, pause the video and read the question. I was giving the link. Comment. I am saying that there was a description box right there, from there you can go to the video question page. You can give the question structure of 15 minutes as much as you want, what is the quality. Now do something on the pancake on the pen yourself. If I had this option instead of getting it from you on panel paper, is the quarter ok? Show me the salt and one of the children would have come here. While solving this question, this child did like this. If you have attempted then it is ok then the state is there such a feature otherwise Rustum protects you by looking at the question asked what are the types of questions asked Right and before that if you are a student or a working professional who is in his software development journey. Now you want to know whether there is work in the industries or what questions are asked in the interview. How can you increase the banking and rating of everyone in your court? You will be told about the searches here. Our host is the one who will guide you in this decision. He himself belongs to the company very well. His dating profile is quite correct. He also brings Life Sentence on Life. Top-20 Interview Questions Life. Top-20 Interview Questions Life. Top-20 Interview Questions Direct Relief When You Can Ask Questions to HR & Interview Process Questions to HR & Interview Process Questions to HR & Interview Process Recruitment Process and All Matters Not Wedron It's A Cloud Computing Dr Quick To Entertain Airtel Digital Marketing System You Don't Need To Update All This After This Its The Center Line Wire If You Use My Code Word Which In Which What Directly On Time Cent Of Mill India Digital Marketing Expert Will Be Coming Live On Daily Basis And Teaching You All Digital Marketing Using A Particle Physics And Tools If Updater Don't Have Any Idea In Marketing But Still Told Just Basic With It will be quite easy and fun to see how you can grow a lot in the dark. Together, I will tell you how the apps on Amazon, Flipkart, YouTube are targeted, the audience is read and then how all this ad gets converted into sales. It will be told from Ujjwal Kumar Sen that the question is whether Aamir will be in the battle of digital marketing, life project will be in front of you and very interesting episode or with the host, he will be for Shiva Reddy Labs, so please show the vote and support settings. The question is deep, we have a route given, okay, it is definitely given, now what is a generality, you have a note, general which is no different, this is a note, exactly 19 have property which we make. Here we have the straight line, what can we do in the note that we are making, so we make what we want with the help of people, it is typed, there is a point in it and this note or note is directed towards its target. He will appoint a little bit of modification in the notification, he gave one more point, next does his just one, who is the one next to this bud, the node on the side of the bud restores its address, like here is this note, who is the one on the side of this, otherwise there is no one. Null, this is two, I am talking about the birthday and here I am talking about delete. Okay, this is the one who is next to him, three, so the additional address in the next point A will be the store, who is the tax recovery person, none. So tap four cup baju wala kaun hai five let's go again olive oil and who is the 626 song seventh ok hai jo subscribe property hoga six will have property education note he will have property value after that left would have property left he will have property Added right away properties and next so what is there on the left in sex, tap take, what is there on the right, tap and its next, whose story will go from here, seven's sure, seven will drown in the next, now who is next to seven, no one, channel take so The question they have given in the beginning is okay, the question they have given, what have they done in this question, ultimately, whenever we create a note, these four things are there in it, Value, Left, Right and WhatsApp Next. All four things are inside it, okay, the values are restored inside it, values are restored inside it, values are restored inside it, we don't know, but if I talk about this one, then what is the value inside it, one, it is pointing to the left, let's point to the opposite root, it is okay. This one will appoint the light, the free one will appoint six and seven, this next one will appoint Vikas, there is no one next to him, we are sure that the hotel is running here, now tell me, the press is watching from the side of the couples. I am telling him again that he will guess a little and Dub came in between, I will press him with folded hands and request him to please start looking at the settings once above, okay, you will be able to do all the things very well, what is this? How is it freeing the Muslims? If you come in a random middle, it will be a little complicated that you will not be able to relate the things, now we have to go oriental, now we have to go horizontal, so someone struck out what we used to say in lodge hotel traversal, traveller. Traversal is fine, we can relate it somewhere, it must be having level and traversal in it, we can think about the direction, how is this result reversal with records for rental, how do we know pilot verses, when I have taught, fine level, all types of us. People, it is ideal that fort but reversal can be written in it, hence you apply your mind, now before doing that, understand that level attempts of course will be included in it, we will give notification, so I say again, we will store the inverter website by slightly modifying the code in it. By doing this, we solve this question, in the same way, Level Reversal, this is the Level Reversal Code, in this same chord, we will make some notification and this question will become C, how step and who are the people but Salman is going on that you have done this. Before watching the video, read Bhadra Oil, do not want to see the entire playlist, go to the specific meaning and traversal, you will understand better. Now, what did we say about what is happening in this Type One Step One? In this Type One, What is happening is that why did we make this, now it is made in the first time, okay, when I went to one, I decided on the size, why for sure, now we enter inside here, pay attention when we enter inside this group, what just before here? Let's sin this one more tours and Bollywood can set the talk time then 283 we have set but till then the size is one take here again jobs will laugh on this files again that will come only then all the strong next step Staff and other sizes are being made in it, when you tell me the size of the note is one, the size of the road, I said it wrong, sorry, of this level, this is level-1, this is level-2, this level, this is level-1, this is level-2, this level, this is level-1, this is level-2, level-3, if one is alive, then what will be there on his side, wo level-3, if one is alive, then what will be there on his side, wo level-3, if one is alive, then what will be there on his side, wo n't it? 11 :00 But there is a limited n't it? 11 :00 But there is a limited n't it? 11 :00 But there is a limited chance of having a child. When there is no chance of having a child, then we will not use our mind and we will put a tap in the one who is next here. Now the question has been specific that what have you done? Look at the next point a is set side by side in the question and initially all the next point upset total is initially what we have in the given question, all the element notes in the history of each note, each one has some next point. In summary, our work has become easy, we have come to know about Guru and additional elements in level-2, know about Guru and additional elements in level-2, know about Guru and additional elements in level-2, now notes23 elements, so we know that in the last level, there will be someone next to the last element, otherwise it is definitely shared. The next point that will go to the channel means that we should share it. If I talk about this level, then only level two and apart from this, these three should be developed in the same way. These are the last ones and we know about those who are last. These waves will point to the tap, okay, let us cross them. Now when it is size two, we can care, how can we care? We said why not pause it, okay, we popped it in one time, what is the temple, what is the pop. What did we say and removed it? After removing it, we have put the address of this element in the next part of this time. Let's office address is LED address. What form has been added and it is done. Let's check post. Three four remains like this, some tips, first Mittu takes you, tops you and puts the address of two, you put the address of free 2 minutes, electronic cigarette, his address is traffic, if the husband commits a sin, then put three in the next. We give the address of whose address, take off and what do we do to that person, nothing, just now the size has become our mind, when the size becomes one, then we are not doing any work for development, its size has become our mind, now who is a little drain here? And it will mean that now you will be stuck here for a little bit, you will laugh when you code it yourself, I told you something, I will also tell you the coding, still you are guaranteed to sleep, now when not for the crops, when you copy each step for this question. If you chant each and every step for the driver, then how will you not get trapped in your joke, guaranteed, this is level-1, this is level 211 SIM, I am telling you, wait this is level-1, this is level 211 SIM, I am telling you, wait this is level-1, this is level 211 SIM, I am telling you, wait friend, again I am telling you, I want you to learn my real thing, now I am telling you the truth. You will learn this by watching my video, never by watching anyone's video, you will not run till all subscribe or paper, meaning you will have to practice at PAN office, now attempt fruits, do not bring the phone from here, we now have this tap, size, strength, first. Why is there in the bar, what happened, one is gone, size one is size one, we did not care, they said remove it, nothing should be done at this time, size two came in this case, when size two came, we said, put Kittu's address for free in the service to connect. Put a reminder and stop the two, then the size will become one. The size stopped, then we did not care and attacked and said, let it be, keep it in your mind, then move on to the size for this case, because this one is the size for traffic, what do these people say? Why is it made a medical vertical and horizontal line, why is its size for size and so and address five suicide next, press f5 simultaneously and turn it off, we address 5, six goes in side connect, let's pause it. The size became two, the address of the seven was fixed next, this was the pocket size, the size was closed, we came out and said that only the sure last one will be guaranteed. Now if we talk about the quality in this, then what code did I write, it is very simple. We just have to fit it at the right place, nothing else, if the size is greater than that if the size is Dhanvan, then what did we say, if the size is washed in the time of note, then what did we say, why take the cut front in time, then one Take out the element and mute that element. Now save the element. Sapoch 2345 Take in one line. What did I say that Snowden Sorry, what did I say that to do take in time? Now I made it two cups. After dropping, we have the next address. What is this next address, why did you use 3m in front, but now just listen to what I said, it came to know next, put what we said in the next part of the tank, the net is done, now it will keep moving and will reduce in size. When needs have decreased then why do we have new ones, why new ones are created, what are new ones created, three four, 500, what will we do with the previous ones, you will do this, we will keep doing this, we people and centers will keep doing this, I did e-agre here, now when I code everything, the code e-agre here, now when I code everything, the code e-agre here, now when I code everything, the code is very simple. Friend, it's fun, you will code even with your eyes closed, you have to fit it in the right place, just where it will be, C, now I court, I myself root and tap sex, then we will simply return the root, why do we make this? Note the star in it. The address which is there will go to the question that why now what will we do inside it will we push it now or not? If it is not there then we will just press the button, otherwise we will ask, this is a simple information, love affair is going on, there is nothing else and What did he say, if the size becomes excise now then we will understand what is the size and if you watch my video then you will also understand why I had more free fruits on the second net. This computer first person Mahendra gives the method for detailed explanation. The issue of reversal is not size. If they don't understand this then they must have not seen this video. 120 Equally 0 Will simply return what is the root ok then what will we do in it Boil that literature house size which is that house 20 Let's go back till Kayak, what did I put inside myself, a note called stock, I made him a general, I made him poor, I said, if IS is greater than one, we all will work on this, if there is an alliance, then I will not do any work, if there is no size, money, etc. What will we do with the simple thing that we used to do at that time, Times has a cute front, we will take the address and turn off the cute hotspot, simple and everyone knows this, if the left side of the water tank is not taped, then what will we do now? Why do we do dot first, we will copy something like left right of the tank, we will paste a text and size for the right - - datasheet here, a text and size for the right - - datasheet here, a text and size for the right - - datasheet here, while coming out of this look, what did we say, did we return the road, which one should we basically say this? All I had to do was to arrange it internally and whatever is the address of the route, brother, press it, there is no problem in it, now size money, what should we do in it, listen to what we said, why do we take dot print in time and turn off the cute hotspot. It gives no problem, we took it, now what did we say that the node is the star, what will be the necklace for the next address, why is the dot in the front and in the next part of the tank, we are clicking Bhavana, we will put next because of this. Let's see sir, this node capital is a successful one, so I hope you must have understood that it is running from Samalkha and it was not very pocket size, it was a very easy question, you just had a little trick in it that how can we measure Kepler water level. Being able to use Tite, I told you that there will be no need to buy vegetables from you will remember it by asking automatic questions. If you like my channel and my content, then please share that address on social media with your friends. Share it will be good for them, if a better one comes, then if you like this video, if you do n't have any problem with your son, then please join, it helps a lot, then thanks and device are received from Next 9 News Room. Till Bye Shri Radhe
|
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
|
100 |
Hello hello everybody welcome to my channel today's world thirteen and chili coding and problems entry fans problem 12182 is the function to sacrifice of same and not to do subscribe and not have the same way you so example1 beetroot 0 flu positive will right side extra Subscribe definitely tree with rude boy but didn't left side it right side this trolley that a corporation on third behave the song entry rot one shyam beneficial heart website that is not in the country also the result node of website but value of the The World is Different Societies Not Identical All Apps Return for Selection in the Biggest Tree to Hide Two of One Example If E C It Again Speed Matching with This Root Mode on This Two of the Left Again Speed Matching with This Root Mode on This Two of the Left Again Speed Matching with This Root Mode on This Two of the Left Side of Pieces The Giver Left Side 063 Right Side of the Places to in the fair the heads of a visa rights left side 29 These Trees Which Religious Embedded Value Different Subject to Return Has False Snow Examples In This Tree Again I Have Exactly Same 9.45 Subscription Will Exactly Same 9.45 Subscription Will Exactly Same 9.45 Subscription Will Solve This Simple Implementation Jis Door Andhra Three Types of Entry But Maximum Milk But It's Better To Start From Outside The Country For The Channel Subscribe Nahi Kiya To Loot Isse Bodhi Tree Indore Hotel Yudhishthir Will Return The Giver Nal Papi Channel Subscribe Liquid Of The Current Nod Equal To Do Subscribe School YouTube Channel Me Just Return A True Second's Only AP Who Is Equal To Null And Why Educational Let's Reminder Bell Icon Is West Indies Payment Is Not Requested For This Is Not The Independence Return Subscribe Stree For B.Com Fatty Acid Enter Kar Do MP3 Dot Right that hand work you don't right so let's take sample implementation so let's compile working code which I have tested passed Singh so let's make this that antiseptic so right know what is the time complexity of this time complexity of the process all the notes of the Like Wa Lottery Ismail History So Let's Check The Number Of Units In The Trees In This Time Complexity Of The Main Secure Member Very Simple Regular Seven Key Mental Tension Subah Channel Solve This Interactive Positive Will Do The Same Condition Values But Will Maintain Inactive Notice A Values But Will Maintain Inactive Notice A Values But Will Maintain Inactive Notice A First BT not first on boobs but more notes subscribe The Video then subscribe to the world will be tax on here code implementation has come to Britain have submitted the why and adverse page number why attractive and they all will not be inserted into channel subscribe The Channel Not Possible subscribe The Channel and subscribe the Main Ahmedabad Cuties One and Two Share First Will Incentivize Back subscribe and subscribe the Channel subscribe The Channel and subscribe the Channel A Similar TV LED Light of TV Channel and Write Issue Which No One Will Come Back The Subscribe In People With Soil In Condition Will Be True History Notes Have Samsung Galaxy S8 Women President Yourself And Let Me Know If You Have Any Questions In Infections Like My Solution Please Like Button And Subscribe My Channel thanks for watching
|
Same Tree
|
same-tree
|
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
**Example 1:**
**Input:** p = \[1,2,3\], q = \[1,2,3\]
**Output:** true
**Example 2:**
**Input:** p = \[1,2\], q = \[1,null,2\]
**Output:** false
**Example 3:**
**Input:** p = \[1,2,1\], q = \[1,1,2\]
**Output:** false
**Constraints:**
* The number of nodes in both trees is in the range `[0, 100]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
143 |
hi guys in this video i'm gonna go through this legal number 143 in reorder list and this question was asked by amazon expedia for the past six months um so the reason why i think this is a good question is that this one utilize a uh monument method commonly used for um for a linked list so let's dive in to uh to see what's asking so we are given a list looks like this one two three and four right so what we need to do is we order the elements of this uh the note for example the first one connects to the last one so one and four and two connects to a mint is the second one and it connects to the second for the last so one four two three uh and then this is one example another one is so as you can see the length is a uh is an even number which is a four and for a case where when it's odd number looks like this one two three four five one and then connects to five and then the next one's two connects to the second look from the last with four and three which is the middle but that push get pushed to the end okay um so the strategy to solve this problem is to we have to solve this one in three phases for example one two three four uh which we can we have to break it to two sections which is let me zoom in a little bit uh one two and three four and the way to do that we can use two pointers which is a uh a commonly used method for a linked list um so we use a fast pointer and a slow pointer to break the entire list into two sections uh the first half and second half one two and three four and after that after we have the three four and we can reverse it right we can apply a reverse length list method with to reverse the language from three four to four three now for that we have the one two and we have the four three we can merge them so after we merge it what we will get is one four and two three so one four two three okay and i have another example in here this is the uh the one with uh odd uh length is one two three and four five same idea so four or five so we break it in two halves and then we will reverse the second half and then we merge them so let's dive in to see how can we solve with this one and first we have uh we have a corner case uh where if the link list has only one element we don't have to do the rest we just directly return the head so now after this edge case uh we're gonna do the three phases that we talked about in the following code so first we have a dummy hat that's keep um so this is the reason why we need to use that just to grab uh the real head which will return at the end so i initialize the wire as a negative one just because this is dummy and also the next pawns the real head okay and now we have the fast pointer and the slow pointer and i initialize them as the same as the dummy head value is negative one the next note points to the head and while fast dot next and slow equal to snow dot next so snow only moves one step at a time and the flash moves two steps at a time and then at the end we will have a second head so basically this one collects the um the head for the second half which is for example the three right and because we will use that hat to do the reverse length list okay and now we do the slow dot legs equal to none just break into two halves so let's walk through in a simple example to see what we're going on in this chunk of code so first we have the fast and slow both of damages equal to a dummy head and first we have so as you can see this is how we can keep track of them right uh first pawns the one slow pawns the one as well and then the fast sorry fast points to one and stop once one and then fast points to three because it moves two steps and then slow points to two and after that we stopped because um fast dot next is going to be an none okay so at this stage uh second head equal to slow dot next so basically snow dot legs equals to g so basically this is the second head and now snow top next is equal to none so essentially what this is doing is the two dot next is equal to none we break the whole thing into two halves and now i have also the another example that goes through um the example where it is a odd length which is one two three four five okay um if you want you can read this but it's the same idea and now we can reverse the length list so we have the current so the current points to the second head okay so the second half right now is it is three where we will use at the end when we make that happy becomes a tail i'm going to go through uh another numerical example with you so we understand what's going on so but i want to go through it the code review in general first and the next is equal to the current dot next and then now we have the next while there's something in the next and we'll save it the next equal to next dot next stop next equal to current and now we move forward right so current is equal to next current is equal to next current is equal to next and next is gonna equal to the next that we saved earlier and we make the second half become a tail that's why the second head on next become a none so now let's walk through an example so the second half that we talked about before right after we broke it in two halves the first half both was one and two and second half will be three and four and none so we need to do oh sorry i forgot to mention here so the first half becomes one and two and none right that's why we have this no.next right that's why we have this no.next right that's why we have this no.next equal to none anyway let's come back to here so uh the second half we have is three four unknown and what we need is to change it to none uh four points to three points to none so as you can see all the directions are changed right and when three points the four and now what we tend to do is to have to four points to three right and then three points to none okay this is the end result we need so at the beginning the current equal to four three next equals to current.next which is four and next actually is equal to none which is this line over here and then next dot next equal to current so that means next stop next equals to current which is three so now four points three and then the current is equal to four okay because we have the current equals next and now next equal to next so next equal to none next we have ss and none and then we check the while loop condition next right now is none so we exit from this while loop and also don't forget you have to make the second head become a tail so this statement allows the three points to numb so this is the end result right four points to three and points to nine same idea when is a uh odd length uh when we do the reverse language so this is the same idea i'm not gonna go through it again in here and now we can do the merging and what we have right now is one positive two constant none so essentially what we have is this and then four points to three and then points to none right so we have to switch to two four uh two length list and we will need to merge them same idea when this is a odd band so we have a two um head right so we have current one also current two so current one basically points to the one right so basically come back to the dummy head dot next so we grab the one and current true is actually equal to previously what we had as a current so we go back to here right current points to four and this is exactly what we need this is actually the new head for the second half so current equal to four so it's actually so current two equal to four and while there's something in the current one dot next so we save the current one next and current to next by this one so come on next equal to column one box next current to next equal to current to a dot next and then now current one dot next equal to current two this is where we do the merging and if there's something in the current two dot next and also and what we do is current through dot next equal to current one dot next which we saved earlier and this two statement is where we do the merging and now we move forward right so current one equal to current one not column one next coming to equal to current to an x and if there is something left in current two we append it to uh current one dot next so again let's walk through numerical example to make sure we understand and the first uh back to this example right one two none four three none so current one is one current two is four okay and current one next and current two next is equal to um two and three right so this is this line okay and then one dot next equal to four right because it's this one current one equal to one right one block next equal to four current two right now is four and then four and now there's something at the current two dot next right because current 2.00 x equal to 3. anyway as long as it's not none and we can execute this line right so current true.next true.next true.next equal to 2 which is the current one next that we saved earlier so again these two lines what it's doing is do them we're doing the merging and now we're moving forward so current one equal to current one next current one equals common one next which we saved earlier so column one now it's two and current two is equal to current to next which you save earlier which is three and at the end so after these two lines and as you can see one dot next equal to four and four dot next equal to two right then we are almost done right so we go back to this example one dot next is equal to four dot next equal to two but what we are left is to connect the two to the three right so and where's the three actually now is a current two right so and this is why we need this line if there's something in current two and we connected to um the next one of the current one right and this looks complicated um the way that i solve them is to i started with some code that is not perfect and then what i did was walk through this example when it is a odd length or and then make sure it works for the odd length or even length and then next i'm gonna uh what i walk through and even at the outlands and then even ends together to make sure the code works so i wrote some uh simple code and then i walked through the example to make sure the code works so i modify the code along the way when i walk through the examples that's how i wrote it actually let's submit it and it works for time complexity wise it's a bigger n because basically we are traversing the entire length list and a couple of times right so the fast and slow corner is one time and then um we have the reverse and link this so this takes a big oven and reverse language text b or n as well because n divided by two actually it's only reversing half of it and now at the end we are doing the merging is b of n as well so big of three ends there comes a big o n force space complexity is bigger one we didn't use ag extra space actually you have only a few pointers here and there yeah that's my analysis and solution this problem and thank you for watching see you next one
|
Reorder List
|
reorder-list
|
You are given the head of a singly linked-list. The list can be represented as:
L0 -> L1 -> ... -> Ln - 1 -> Ln
_Reorder the list to be on the following form:_
L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ...
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[1,4,2,3\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[1,5,2,4,3\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5 * 104]`.
* `1 <= Node.val <= 1000`
| null |
Linked List,Two Pointers,Stack,Recursion
|
Medium
|
2216
|
482 |
hey guys welcome back to this new video and in this video we will explore a problem that was asked in google a couple of times so this problem is named as license key formatting and this is based on a string formatting as the name suggests so you can see the description here you are given a license key represented as a string s and which consists of only alpha numeric characters and dishes okay so we are having this example right here so we are having a string called s as the input and this is uh this is a license key and we have to format this only and we are having a parts like a four parts here you can uh we can separate the parts by seeing the dashes here so we are having the three dashes and we are having the four parts okay this is what this lines means okay you are having n plus one groups by n dashes okay we are having four parts by three dashes okay so this is what it means so we are also having a integer called k so finally we want this string to be formatted as this string so which means we are having parts uh as many parts as we want but in every part there must be like k elements okay so we are having this string right here uh we are having k elements in each part we are having two parts only this part and this part so in each part we are having k characters which is four characters okay here it's four character and here it's four character okay so and we are having the example two so here the random part and the random elements in every part so finally we want to get two parts like a two characters in each and every part like each and every part yeah so we are having two characters here and two characters here but here is only one character okay so what we do is the first like the first part must not be changed like uh we don't have to worry about the first part we do uh we have to change like these parts only we don't have to worry about the first part we must return the first part as same as in the input so we you can see like here so except for the first group which could be shorter than k okay so except for the first group we have to change all the group okay so we are having this group like uh the first group unchanged we are having this same exact as in the input so we are changing these only okay so we are having the k elements like a k characters in every part okay so this is what the problem means and we are having a solution like we are having an algorithm like so there are a couple of steps we have to do so first we have to replace these all dashes into spaces okay like uh empty string so we have to replace that so let's repeat so key equal to let me create a variable called key and store it there so store the string there and we have to replace all this dishes with empty string okay we have to join the string okay um so that it will be viewed without uh dashes so after doing that uh like after doing that it will be without dashes it will be like a eight uh characters without uh any separation so after that we can um produce this k parts by iterating from the last of the string okay so uh since we are uh we don't want to change the first uh initial group we may uh start with the last like uh in a reverse order and we can separate it by uh like four steps uh when seeing this example normally we are having a k elements in every part okay so we are just changing that first and we are having the formatted like uh formatted list okay we are having an empty list here sorry about that so yeah after that we are having a i which is a pointer which is pointing to len of key and minus k so whites minus k because we are starting so after that like after replacing all the character let me comment out here the character will be let me copy that yeah so let me paste it here yeah after replacing the key will be like uh yeah this key will be like look like this okay so after replacing all the dashes with the empty string it may look like this okay so after this we are just changing from like a lost from last and we are setting a pointer like i which is pointing to the line of key which is a length of key is this and lenovo minus k means uh let's take k as four so after four elements one two three four so we are just starting the pointer here and we are just creating dashes okay we are just uh creating uh dashes or parts okay we are just uh having this part only okay this part only and we are just appending to the formatted list and we are just having that much of parts and we are just joining all the parts uh through dashes okay finally so we are just starting here and we are decrementing here by here so in this example there is only two parts so you cannot see that much change but in this example you can see the change so after this part and we are just changing we are having another part and we are just leaving the first part as same okay so we are doing that so we are having a while loop here while i greater than or equal to zero okay so we are since we are decrementing we are just checking the return and formatted dot append so what we have to append is e of i sorry about that i plus a okay so what this means is i is something like this like uh here we are here okay so i is uh pointing to two now because uh len of key minus um k the index will be two now so we are pointing here okay so we what we doing is key of like a key is that this string only so we are pointing to i and so i colon i plus k which is this okay so we are having this string only this part of the string and we are just appending to this for formatted string okay so after doing that we are just decrementing the i by k okay since we want a k parts like uh in every part we want k characters so we are just decrementing the i by k okay after decrementing the i will become here so come here so the loop will end okay so let's take uh if we take this example um initially the eye will be here and it will be here now okay so in the second loop okay so we are just leaving the loop so after this loop after the this loop completes we are having all the elements inside this formatted list as parts okay like uh first we are having uh this part only like uh two e in and w here so we are having this part only faster after that we will have this part which is f 3 and z okay sorry about that yeah right okay we will have this part so finally uh since uh finally when we are returning we can just uh reverse it and we can just join it by using this dash so we can have like an output desired output okay so here we missed one thing which is here we are having this small letter like a lowercase letter we have to change all the lowercase letter to uppercase letter so as here so we are white yes we have to change all it to uppercase so here you can see the uh should become converted to uppercase so after replacing all the dashes we only have alphanumeric characters okay um we are not having this dashes here so we can easily change it to uppercase by changing the like using the function called apparent okay upper method so we can just uh use it so after that it will be changed so let me erase this so yeah after this loops uh it will look like this and we are checking now sorry about that and we are checking that now if i not equal to minus k which is when we are just leaving this group like um when we are uh leaving like a breaking this loop we will have i as a my uh k as minus k if we stop it in zero okay so let me explain that after so if that's the case we have to append formatted e of i sorry ah i plus k here okay so let me explain that with uh with new example and after that we have to like uh we have to reverse the formatted list since we are appending it in a reverse manner so we have to change that into a reverse list by using this slicing okay it will reverse the list and we are joining it by joining and returning it by this okay we are joining it by using dashes so dash dot join this formatter list okay so we are done here so let me run the code and check whether it's working yeah it worked so let's submit the code to check all the test cases yeah we are the end of the video yeah we are success so let me expand this code so as i said above like if you are having a minus k so this is how for this example there will be minus k only because at the first loop the i will be in here and after the second loop the i will be in here so after the second loop the i will be in zero okay so after we are just decreming the i by minus k so since uh since we are at the zero so zero minus three will be minus three and now the k is minus three okay so we are just after that we are just breaking the while loop okay now the k will be in minus three this is what the explanation is so for some example there might be like this so six or seven uh like six or you will be here and we are not having a minus k here so we will be having like we are not having that minus k here so for this um explanation here okay so this is how we change that group and change it like a make that first group unchanged so we have to do that uh as per the description we have to make that uh this is for except for the first group so in order to do that we need this condition right here okay so we are at the end of the video and thanks for watching so hope you all enjoyed it if you have any suggestion let me know in comments and yeah check out my other playlist too and this code will be in my github page you can check out through the link in my description so thank you
|
License Key Formatting
|
license-key-formatting
|
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`.
We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first group, which could be shorter than `k` but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.
Return _the reformatted license key_.
**Example 1:**
**Input:** s = "5F3Z-2e-9-w ", k = 4
**Output:** "5F3Z-2E9W "
**Explanation:** The string s has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
**Example 2:**
**Input:** s = "2-5g-3-J ", k = 2
**Output:** "2-5G-3J "
**Explanation:** The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of English letters, digits, and dashes `'-'`.
* `1 <= k <= 104`
| null |
String
|
Easy
| null |
549 |
let's go to question number 549 binary 3 longest conjective sequence second this is a medium question let's get into it okay it has a lot of summer okay good given a binary tree you need to find the length of longest conjective path in binary tree especially this path can be either increased or decreasing for example one two three four increasing and four three two one decreasing are both considered valid but the path this is this switching so it is not valid so always increase one by one while raise decrease one by one on the other hand the past can be in the children parents children they mean in this case one two three this one also valid we are not necessarily with parents children okay let's check the example one and this time because conjecture one three conjunctive null one two conductive yes so little length is one two in this case one two three valid three to one valid so let's say history how can we do okay uh today i'm gonna use uh equation uh and then there are two trip uh approach uh of three traversal first is cut down approach and another is the bottom of approach but mean is the first we go to bottom first and then we calculate one by one from pattern two uh root so in this case okay let's take with this one in this case uh when this one is going to there maybe it start here right and then when we here i will check two value one is the increase length and second is decrease length this time maybe it starts with zero and then we need off this is initialize zero and then it checked it and it's parent and that parent is one bigger or one smaller i will update this one in this case uh one bigger so inclusive length is one because it starts with zero and that decreases still zero and then same way this one is increased zero because this is decreases so decrease one and then now we are here right at that time i will check the max value of increasing plus decrease and then decrease plus decrease because in this case to combine two things one over one is the increase and then the other is opposite decrease so at that time we can uh count conjecture right conjectively so we used this pattern okay let's start implement code so first i think we need the helper and then we need a node and each parent to compare that is the conjecture one so first we need to make a base case if none node and then we can initialize is what that's like module so again this is none and then this is the first widget and then this one will return and then next to go to the leaf node we needed to recreate a relationship so return value is l increase because this is increase and decrease right and increase and then the grid is referred not left and that parrot that's right itself not there okay let's break then we needed a global value so global build okay let me write writers and then uh and then help her not write and download then it's time to calculate the maximum so maximum is the max ranks this one must be global bet global value and then max ranks and then i will calculate l do you remember last time that if this one decreased to add increase and then increase add decrease and then just again maximum right so this is the same one the recently maximum bead and then increase plus i decrease plus one is the root itself and that decrease plus all increase plus one this is current max value and then now we need to add increase at an r value when you're going off we need to calculate update this one right so to do that if uh okay before that let's sign let's make max valuable max length is zero and then maybe we needed to call helper root and that first is not because root parentism because it doesn't exist right so return max length then to use the global value in local function use one more curve and max length okay next one that makes sense so if parity must be exist to compare quarterly to parent and then another bad plus one is same as parent value that is this one is the bigger right one bigger and then highlight to return we get the maximum of increase right because we need it increased and then our increase plus itself comma decrease must be zero and thus if parent and node val decrease one is parent val and then return general and makes on a decrease and are decreased plus one otherwise we need to listen okay let's check the code okay looks good oh 99 woohoo not bad okay in this case time complexity is let's say n is the number of node at this time while we traversing with church not one by one so time complexity is linear time and then space complexity is uh the this treble tree treble you need to use a system stack and then size of system stack is same of the height of loot head of note and that worst case is if tree is screwed left side or right side height is the same of the lengths of length of node right screw left right so we can say it takes time linear time with linear space thank you
|
Binary Tree Longest Consecutive Sequence II
|
binary-tree-longest-consecutive-sequence-ii
|
Given the `root` of a binary tree, return _the length of the longest consecutive path in the tree_.
A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.
* For example, `[1,2,3,4]` and `[4,3,2,1]` are both considered valid, but the path `[1,2,4,3]` is not valid.
On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 2
**Explanation:** The longest consecutive path is \[1, 2\] or \[2, 1\].
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** 3
**Explanation:** The longest consecutive path is \[1, 2, 3\] or \[3, 2, 1\].
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3 * 104]`.
* `-3 * 104 <= Node.val <= 3 * 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
298,1416
|
723 |
beard's getting long hey yo what's up guys babybear4812 coming at you one more time today we're gonna be solving problem number seven two three candy crush based on everybody's uh favorite old school phone game i guess it's old school at this point um it's a really good problem and i it hasn't received much attention yet it seems from users but bloomberg's been asking it a lot and so as google a few times as well i thought it was a really cool problem actually so i thought it would be worth diving into and trying out the logic itself i think it's appropriately tagged at a medium it's definitely a doable problem it does require a bit of thinking though and the implementation itself i'd say is a bit heavier maybe uses a few extra lines of code than what we're usually doing in one of these questions so with that said if you haven't tried the problem yet pause the video try it out come on back but uh otherwise let's just jump into it so we're told that the question is about implementing a basic algorithm for candy crush okay so i'll kind of skip through this and i'll explain to myself through a couple of examples but we're given a 2d board okay and at any given point uh at board i j if we're given a zero that's a blank okay it's a blank cell anything else is fair game it's not blank we're told that the board represents the state of the game following a player's move uh now you need to restore the board to a stable state by crushing candies according to the following rules so uh for those of you unfamiliar with the game first off i'll go and go check it out and second of all for those of you who are just as a refresher if i pop a bunch of candies and then i'll have some new ones for the existing ones will fall that might form some other combinations which will then uh you know crush more candies and it'll keep kind of keep dropping downwards so we need to go through all those iterations until we're done with the crush and we're not just doing one step we're going to do everything from our initial state until stable state all right the rules more formally speaking are as follows if three or more candies of the same type are adjacent vertically or horizontally crush them all at the same time these positions become empty okay after we crush everything simultaneously if an empty space on the board has candies on top of it the candies will drop until they hit a candy or the bottom at the same time no new candies will drop out the top boundaries so we don't need to worry about new candies coming in all right um after the steps there may exist more candies that need to be crushed like i said earlier and if so we need to repeat the steps above if there does not exist any more candies that can be crushed so the board is stable return the board as it is you need to perform the above rules until the board has become stable cool they gave us some example here and they walk through it basically in this state in the game right over here you see that the ones and twos here form kind of a non-stable state so those will be a non-stable state so those will be a non-stable state so those will be crushed and after that happens we see a bunch of fives come down and then those will be crushed and i'm walking through this quickly because i will give a slightly more detailed description in a second but i think it's for the most part understandable um and we're going to do the song place so there are a few major steps that we're going to have to take here and understand this problem first off we need to understand what it actually means to crush something well we know what it means to crush something but i want to get particular about what we're going to be doing here if i've got a whole row of candies that is not a row that is like a diagonal it's a bit better i got a row of candies here right and let's say that each of these candies each one is represented with an integer okay that's how we're given in the question let's say uh all of these are one and then this one is a two because we have three in a row here that are ones these three will all be crushed we somehow need to tag these and make sure that they go by charlie what i want to clarify is that this if we had an arrangement like this where this is a one and maybe the rest of these are you know these are our threes and it's a four what will be crushed is still only these three the one because we have three horizontal ones adjacent we will not be doing this l formation here the reason we're not doing this l formation is that column wise we only have two ones okay we don't have three if we had a one right here and now we had three ones in a column then these would be crushed as with all of these so the these are jsons we make these kind of l shapes only if we've got a column there's like a row or a column both of which have at least three okay i just wanted to clarify that because i've seen some confusion over that before so i wanted to make sure we get that out of the way so uh apart from that let's really think about what's happening like how do we actually how do we determine which candies we're gonna crush first off the solution isn't going to be particularly elegant per se because we do almost in some way need to do like a simulation and a full walk through of the board every time so i'm not gonna i don't have like a super uh you know clever hacky way to get through this quickly and quite frankly you don't need to the solution we're going to go with is a good one you could argue it is kind of brute force but i believe it's the best way to do it if you guys have a better more optimized way to do it let me know down below but as i was saying we will we're essentially going to do this we're going to have three steps okay the first step is going to be let's actually tag elements that are adjacent to each other that have three or more repetitions of themselves so what we're going to need to do is we're going to need to check rows that's going to be one thing so maybe our step number one is going to be check i'll say check plus tag rows and we're going to figure out how to tag these appropriately okay once we do that we've now checked our rows one by one the second step we're going to need to do is to walk through column wise and then through every single column see where we've got three or more items that are ready to disappear so i'm going to write check plus tag columns all right columns now after we've done that we've somehow tagged these things and again we'll talk about exactly how we're going to identify them but after that said done then we actually got to do the dropping okay so i'm just going to call that gravity and when i first did this or the first couple times i tried this i thought this was the hardest step it actually it's going to be very similar to another very common utility problem and i'll walk through the solution to that one but it won't be as bad as you think big picture though this is really all that it takes every single time we do one iteration of this we're going to have to ask ourselves are we in a stable state yet okay so we're going to have to keep some sort of track of are we in a stable state the way that i think or i think i know we're going to do that is we can just keep some sort of boolean at the top of our function and with this boolean variable we can say well if we didn't check any rows and we didn't check any columns or tag them excuse me i should see if we didn't tag them as saying there are three or more candies that need to be crushed then we haven't done anything and at that point we're just we're done and we're going to return what we got it and that's our stable state so let's actually talk about how we're going to do this tagging of the rows and then the columns although the logic will be the same let's say i've got i'm going to make another row here so what i'm going to do is i'm going to say it's a bit longer so make a whole bunch of these what i want to say is this i two one five this is what i'm gonna do okay so i need to go through and visually looking at this we realize we understand like okay there are four ones in a row here i'm going to need to tag these and i want to get rid of these so one thing that you can think about is you just say okay well if i see four in a row if i see three in a row let me start making these zeros so i see these three in a row i say okay well this would be a zero this will be a zero this would be a zero band those are going to disappear and we get to the fourth and it's like wait or you know what even better yeah let's see you somehow checked all four of these and you said to yourself i see four in a row they're all gonna be zeros fine fair enough the issue with that is what if we had a column coming down here and this column had a whole bunch of ones right but we were first checking the rows so it's like you weren't gonna check you can check the rows and the columns all simultaneously and grab all these so there's a bit of an issue in dealing with that how do we actually tag these such that we preserve the i'll call oneness since the number one the oneness of this cell so we can compare it to other potential options as we're going both across and up and down well since all these candies are going to be positive numbers and we're told that in the question and down here in the constraints we can simply say if i find numbers that match in absolute value then i'm going to tag them as being the same what i mean by that is this i'm going to take a slider of with three at a time and move it across my rows the reason it'll be with three is because what i'm interested in is tagging an entire block at a time i'm going to start by looking at these three units right over here i see a two and one and a one these three numbers are not equal their absolute values are not equal and the absolute value is important you'll see why in a second so i'm not going to do anything i'm going to take my slider of 3 and move it over this way now i'm checking these well this equals this and this equals that so they are all the same so these two are going to need to be crushed but instead of setting them to 0 what i'm going to do is i'm going to set them to negative 1. i'm going to set the negative 1 i'll set them to negative 1. the reason i'm going to do that actually let me do this let me get rid of this first so i'm going to set the negative 1. the reason i'm going to do this is as follows now i'm going to take my slider move it one more over i'm going to move it one more over here and i'm going to say to myself okay well sure these two are negative 1 and 1 but the absolute value of them is the same and that's going to be the key thing to understand here if the absolute value is the same i can then also mark this one i want them all to be negative because i want them all to disappear the reason this is important is because now let's pretend we go column wise so we have these are negative ones i got a column here now and this happens before the crushing remember so we're doing we're tagging the rows we're taking the columns then we're doing the crushing the gravity if these are ones i and i'm doing that kind of my same block of three comparison looking this way vertically now i can still say to myself okay these will still match up so i want to crush all these in this direction too so these are gonna be set to negative one and i'm gonna take a step down and look at these three again we're in the same position this is gonna be negative one and what's gonna happen is like so what i've just described here is actually our first two steps it's both uh tagging our rows and tagging our columns we're just going to switch the order of the for loops but i mean fundamentally the way we're moving this window will be identical in both cases so this explanation kind of covers the tagging and let me know down below if you have any questions if that doesn't make sense what we're then going to do about the gravity is this is imagine that we now have i'm going to draw the rest of the board here i'm just going to make it up and maybe all you all want me to see my face here dude there we go move myself out of the way so i got well when i lost that i've got you know my rows here and what i'm going to do is this is i'm going to say i'll put enough a bunch of random numbers easily out of them seven three four five i'm just i'm filling in random things here really it doesn't matter eight nine ten four five six three seven dead um these now are all going to disappear how do we actually make them disappear and this was actually an awful example so what i should have done is something like this i should have added a row above here all right so what i'll do with this row because we actually need something to drop i realized i should put these at the top i'll do 7 8 9 10 11. okay well um what happens now so i need to go through this gravity thing the way that we're going to drop these is going to be column by column the reason we can do this and we don't have to do them all at once is because we're not actually going to be doing any other popping until this the gravity is done then we're going to check if we need to do another iteration through our function to do more row and column if i look through this function i'm going to start looking from the bottom up if i see a single number that's um rather let me take a step back the explanation i'm about to give is actually identical to the moving zeros problem okay if you haven't tried that one if you don't know it look it up i'll do a very brief description here but i won't get too in-depth because get too in-depth because get too in-depth because it is a separate problem that i consider more of a utility problem um so if you think about the moving zeros problem in the moving zeros problem we essentially have we're given an array like 1 0 3 0 12 okay and then what happens is we need to move all the zeros to the end sorry so we keep an index at the start and then we walk through a form and we tell ourselves every time i see a non-zero non every time i see a non-zero non every time i see a non-zero i'm going to move my this index pointer up by one and i'm going to swap that number to my previous index pointer okay the reason i'm doing that is this one swaps with itself it kind of stays where it is um then i look at the zero three zero twelve my index now i've moved up to here okay and imagine we saw this pointer i like it in a regular for loop but we're gonna be walking through one by one this is a zero so it's not a non-zero this is a zero so it's not a non-zero this is a zero so it's not a non-zero number so we keep going our pointer is here now our pointer sees a non-zero number so our pointer sees a non-zero number so our pointer sees a non-zero number so what it'll do is it'll say one three put it where the last index was keep everything else as it is 0 12. okay index is moved up by 1. we see here this is a non-zero number we see here this is a non-zero number we see here this is a non-zero number this right here sorry this is a zero number so we don't do anything this is a non-zero number do anything this is a non-zero number do anything this is a non-zero number so we put it where we had our last index which is here 12 1 3 12. we saw this zero and we saw this call here we move our index up by one from here since we reached the end of the array everything from here on outwards must become a zero right here we only have one item we make this a zero if we had any other numbers those would also become zeros and so on and so forth we've now shifted all the zeros to the back that's exactly what we're gonna be doing here except i'm gonna be shifting the zeros i'm gonna be shifting the non-zero zeros i'm gonna be shifting the non-zero zeros i'm gonna be shifting the non-zero numbers down okay every time i see this negative or not even every time i see a negative number every time i see a non-negative number every time i see a non-negative number every time i see a non-negative number or i see a rather positive number because i don't want to move the i guess we're gonna move the zeros every time i see a uh a non-negative number i'm i see a uh a non-negative number i'm i see a uh a non-negative number i'm going to be uh doing this whole this business with the index and saying okay let me whatever that number is let me swap it down i'll bring it down as far as i possibly can maintaining the original order and then when i get to the end and i've kind of picked all my numbers down what i'm going to do is i'm going to fill everything else up with zeros because now we have blank spaces there okay i know i rushed that explanation just a bit but like i said it's a utility function that kind of comes from a whole other problem so i didn't want to go off on too much of a tangent and explain that let me know if you have any questions down below um i hope that kind of made sense and that kind of wraps up the explanation on how we're going to logically go about this we're going to tag the rows we're going to tag columns we're going to do this gravity business we're then going to check if we haven't if we did a full walk through the report and we didn't make a single change that means we're stable at that point we're done we're just going to return the board at any point if we make a change so if we check a row or a column we're going to say okay we're not then we made some changes so we're gonna have to do one more iteration after all right that's the high level uh that's the high level of it so let's have a look now as let's say let's have a seat let's have a look now at how we would actually go about implementing the code here so let me move this out of the way i said we want to do three things so actually typically we always like to do error check i'll start with the error checking then i'll say my step one was crush rows okay our step two was crush columns and our step three was gravity okay at the end we're going to return the board and again that'll kind of depend on if we're done or not um so first thing for error checking we're just gonna see if we're given some you know bogus board we're not gonna although i think we're told we're given a legit board i'll do it anyways just for completion we'll see if not or just return the board as it is now what i'm gonna say is i'm gonna have some variable called done okay and i'm gonna presume that every time i start a function i'm gonna say that i'll assume my board is good the reason i'm gonna assume my board is fine as it is because when i jump into these items over here and i realized oh damn i gotta make a change it's like never mind we're not done okay so then we're gonna set it to false so really what this means for us is we're gonna return board if done is true otherwise we're gonna call candy crush again on the board we're gonna so we're gonna return candy crush of the board all right um so that's kind of our i can just anchor us our beginning and our end and now this is where we're really gonna jump into the meat potatoes we want to start tagging rows at a time okay so if we're going one row at a time what we'll do is for r in range and the length of the board and then we're going to want to go through the columns okay so we're going to say for c in range length of border r except what we're going to do is this since we want to have the remember how we want to have we're not just going to be looking one item at a time three items at a time if i want to have a window three items i need this thing to end a bit earlier right because otherwise i'm gonna go overboard so what i'm gonna do is i'm gonna say we'll go on to length the board minus two all right so again that's gonna allow us to stop at the third last column so we can check everything that's ahead of it now we are essentially gonna have three numbers that we're gonna wanna compare the first item in that row the second item in the third and rather when i say rewinding within that sliding window we have i'm gonna call those num1 num2 and num3 and the way i'm going to define them as follows is i'm just going to take the number uh board of r oops board of r the board of c i'm going to take a board of r and then c plus 1 because we're looking one more item over that's the second item of that window and then the third item of the window we're going to want to be equal to board of r c plus two now if you guys remember this business that i set on first we're going to check the rows and then we're going to check the columns well since we need to compare and make sure that we're looking at the same number and we might have already tagged one as being a negative i'm just going to go ahead and take the absolute value of all these numbers to make sure that what i'm looking at is actually going to be a good uh comparison so that the one in the negative one will match up as being you know the same value now i'm looking at these three items and i ask myself when do i actually want to go ahead and tag these i want to tag these if they're all the same and they're not equal to zero so if num1 is equal to num2 and num2 is equal to num3 by logical extension you know uh one has to equal three then and what i'll say is and number one is not equal to zero then what we're going to want to do is tag all these and make them negative so not am i going to want to tag them i'm also going to want to say done equals false because it's like we're not done we're not complete i made some changes so we're going to need at least one more iteration to walk through and make sure that there isn't anything we got to change the way i'm going to do that is this i'm going to say that i want to take my board of rc and set that equal to now this number that we have over here we already have it's its absolute value right so what i'm going to want to do and i know it's equal to the absolute value of this i'm going to want to take that number one right and i'm going to want to set it to its negative value number one is always going to be an absolute value okay it's going to be an absolute term i want to make sure that within the board i'm taking that positive number and setting it to its negative all right i'm going to want to do the same thing here board r uh c plus 1 is equal to negative num2 and finally board of r c plus 2 is equal to negative num3 all right what this is going to do for us again is essentially say let me take whatever number i have and negate it the reason i want to make sure that i'm negating the absolute value is because it what if it was already negative and then i negated it i would then make it positive and then it's not going to it's not going gonna crush out how we want it to so i'm setting them to negative by making sure that i first take its absolute value and then make it negative all right let me know if that makes sense if you have any questions again as always drop them in the comments down below but that's basically the logic for crushing the rows crushing the columns as you can imagine is going to be very similar and what i'll do there is i'll say for c and range and the length of the board at zero so we want to go one full column at a time okay and then the actual the row size that we want is going to be also in kind of in increments of three and what we'll so we'll say that for r in range and the length of the board it's leaked peak and the length of the board minus two again so we're going to want to go downwards but only up to the third last item because we're going to want this sliding window of size 3 perpetually going downwards and we're going to do something similar we're going to say number one is equal to the absolute of all these and maybe i'll even get smart here just copy paste it um except we're going to change one thing since we're going downwards this is going to be r plus 1 and this is going to be r plus 2 because we want to look at the items that are one and two atoms below where i am not to the left or right then my condition here stays the same and actually the rest is pretty much all the same again barring this fact over here this is going to become r plus 1 and r plus 2 because i'm looking downwards not to the left or to the right and so unless i've made any glaringly obvious mistakes which i don't see right off the bat but i wouldn't put it past me um this is actually the logic for tagging the items that we want to be crushed upon like when we actually do our gravity we're going to implement that gravity step right now for the gravity step we're going to want to go let's think about this we're going to want to go column by column right so logically then what we do is we'd say c in range length of board 0 kind of like what we were doing here and then what we'd say is the following is we want to do two things one is we want to say move all um positive numbers down so the actual cells we have the legit ones and on top of that what we want to do is we want to say we want to save up put zeros in for uh missing pieces right so we're gonna have to replace those the stuff we move down we're gonna have to replace with zeros and everything that's kind of come down so in order to move those down this is like what i was talking about the moving zeros piece i'm going to start with um we're going to go one row at a time and we're going to go let me think about this if we want to crush one at a time so if you think about how we had that array um and we went from left to right imagine tilting and now column wise and we want to go bottom up right so what i'll do is i'll see for our in range uh and the length of the board minus one so we want to be at the bottom and we're going to go up by one unit at a time until we get to zero um well first things first actually move this um yeah actually that's fine um i'm going to want to create that index that i was talking about so index i'm going to set that equal to uh length of board minus 1 meaning that's going to be the first place where i'm going to replace uh so it's a really weird angle i just realized where i'm going to replace my numbers with that as we're dropping them down and that's where i'm going to bring my greater than zero numbers to my actual cells so what we're going to do is as follows we're going to say if board of rc is greater than 0 what's going to happen is this i'm going to set board of index c equal to board of rc so i'm effectively moving that number down and then i'm going to set index minus equals 1. so that means that i'm going to move my index one upwards and saying everything from you know everything below me needs to stay from here on up if you don't move anything else on the rest this needs to become zero because it's like everything else is dropped all right once we do that i'm sorry i try to brain fire um once we essentially do that so that'll actually bring everything down to where we want it to be once that's done we've got to fill in zeros for all the missing for essentially all the missing pieces um or for everything we brought down that's now still duplicated again think about the moving arrays moving zeros to end of array problem we're gonna fill all those in with zeros so we'll do another for loop and we'll start this one from where the index last was and we're going to make it until negative one and we're going kind of down by one unit at a time like visually we're going upwards but the row index is going to be decreasing and so what we'll do is we'll say board of r c is equal to zero there and in fact again now if i haven't made any glaringly obvious mistakes we're actually done that will be that gravity function is the one that will bring all the items down and like we said if we've at any point made a change to our rows or columns by tagging them done will be false as and we are not done so when we get down here we'll return the board if we're done otherwise we call this thing again and i think this should be self thought it might yell at me if i don't do self um otherwise we're not then we gotta do it again in this next rendition i start by saying done is true if i don't crush a single row if i don't tag one that is if i don't tag a single column done will be true so we're not going to have to do any of this and maybe you know i guess if i think about it uh maybe we can just do this if we if that's true so maybe i'll say if done we can actually just skip this won't really save us on asymptotic time analysis but in real time it might do something for us so i'm going to move myself up over here and try to run this code and see if i somehow got it miraculous on the first try which i didn't it looks like i'm about to timeout so there's something that i missed here let me see if i can find the air and i'm sorry guys i just caught it's been a long day this is not true like this if statement i just threw in here for fun and sprinkled like confetti like do not do that um so the reason this never actually happened is because that means that you know if we never said done to true like we're not actually going to end up in this loop we're never going to crush anything because we want to be crushing this if it's not done right so that means if we tagged anything then we want to jump into there so i think if i run this now it should be good there we go i was seeing like the opposite i was doing the opposite of what i meant to do so i'm sorry about that i hope that didn't cause too much confusion the problem is solved uh i know this was a bit of a longer video i do apologize thank you for those of you who have stuck around i hope it was worth it um this one look like it's a bit of heavy lifting to get this done i'm sorry i don't know what this tag is there we go i know it's a bit of heavy lifting to get this one done it's not the easiest problem in the world it's involved but i think it's an interesting one nonetheless and so let me know down below if you guys liked it if you like this longer style video um and as always like comment share all that stuff um i'm getting hungry i haven't eaten dinner yet and it's getting late so i'm out of here i'll see you guys next time and yep study hard peace
|
Candy Crush
|
candy-crush
|
This question is about implementing a basic elimination algorithm for Candy Crush.
Given an `m x n` integer array `board` representing the grid of candy where `board[i][j]` represents the type of candy. A value of `board[i][j] == 0` represents that the cell is empty.
The given board represents the state of the game following the player's move. Now, you need to restore the board to a stable state by crushing candies according to the following rules:
* If three or more candies of the same type are adjacent vertically or horizontally, crush them all at the same time - these positions become empty.
* After crushing all candies simultaneously, if an empty space on the board has candies on top of itself, then these candies will drop until they hit a candy or bottom at the same time. No new candies will drop outside the top boundary.
* After the above steps, there may exist more candies that can be crushed. If so, you need to repeat the above steps.
* If there does not exist more candies that can be crushed (i.e., the board is stable), then return the current board.
You need to perform the above rules until the board becomes stable, then return _the stable board_.
**Example 1:**
**Input:** board = \[\[110,5,112,113,114\],\[210,211,5,213,214\],\[310,311,3,313,314\],\[410,411,412,5,414\],\[5,1,512,3,3\],\[610,4,1,613,614\],\[710,1,2,713,714\],\[810,1,2,1,1\],\[1,1,2,2,2\],\[4,1,4,4,1014\]\]
**Output:** \[\[0,0,0,0,0\],\[0,0,0,0,0\],\[0,0,0,0,0\],\[110,0,0,0,114\],\[210,0,0,0,214\],\[310,0,0,113,314\],\[410,0,0,213,414\],\[610,211,112,313,614\],\[710,311,412,613,714\],\[810,411,512,713,1014\]\]
**Example 2:**
**Input:** board = \[\[1,3,5,5,2\],\[3,4,3,3,1\],\[3,2,4,5,2\],\[2,4,4,5,5\],\[1,4,4,1,1\]\]
**Output:** \[\[1,3,0,0,0\],\[3,4,0,5,2\],\[3,2,0,3,1\],\[2,4,0,5,2\],\[1,4,3,1,1\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `3 <= m, n <= 50`
* `1 <= board[i][j] <= 2000`
|
Carefully perform the "crush" and "gravity" steps. In the crush step, flag each candy that should be removed, then go through and crush each flagged candy. In the gravity step, collect the candy in each column and then rewrite the column appropriately. Do these steps repeatedly until there's no work left to do.
|
Array,Two Pointers,Matrix,Simulation
|
Medium
| null |
238 |
hello everyone welcome today 27th of remember eco challenge and i hope all of you are having a great time without much to do let's look at today's question is product of aris accept self in this question we are given an area of integers and we need to return another array that represents the product of all the numbers that exist in that array accepts the number at that particular index itself without much to do let's look at the example here and the first case is one two three four as is given as an input array and it output becomes twenty four twelve eight six how so if we multiply all the remaining numbers except one what will we get 2 into 3 into 4 is 24 so we get 24 here if we skip 2 for a second and what are the remaining elements 1 3 and 4 so product of 1 3 and 4 is 12 we have 12 here let's forget three for a second and what are the remaining element one two and four what is the product of one two and four it's eight and let's forget four for a second what are the remaining element one two and three what is the product of one two three it's six the answer added becomes twenty 24 12 8 and 6. i hope you understood this example and now look let's look at the ppt and let's try to devise the algorithm together so let's move on to the ppt let me just take a pen product of rxf self lead code 28 238 let's take the same example that was specified in the question the input elements are something like this one two three and four and in the first go let's define the prefix product moving from the left to right direction i'll tell you why and how it is helping us so let's for a moment let's define a new array and in that array we will write prefix product rather than prefix sum and will move from left to right direction so let's build this array first we have one at this place so one stays here next we have 2 here so 2 stays here 2 into 1 is 2 this becomes the product becomes 2. now let's move ahead the next element is 3 into 2 is 6 so we get 6 here 4 into 6 is 24 so we get 24 here now we have completely built the first array moving from the left to right direction let's create another array moving from right to left direction and this time it will also be the prefix product let's start the process the first element that we 4c is 4 so 4 gets there next is 3 so 3 into 4 is 12 so 12 gets there next is 2 into 12 is 24 so 24 gets there 24 into 1 is 24 so 24 gets there now we have appropriately built both the arrays one moving from left to right direction another moving from right to left direction and both these rs represents prefix product pp let's call it prefix product i hope so far the approach is clear to you now let's talk about how are we gonna use these two arrays to actually come up with the solution so we need to do some visualization here and let's talk about this particular element what is the answer at this particular element it would be equal to the elements to the left of it the elements to the right of it so what are those elements we have one we have three and we have four so the left product turns out to be equal to 1 the right product turns out to be equal to 3 into 4 which is nothing but 12. so how can we exploit the arrays that we just created to actually retrieve this value it's simple what we need to do we simply need to look up to the element in the left array the left product prefix product array at i minus 1 index this particular index and we need to look out for the right part using the second array the write prefix product array and add i plus 1 index so this value gives us 12 this value gives us 1 and product of these two would lead to the answer let me just take the pen to highlight it better for two we will use two values one highlighted by this particular index in the left prefix product array other uh in the right prefix product array at i plus one index so this becomes i plus one index and this becomes i minus 1 index and now we have appropriately set a value for 2 in the answer array which is multiplication of these two let's proceed ahead let's take another case where we are using this particular index and where will we look out for we'll look out for this particular value and we look out for this particular value 2 into 4 is 8 so we will write the in the answer array value 8 here let's talk about this one uh what is the value at i minus one index in the left prefix array it's six what is the value in the uh right prefix array there is no value to the i plus one index so we'll use one as default so one into six gives us six let's move ahead and the last element that is left is one so again we'll do the same thing we look out for i minus one index in the left prefix array prefix product array and there's no such value we'll use one as default we look out for the value in the right prefix product array and it's 24 so 1 into 24 gives us 24 becomes the result so we have four values dumped into the answer array which is 24 12 8 and 6 which is an exact sync with what was expected in the answer and this is what we are going to do so now let's move on to the coding part and let's solve this approach here i've defined three arrays the answer array for swirling the final answer the left array for generating the left prefix product the right array for generating the right prefix product and let's take a variable write prefix product and initialize it to one and let's loop through the input array moving from the left to right direction and a builder left prefix array prefix product array this one with each iteration we multiply left prefix product with nums dot i similarly let's do it for the right prefix product as well take a default case right prefix product equals to one move from right to left direction with each iteration you multiply the current element and update the right prefix product at i8 index and once you're done with building these two arrays uh let's extract the left product let's extract the right product and let's multiply these two together and build our answer array the important part is to have those corner conditions written appropriately if i is greater than equal to one then only extract the left prefix product array otherwise use one similarly for the right part and in the end you simply return the answer array let's try this up four milliseconds thirteen point five percent faster you could improvise it uh but in terms of space i at least i believe we are using three rs you can reduce this to a single array and in terms of time i don't think you can improvise it because the time complexity of this approach is order of n you are iterating to the input array three times and that's it you can't go beyond reducing this value to log n or something space complexity since you're building the answer array it is order of n this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
|
Product of Array Except Self
|
product-of-array-except-self
|
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`.
The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
You must write an algorithm that runs in `O(n)` time and without using the division operation.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[24,12,8,6\]
**Example 2:**
**Input:** nums = \[-1,1,0,-3,3\]
**Output:** \[0,0,9,0,0\]
**Constraints:**
* `2 <= nums.length <= 105`
* `-30 <= nums[i] <= 30`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
**Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
| null |
Array,Prefix Sum
|
Medium
|
42,152,265,2267
|
1,458 |
Hello Friends Today Due To Loot That Is About Your Swapna Dosh Amritlal Khanted And According To The Last Test - Chup Ke And According To The Last Test - Chup Ke And According To The Last Test - Chup Ke Nishchay Ko Fold Doctors Without Sab Theek Hai To Ke Simple Rukh Begat Dekhtein Dance Fix Into Cash Withdrawal 3D Raghu Dixit post a professional way to make a statement on bill discrimination is ready that aapke sunao su a statement from distant servi hai 200 most of the music play on how to according to hero MP3 a positive Sudhir Raghav on hai acid servisu superkid.pl The British Ships and its Significance of short note on that Bihar to dam anti ok sunna hai and national and foreign sight this suit ankit ko 220 pinpoint arrangement for telling 15th and then and country ok but in this page to show how to extend here And in the decisive test match, six under this paste, I am thinking ok so go have a quarter inch right final fight with him, why not, I am a business tab, where is the last 12, it is modern and difficult that this channel and soil Everything they didn't tell about a system to fix a hydrate oral administration at midnight children that your sweet-dish loop is happening with Python who that your sweet-dish loop is happening with Python who is the topper Ajay that your ₹100 note is Totally's birthday wish that your ₹100 note is Totally's birthday wish 123 Videos Recent Notification Fix Just Three Record This Tweet A Specific Gravity Hai Ne Is Meet's Approach Shoot Me 10 To 12 Hello How Can Share This Post On A Wednesday Student And Addictive Co Unmute With This Temple Run Is But Because 0f Vacancy More Depend For There is a request from the group admin 169 that the court should again give contractual appointment, that I think tank refilled test post - 3 I think tank refilled test post - 3 I think tank refilled test post - 3 test posts on Thursday, how to connect with saint, a bird flu positive and a college kid did this in the central hospital like this By the way, the second robber and don was the da so this is the valley university me invest example festival subscribe to find you fragrant are the pound inches of these donkeys tasting this dam acting so then the next point is that his to pointed spots were 15-minute show were 15-minute show were 15-minute show that 19th admit and textile nine 2,000 that 19th admit and textile nine 2,000 that 19th admit and textile nine 2,000 maintained a product of the festive printout this condition in which was the specialty of Bihar province was a part anti a sacrifice a heart pattern is away at the time of head secretary Anoop
|
Max Dot Product of Two Subsequences
|
sort-integers-by-the-number-of-1-bits
|
Given two arrays `nums1` and `nums2`.
Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not).
**Example 1:**
**Input:** nums1 = \[2,1,-2,5\], nums2 = \[3,0,-6\]
**Output:** 18
**Explanation:** Take subsequence \[2,-2\] from nums1 and subsequence \[3,-6\] from nums2.
Their dot product is (2\*3 + (-2)\*(-6)) = 18.
**Example 2:**
**Input:** nums1 = \[3,-2\], nums2 = \[2,-6,7\]
**Output:** 21
**Explanation:** Take subsequence \[3\] from nums1 and subsequence \[7\] from nums2.
Their dot product is (3\*7) = 21.
**Example 3:**
**Input:** nums1 = \[-1,-1\], nums2 = \[1,1\]
**Output:** -1
**Explanation:** Take subsequence \[-1\] from nums1 and subsequence \[1\] from nums2.
Their dot product is -1.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 500`
* `-1000 <= nums1[i], nums2[i] <= 1000`
|
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
|
Array,Bit Manipulation,Sorting,Counting
|
Easy
|
2204
|
441 |
200 Hello Guys Today They Have Gone Too Far From This Question Off List Switch To This Arranging Coins is Fickle Mathematics Question That's It Nothing Else Ok I Am The Giver In This Your Encounter Is Ok This Is A Game Of Money Ok Now Who Am I You are making a staircase but a simple question, I understand well, now you are making that Chakli from Banaras Staircase, it is possible that which of yours gets shot last, then it is possible that the last step is not completed, then as many as Step beyond that is complete. You have to do whatever is its value. How many steps are we complete? Okay, this is for example. Look at this. If you have input 251, okay, then the first step is complete. Okay, one is done, the second test is also complete. Okay, so is this third tip complete? Not ours, the third one is not complete, so we will take two. What is saying is that our two steps can be completed, if you have given only five ponds, then it means that it has to be given a little bit of eight. Look, I mean the last chapter is not complete, but the first chapter is completely complete. Okay, the first 3 are complete. Okay, how to do this, the biggest question is if we execute it, then how to do it. Now look at it carefully so that the staircase is on the side. This is life, is it two? It will go by adding 3G. This is a phone. What should we say? This is youth, this is two, this is three, this is four. We can walk in the flu. Yes, of course we can walk. Why can't we walk? Let's go among the people. Let's fold, what are you doing? Tips, how many steps is ours done? A for ant organizer, we did not go to play zero betting, either it is not there, then he will take it is ok for anti end and we will follow him till the end, ok, we will take it back. Presented. Wife, this means Raghuvar is automatically fine, now look, write, come, now we will have to take a counter courier, controversial, what will show us, brother, how many steps are our complete, now look, what to do now, watch this dance. This N minor came that this garlic is zero two now what to do is to rape that your ok what is written will you still understand otherwise CMT plus that attend qawwali will be done End - 5th attend qawwali will be done End - 5th attend qawwali will be done End - 5th 84 What are you writing? I am not able to understand anything. Mother is going through it. Now explain to us. Give us what we have done. From one to the end, we have taken the steps. Now we are looking at each strip, if it is the values. If 1100, this means yours. It is just, it is properly complete, okay, if it is not zero, then we can increase it by one step, okay from this point, which one can we increase, okay, then we will account plus, okay, and what to do in the next. We don't understand anything, this is what we mean, how much attention we have to pay to make that step. To understand properly, what we have done, we first see that and - is meaning we first see that and - is meaning we first see that and - is meaning if your next step which will be if your given. What are the numbers and if the valley of the rectangle required for the next step is greater than zero then what will happen if we can make that then the valley of the counter will be plus, this means that we have added it to the tap, okay and that After that, what will we have to do? We will have to decrease the volume also, we will have to do so many steps. 4 Support us, 4 steps. If we increase, then even four will have to do it, right my brother, thinkers, we have done it - okay, now I have broken this condition. First I have - okay, now I have broken this condition. First I have - okay, now I have broken this condition. First I have checked that if your one state is now if it is for and if your f5 is absolutely negative here, it means that you do not have so many points, what will we do to complete the dog, we will back it and come out. It's a simple thing, okay, you should understand it, okay, it means a lot, it's simple, see it two-three times, see it two-three times, see it two-three times, you will understand it, okay, I have written the first test, ThinkQuest Five, there is something like this here, quickly run it. Let's share it and see, let's take it in a player and read it here, hello dot cp, I have program color name, hello six sixes, I can do something like that, hmm, first I will give the whole forum in the description, is it okay to mix it well, is it coming or not? Okay, and if the actor gets dizzy, what will we do for one, if I get dizzy, let's check for a minute and set Agriculture Karo that we will shave the first case, now we will see if there is anything else to come, how many fours of 40 Thana-3 A: Thana-3 A: Thana-3 A: How much is a person and then type it and then there are some quick typical maths questions. Okay, in this you have to use your mind to follow because the use of pallu is because it is showing the text. Our first So many questions mean the school, the commission, that means the school, okay and all this, how many complete scooters are available with us and what we will do every year - we will keep available with us and what we will do every year - we will keep available with us and what we will do every year - we will keep doing it, okay, it is simple, this is a very good question, so let's turn to the whole. You will find it in the description. It's okay to check and it's okay to like the video. It's okay to subscribe the channel and share it. Share as much as you can. Thank you.
|
Arranging Coins
|
arranging-coins
|
You have `n` coins and you want to build a staircase with these coins. The staircase consists of `k` rows where the `ith` row has exactly `i` coins. The last row of the staircase **may be** incomplete.
Given the integer `n`, return _the number of **complete rows** of the staircase you will build_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** Because the 3rd row is incomplete, we return 2.
**Example 2:**
**Input:** n = 8
**Output:** 3
**Explanation:** Because the 4th row is incomplete, we return 3.
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Math,Binary Search
|
Easy
| null |
212 |
WhatsApp to Ajay, then on this question you have got a Today Hey, character Jhal and by adopting the word Ay, you have got Sapoch Hai, okay, this is the 2nd year of the character, Today Hey is 84 and along with it, there is another string. You will get makeup that Priyanka is coming, okay, nothing else to do, on both the inputs you will get R which is for middle, here the words are tight and speed train. Now you have to find some inverter on this board. So make an error list, put that word first and tanker two multiple words can be found, if you find any then hand the list and attach it to MP land 2. Okay, let's see once how we can find this square on this. So basically l this cross and something like that, there is a guy, you can go top bottom left right that all these, okay what does it mean, this AB keeps common money, the first loop is ATS, to send it to you here. But let's start, so now how can you do your wish that if I audited the next stop is this, I will only look at its four adjustment sites. Okay, on the top and on one side, there is none, but on the bottom, this is and here this is tight. Here it will be made, it is made, okay, then again, look at its four Edison sides, below it is a strip reading, now half an inch below this, the complete introduction and whatever is there, if I have got it here, then it presses. On this, parents, set the alarm on your answer key, then turn off the alarm, PM does not add the victims anywhere on this, so this will not be found even in Word, next stop 8, now if you search for this guy, he is here. 48 directs to the website so it is not here they are not here also so you here we grow that is here also and what becomes next on its four medium size then exists here torch light After here, I got the game monkey, okay, so here I got TV, okay, this is the thing which is shared on both of them, it is PHP and Tasty Center, this is the last one, so it can, so I got this here, okay, next monkey. If you have then this is the complete take, which has no side effects from all sides, this guy is tight, you will not be able to get the complete take, you had to take the complete answer, this is the vote, you can do it on any order, edit if you want, make it like this Even if a pet vessel can be updated on this border, if it is soft or if it is printed then the output will come to the border from one place. Okay, one thing that you have to pay attention to on this question is that there is one character here, it is the same word twice. Can't use bar means let's take an example of Ajay Singh 's LG 4K. If some word like this was 's LG 4K. If some word like this was 's LG 4K. If some word like this was asked to be put in front of you then it is fine then here it executes that it is tight here, it is used. Below is the mail. Idhar bhi hai vr are used kiya hai to ke album vr yeh chaar bunde don't become that friend in the end of it dobar sakti hai so you can't use the same word twice for a string ok this don't use it again You can do it, but you won't get this guy, it's fine, if this was there instead, you would have gone up and used this guy, then the tax would have been broken, but kids, this is not the case, okay, let's see some constraints in this question, this is the word dot length. This can be as much as ₹ 3000 which you can use for your as much as ₹ 3000 which you can use for your as much as ₹ 3000 which you can use for your function find words. Here you have got a chess board. Father-in-law, this is a character board got a chess board. Father-in-law, this is a character board got a chess board. Father-in-law, this is a character board and here it has been made with words, so the length of these words printed can be ₹ 3000 and Its chairman was can be ₹ 3000 and Its chairman was can be ₹ 3000 and Its chairman was World of Oil Total 10 also word maximum can do maximum then you have toss board and throw will be of evening and he can go maximum to help torch light come here ok so the question was this and It is okay to pay attention, it has to be done from Uddin stall, so when I solve it, I will keep it expected that it will give you backtracking that if you do not know the back but what is it, now its explanatory video has been made, its gender will be on the description, now that You can go and see, okay, you still have to keep the back, who uses it and fold it, then okay, so basically what we have to do is, find all the words which are there, keep this one. This one is two wear okay so what can be a solution grab this guy and search here over 15 so found here this big tries next step is to catch either next sunday white I got this word that the next World Cup has gone here, it takes action somewhere, it does n't have any effect here, it doesn't do anything, it does n't do anything, it doesn't do anything on the whole board, so this word also couldn't be found, we got the press. Hold on to the club, daughter Ira, don't keep looking, Lord, it is here but it is not there anywhere on its edit, if its width was not there anywhere at the time, even from here we will not be able to get it completely, we do not want just one word. This word should be complete, the diet should go ahead or again or on its direction that one side is this and then one is tormenting against, here it is being fulfilled that now if I got it the next day then there is no further or if I have got it then I will try. We will reduce it by starting again and it is not here also, is not here, it is not here also, a diet is coming here, that is, we started working here, its Edison, there is no powder anywhere in it, but then here our work stops at night. Then do the next form and if it is not there anywhere then it changes completely that it does not make reservation, this way the course work will go but it is not very correct, okay, or why is it not correct for the service, you catch a class, if you assume. Take this cross, Khinvsar grows and I do not have any heir, then what work do you do for another year? I travel all the way for this too, I hold this one, and travel all the way on board, hold the next one, travel all the way on board, all the way to catch Rakshabandhan. When we travel the whole world, then basically you are checking a person whether he exits or not. Instead of this, we can do something else. Here, instead of selecting Roberto by holding Select Specific, we can do this work here. If there is anyone then I am here, if I add one more here, test and twenty match by subscribing, okay, so when I come here, let me see if there is any person, he is starting, right now I am in some express I am not talking about the explosion, right now I am sitting and talking a lot or Kuch and Gram also take it and Ren take it, okay so there were two people who were going to be roasted here, that is, both of them are also my He is a valid candidate and the growth is fine. After this, what do you do after this, which element is safe in the mother who setting, is there any other element or other character among them, does anyone have it, then you search, does n't he have it? Even if he does n't have it, no one else has it, so father, there is no need to free you from here. Height, the first guy is right. If the next guy doesn't exist, then it is not right to go here. Second never, which one is like this? The second one is his. What will you do from here, the first one should be tied and the second one should be this, on both of them he will have it, both are married candidates, after this, the famous defeated, after this again, if one is needed, then here no one has it, so here We will do direct radish at least one person should be there then search we are not on the net no need to think flash lights go on darshan was wrong determination team then they will help in this for TMH 2018 both legs so if If it happens then it works for and then because it is not found, we do the same thing again from here and from here so that we complete both the tasks assigned here and apply this algorithm twice. If we were able to achieve then it was basically a fielding job, I want starting, I want that, then mix these two off, then if the next one is needed, then these two are French braid, French, then both of these are 1 crore on the electricity board and the other guys here. This is on low flame, I think it works very well in comparison to the previous one and let's see, okay, this is my dam and these are the words, this is the basic riff, see here basically what I have to do is, how many prefixes should I have? The match is happening and we have to keep them together. We can try to achieve this through an example. Let us understand this. If I had put all these butters in the study, then it is fine for all these wards. Basically, there would have been a problem in printing. On this dry fruit. After this and two more is church from one text and this is the ending height here I add one more word some after this another change goes and this is also a pending of one word okay then bind that this I have closed it, add this also and these are okay, try this, how will it help, then it will tell me, it is a shot tied to work and its following people, like if I want to start working from here, then I Asked my tri, right now I am on the route here, okay, right now I am currently on this blog and I am on the route here, okay, I asked you some guy, does it start, then he turned it on, yes friend, that means. That there is some word which starts for this, how many full notes are required for that and this one? Okay, this is absolutely correct, so it will say, now there is a next word on either of those two, so anyone's explanation here? There is no word torch light here or I am not right. Okay, then we will look back at this Yagya. Next number is right here. Okay, after this, we will ask him, is there any person after that, who has this Yagya? Next letter, here he has this tight, so we will find out from here that the athlete is someone who has something like this in trading, okay, so we will come here and basically you will get this note with you. We have a okay next is right there after this so I will message the third letter to the third alphabet is that this so here near this in the bottom children pet is just team that you have got this one director's award and all this There are words, you have to search them, okay on this board, I have written all these words here on a try and the red ones in it are all the pending words of this word. Just like if you are a common journalist then this is CP. Thakur and friend means warning, then there is a chord here, so C A R D Chaurasi Sumiraun, I will go to this board to work, it was about to start that I will give the option, if happy comes here, then this one C is basically a root. When we call this function, we will start it on this seat and this C will get the root of its stranger. Will you do this? Will you consider all the words which start with C? Okay, something on its sperm try. Words are registered which start from seat, all these are height, so here I came from this but I asked him do you have any children who are tall, he said yes, there are some children who are C chart tight, this brother confirmed. Now we have limited it till this point, which years can be taken after this, after AP it can be taken and Sibal can take two, we can keep two closed, so now we who are for this purpose, to explain this. It would have been half easy to lose that the first character is like this and there is a note here, the CO was left here, the routes were done, the chest itself was found, now it will call its four, so when it will call the bus, either it will Will give him the C note, okay, this C note, he will get it, now the tight cigarette is doing the note, so the till has arrived, I have got it, now we have to find it back, now we have to hear that. In which there is Hawaii after C. Okay, so whatever it is, it will ask from this point, do you have any such letter placed on it there, okay, which is clear, if it will be visible that and on Hawaii, basically Dhairya Restaurant is this. Time data is there in the same panel, there is no word there, it is not there at all, so you will not be able to move ahead by going to it, after this 84, this is Samhita, walk after pregnancy, this is the planet, there is no reason for this, so we have added it. Called will wish if no one does it then it will be Paul means it will be liter in between the function is ok will be sent back next day then where can we seal then it can make us tight ca a does any such products do again We will call another one this year, you will get the same description, check it will ask if Aamir has any other hair style, then here is this channel, starts like CCR, Senior, DSC and CT, if you do some work in this way, then this app is Exactly how do we go here, what will this one do, this one can go and so on, so if this one goes, what will Is there any word in words on which third character is accepted? Look here, only 'else' and ' Look here, only 'else' and ' Look here, only 'else' and ' teacher' are 116. If no one teacher' are 116. If no one teacher' are 116. If no one does it, then there is no use in leaving. You will go from here on your own, so your next second person is that. R is right, that guy will do the wall and he himself said, this one will give permission, okay, what else will he do, will he improve? Do you, the one who has children, the one with R will say that he is a guy, that at least one If there is a person then archive for all went through, pay attention here, then this is the other person, this is also someone's pending, tight, if this is someone's pending, it means that we have achieved more on the board and this note was some kind of guiding. This is a valid word, I have found it tight here, CR, I have found it, play the list, ok, now till the next day, what else can I say, we will not go, this is backtracking, Monday morning we are going to visit the center, ok, we Here ₹ 1 visit the center, ok, we Here ₹ 1 visit the center, ok, we Here ₹ 1 OTP can come and more can also come and what will the note do, it will equal and this arm hole will allow, so now what will this one do, will it ask from the arm hole, so is it normal that every year there is someone who When it starts back then there is no one here, so this one will call, this one will go back, he will not work, he will go to the next day, this one will stop Jhala, will do pedicure, absolutely did it and gave ok, what will he do, so now he will ask CLR I have got so many words, friend, I have got so many words, after R, now I have to see Delhi, a height, if I want to see it alone, and will say yes, the one with 'do' a height, if I want to see it alone, and will say yes, the one with 'do' a height, if I want to see it alone, and will say yes, the one with 'do' adjusts the word, but see here, there is no end on someone's card. We will not add that there is no network here, okay, let's move ahead, then put it in this here and exit used to say this, what to do, where can this go, please, this heart is not in control. Only Divya can deliver like this, there is no speed, we ca n't even explain the method like this, so come on from here, we couldn't remove the curtain anywhere else, everyone everywhere will have faith in you, so now Paava Commando Gaya, take you back. And went to and have more options, part-2 part-2 part-2 torch light card options, you had the next college, well, after RR, it will be difficult here, it will be tough and who is going to be the commissioner of this next, so I too. Don't get confused, just hey friend t8 yes friend, what to do, he will say CR, I have got so much word, I have got so much, now I have TV, then you don't have it at all, take this, still it got spoiled, this too has been returned to someone else. Will take it, put it on Advani, put it on DP, put it on TP, now if all three are hit by this, then what will he do with the king, he has already called once, now he will call again, okay, which note did he get, he would go back again. That one semen was found tight and here and the condition also depends on it. Calling the We are getting extra one after the other, one is not here, so if you are not there, this pattern will come and its entire work has also been done, it will go from here too, so it is fine, but it is complete Komodo, did we get CR, a word, we are tight. Now let's change the turning point and see, now the input, we have shot the CO and seen that the car has been found, now it is the turn of the next patient, we will do our work, we will give him the route, okay, this is the sim, we will start the work, we will give him the route, we will say, what do you see? If any person also has this setting, then here it is never starting, if a pin is inserted tight, then its work starts and is over, it will be folded again, it will expire and fried, so here no word, excel, starts, this. Return will be done ai no one starts Khulwai no one starts aa and also does not happen from and 30 is needed but after all these we will go tips Tiwari will be shocked he will be given form he will ask form if any minute If it is clear then yes all are third tier wide ID price reason high they are ok again this is absolutely perfect it will ask from all four of them right there it is ok this note will first do another not ok this is ₹ 10's this ask ok this is ₹ 10's this ask ok this is ₹ 10's this ask from this note do you have any child that starts with one it doesn't have any tight came back from here and went to the that over here and the hair will feel that now it will ask arrow you tell what If you have any knowledge and if it starts then this team has one knowledge and if it starts then this will also work, this eye will work and will equalize tight, we have come to the other side, so now the one with this eye no longer has the stomach after this, okay There is no one coming, there is no toilet, all these people come, he will definitely do it and will give more, hey, what will he do, the wife will mix it, is there any person who is white, RCB will ask, do you have any person who needs the white money back, he will see this note that This is the same guy and he is also some guiding. Okay, so we will add our hair pack and word e.t. Action private has come, e.t. Action private has come, e.t. Action private has come, okay, right now the logic is not limited to one, okay, so now let's see how to do home improvement in this logic, okay, in this question I am changing the structure of my note a little, that is why what am I going to do in my notes The subject is written, it is for keeping all the children, this note will remain the same for now, there is a way to type note on it will make 40 boards, so let's make an end mark here, I am not taking it under force, okay this bullion I am taking a string in place of A string of this TR This trick is basically how it will tell me if it is pending or not, then there are only three records of these people, the string that will be near P is by default because it is not related to anyone. Okay, the ending is CCR, all together, okay, this is C, it has a tasty and panel, it has such a request, there is a tap, it is not landing, it is not a front, so such a request has to be made, okay, this is a request, this is the ending, so it has Which is tasty and this is basically complete, this category will be kept that CIA and it has CCR, this word will be complete, whoever has the word is someone landing, it just does not have the word, it is null, that is medium, okay, now see our What will this gem be? So it will be one. You will do the main function for us. Everyone on this board will take a chance to be the starting guy. Tight Eye Looper 020. The numbers on the World Cup are - Tight Eye Looper 020. The numbers on the World Cup are - Tight Eye Looper 020. The numbers on the World Cup are - 190 so A minus one and here we are. We will call a difficult function where basically the entire work has to be done which is to edit the words that are being created and do our com and on power this route is ok and will give this, so now basically let us make a small track. I have got this guy, the current guy, if he is the latest one over there and he has got the route, then what will he do, will he decide whether there is any child abuse in this route, who keeps the stomach straight, so basically here now the vote is I take that in the chapter, whatever is placed here on the board is the character f4 exists CHC that exists s child that you are the root that this is written correctly, I have written the child of the root ok, this is of the root so that there is no child of this, how many seats This board is what it is, if it is not there then we will do the return forms. Height, it can be towed in two ways, if it is positive then we will return it and if you come, we will do some further work. If we have to do what further, we have got the same. That what can be made next, that can be made, all four of them will call for years, tight call 4 Om said that Bigg Boss BF will get trapped, that some of these cowards will change here, you will be able to reach only then and this time Guava is of frustration. Will give it to the jersey and the root is less dot side. Okay, which child is this, so now we are C, so this C is noting the chapter, what will happen with this, it will be applied here and there on all four directions and all of them will be C. Will be taken, then what will he do? Look at the next level here, he calls the place of ' Look at the next level here, he calls the place of ' Look at the next level here, he calls the place of ' puja' and gives a note with 'C' puja' and gives a note with 'C' puja' and gives a note with 'C' that 'I have received this signal', 'What has I that 'I have received this signal', 'What has I that 'I have received this signal', 'What has I learned?' He will learned?' He will learned?' He will check whether this is what Ramesh is, exists as a child of fruit, the roots for it are already there, so if it is not there, you are here now, if not, then we return it and like if it is there, then you are again on four drops. You will call, this will become rx1 juice on your four directions, this time 120 will go You do not have any charge which is This doesn't work this second one again call on the dude and this time it will give it to him mixed with this note tries so gave this one now this one and over here further we saw that dude this hilarious Ka one ka koi chaal ho hoon ho else ho right, this song is repeated again for then exists as a child of a, so here one ka's shoulder executes, oh this will take the form, see what this is, that's the ending too Is the height here if it has the root near the root blacksmith root's root then this is our write a queuer and the root is the child and if it has the train which is STR not requested null then the notification means it is ending so we add this one. We will do it if they are from here, then who will do it for four years? Okay, right now, I have not got some cases under Delhi, how come, now we do so much work first, then the village will be handled by the delegate, okay now that from here, there are four directions. But starting from here it will be like 'I will 204' that on starting from here it will be like 'I will 204' that on starting from here it will be like 'I will 204' that on this line three plus that if it wins here then it is a mistake and we will vote for DLF face, 'I will is a mistake and we will vote for DLF face, 'I will is a mistake and we will vote for DLF face, 'I will give my vote' and will give our road and it is not made yet, give my vote' and will give our road and it is not made yet, give my vote' and will give our road and it is not made yet, okay it will be made here Ajay that node protein plus to new note Aditya we will also add all the skin a stringer schoolen on the words here from fruit dot in taste those minutes will be okay they will break again will break and will give share list reply to alerts his name was jhaal What have I done with this that it will do all the work then it's okay, you make Davis call edifice ₹ 50 like traffic video fans ₹ 50 like traffic video fans ₹ 50 like traffic video fans club inter board and second I have to take induction I love my India JP and third route type them The route of is done and the last viral list on which I will add my answer is I am ok let's complete my work here now let's see the first task was to see the rice do I unite any of the routes Child, so how can we write it? We will have to write a description on the name of effigy root dot child root. A public static price node will have a note that there will be tiles, next there will be something else and that the letter on the board is mapping on board of IJ. For if it is equal to null then it will not exit, we will return the other vice exit from here we will process in. Okay, what will we process, if it unites my, then first of all check if this is a child root. This one should have ending that notification tap has history, that notification is wedding, arrest him and then call on four drops 2014, it would be better to make node child, you will not have to write again and again, so basically this guy that this We are talking about okay here if the child art that SPR is this note a personal if it is not a tap answer daughter that child S PR will do a lesson and then Chawla recent Airtel will dad then thrown here which one they are a block multiple Times can be accessed, it will also have to be entered that let's copy this, Jhal torch light will not go to root here, Hello friends, child will go here, when is it ok, and if you want to go in four drops, then a big plus one by - 100 plus. One this then a big plus one by - 100 plus. One this then a big plus one by - 100 plus. One this minus one we will do all these and the last task is no block for updates multiple times and no repeat packing work here everyone had gone here how can we come back from here also make it special to stop the edit It will be necessary to have a garden A Related Post New Kurian 15 Okay, if it is a stick then you will know about it Yo has been given and it also needs to be received Jhal is okay and will be middling before calling By the way, dad I have one more suggestion And after the call is completed, we will pause it again. Okay, and we will not go to the visited person. If I have seen this request, then we will return from there. Okay, so this too, our work has been completed. Much of the front was the same as before but here I have to match the data and to match that I have to try to use night and all, brother, like this now one and that, what is the work, I checked the call here. I have put it that I plus one is my mansion belt no it also needs to be handled Iceland Prof Jhal ok then oil 100 and even if this board 's Lanka is too much then we will return also if there is 's Lanka is too much then we will return also if there is 's Lanka is too much then we will return also if there is spirit then he will get scared and Here, if he does not do this after taking tea, he will be returned as Yagya Voice Child. If there is an ending then add it and do all your work here. Chair is complete, adopt it, you make it, complete the try. Is it there or is it just needed for the function in the future? I have to do the work of these shirts. I have to do separate work to handle the insults. This is what they can do. People's route will be opened to inverters, so this spring, there is no public petition requirement here. Hai tech world alarm set pin gas that here node was current request purpose. If you want to keep it simple then to keep it simple we can make it outside also. Nothing has been done on this note. Here we have put kumkum. Nadia static function and here we have to send the note also. Note 6 were current and skimming. We will add all this on the current that it will be heavy here. Okay, wait, it is a match, now let's cut the ball swing in these T20 games. Current note dot This character on the sides that this - A If it doesn't juice is equal that this - A If it doesn't juice is equal that this - A If it doesn't juice is equal to null So add this one there Minute I have to add this So that will create a new note at this point And later we will People will update the current that cut from that side, here we have to tell basically and walks, then add dot request 2s, it has been appointed white, everything else is fine, here you can work separately in a tractor, also made here. You can buy a new note of Rs 2165 and this is not at all the case, it has become cancer, it has become something else and has also become addicted, we have used each other, we have taken each other on a date, this work has been completed, let's see how I have done my duty here. This case has not been handled and there could be a mistake, but on this one, I am doing it, okay, in one case, I will show you more, if something like this happens in the past, share the thread and then here again, better. Here also CLR tight would have worked here, my password is to stay away from it, here it can become prostitute and here too it can become sewage and right, so this test goes there once and runs it and does its work. So basically the length is and the number of rows is for the column, this is the aegis of add yr bt which rac Hello friends pay that this is my matrix something like this is my entire board of great and after this there is only one note to do this point ok this is my input car I should get more tutti but the one who is my friend Lotus we will duplicate it twice right yo type ko makkar this is my house again so what does it do start from here first I will make my house try, it is here C. A. D. R. This guy is tight, he started my work from here C. He has come, he has come, the word is complete, so I have added it to the list, but later I will roam around here completely. Have you come here ? Have you come to this? ? Have you come to this? ? Have you come to this? Work has started again from here. Got the team. Got here and got the torch light. So its second grand has also arrived here. I am this I am here. I am this. How will I prevent it? We can prevent it in two ways. What is the difference? Let's look at what they have. When it comes to removing dimples, there is a solution. Set is fine. If it is not deleted in set, then you What can you do, here you are getting only Ajwain Sir, you can put this one car on the set and later you will get this car too, this one will also go on the set. So kids, don't keep it like this, add one more, it will delete the light or don't add it, you will have only one more net, but this is not the right way to do it, why is it not the right way, if you have a very big spring on your tri. There is one here, understand that by doing it like this 10,000 times something like this here, understand that by doing it like this 10,000 times something like this here, understand that by doing it like this 10,000 times something like this happens, there are thousand and 10,000 happens, there are thousand and 10,000 happens, there are thousand and 10,000 and if you have a very big board on your board, I am full of exams in it, okay what will you do, there is 10,000 here. But what will you do, there is 10,000 here. But what will you do, there is 10,000 here. But once you add it later, now you will make that answer again on your side, whatever you try, if you use it here, then you will go to the one, this one is big, the next one is average, the next one is stomach, the next one is also this, now just a complete friend. You will make a string, it will be so big, I will itemize it here, then sir will see that it is a duplicate, will not add it was tight, I was lucky, what can be another solution, so which word do you point to sale? You point to those words which are of type like you get it once, half an hour, from here it means like this, I had it, I did it once, I got a job here, I saw, I got a SIM, I saw, I got it And I saw and there is a pending here, I added it and now I will remove it from here, that is, this railway line, whatever I have done, I will give this running Rajwada, it has a West Ring, I will make an equal school, I will make torch light, then you will come again when it will be true here. If C A D R is already ready then it will not be added tight. If I am here again doing the vikar on this channel that this is where I added the guy and then here the child but still the request is null, I removed it and added it. If you have increased it, then here it should not be at that point, it is coming tight only once, okay, it is going absolutely fine, but still if you look, this time is too late, zero point 4875, here it is known. It won't do, it's too much, what is he doing in one, he is making a complete answer, an example settings will have to be shown, whereas if you have any try table, it's some time from now, goodbye, this is just one guy, so much It is big and you have here the cross which is a box for this award, I am now closed, the net is that I will run Britain right before, after reciting this mantra, this thing does, it goes here, it texts, it is here, it expresses, it is here. This is how it is done, you will go till the bottom, add everything, there are a lot of cases here, these are flights, of course, you will create the one with white office, you will run your Airtel East African, till there the identification will go till this point, then you will return from there, I am fine. This time and next year, if you start the yagya off office, then what is its number, this is a completely different guest and it is going on, right, this is my first bandh, the one below does this, the one below reacts, the one below practices. Not only this, after this there is another choice from here and this one should come back here, this vinegar tightens his co, so basically you have a guy because he unites on the prime, now you will make him bigger every time he is here. Time is spent on VAT on such an oily site, okay, so how can you reduce this work, so once you have completed it, delete it, once you delete it, you will not go to it again and the example is here. But first of all, if you have become constipated, I wish you could comment a little here, this is RDS, type your word, now what I am asking you to say is that you delete this band, delete Edison ne, now. If there is someone else here, this is this, then this can be updated, so what will you do from here, if there is a cut here again, then it is not a sin here, torch light, the calling ahead is tight, if you see another example. On this, which RSS is it that this word and teaser adding in these sections is fine, then first you will go searching for this, it has become an RSS, then remove that one from here that this is not a wedding, it has become an RSS. So you will insert it from here, Ajay was removed by cutting his stomach inside, at this point, if you look, this guy does not have any child, there is no tight channel, there was just nothing below it and this is the most The last value of Airtel was Lite, there was no need in it, if you come one after the other, then here is another word triad which is being used by someone, it can be allocated if in the future, basically if seen, now I have a child. Whoever is using the word tight, if you make TRI di next roti here, now that is why you will come to us, TCR ID has been blocked that this is not the ending, now attending has been removed, see what happened again, this is me, someone new. It is not there and it is not even pending in itself that basically as soon as its children become zero, it has just come here and created a word of course. If it does not have any child then you delete this oil and it will go away. This is clear, so now look at this, both of them have gone away, remove this tight, as per I have done, give him a son, he has no right to be here and this is filled with water, but he still reacts with acidity. Otherwise, this is a separate button, that's why we have diarrhea again on our home feature, we searched for this year and that Sachin got completed, oh man, we got it from here and we got it from the last pizza place. That when you keep going back, this recurrence of you keeps going, then we have already killed this guy and unmuted him, okay Amma, this guy is lost again but has become a writer, no one is near him. There is no problem, delete it, now after this update the height, there is no file after this, read it, you can also do this work with less flash light, when can such a problem arise, if you searched CO City Reporter then it is not there. A test will come, it can be UTS, here it is right and next to it has become a small letter, so it is connected here, the ending is here, so use it, was it removed from the admin, okay, so look, now we will remove it. If you don't do it then we will remote it because after this there is a child which has done something else etc. CO dot s pets has kept the whole world in voter hold type, we cannot delete it, ok, how will we achieve this task of deleting it? So those of us who are not going to do this, when we delete it, we will basically have to inform our parents that you are my parents, I am going to remove it, remove me, then go and set the tap in its place or torch light and set it to the side account. You will have to keep it, basically if you look then it is not ready for you, how will you know that you have the earliest big produce, if all the nine go to Lanka, then this will happen, you cannot understand and check, okay, so we are here to do the work of an account maintainer. What will be the task of maintaining the account for the one, then it is the root, it will have an account, child current, that is the point, as soon as I add those people, we will go to it and shrink the control Vishwaroopam, ok. Okay, later we will add one that its account for depositing FD account for deposit which is Amrit like I did one side of it, made it one account, this sacrifice is deleting how many different words are there below me and then next I will go and wait for 150 rupees, I have a child for it, then close the account, okay total, how many have it started, it has a style, it has zero gait, it is tight, after this I edited the duty, then what will I do? So what else is it going to have Maya Sides, so no, it is going to climb, it is going to be used, so let it have one angle, okay, basically how many members are there in it, we are computing it is AP, okay, what after this? It did not have an oven, it had to be added to the flash light, what was the use of new bread? If you have children, please change the comment to English. Okay, yes, it is absolutely correct. Okay, bye again, if you select the team, then close this account. Do this and this account is the hero by default. It was tight, but we will cross the back track from here. Well, what we will do is where we do not have to go, let's see if I first search a word that account. Which is there, two steps, one account, two, the children and one of the children given of children, such children are okay, it is on this that you will be cleared, happy where RBS, this word, if you come to visit, it is okay, let's go to the first seat, you are on the route. Papaya is tight, the apk file is economic and there is 1 end in it, then you will use it and remove it from the end, it is okay, it will go to the edifice again, it will go to all the children, if it comes like this, then you will reach here on Davis. I went all the way till here but now you will start battering from here, I have to go back up, I am tight, I did not use this guy, I used F4, after this there is no charge for it, so no call will be made, the only closed channel is Colonel's. If Share is taped then further calls will not go through what will I do after that I saw that it is closed and leaf, it has zero on the account at that point, so now leave it here, we will not notify the parents but we will explain this. When this reaction goes up, it will go back to the bone, then D will check his child, it is okay, whatever it is yo style, if it has started on the account, it means who has any child of course edit but there is no vandan He has a net, he has no choice, zero, it is used, so what will he do, see, my friend, I reduce my child user by one, I make a hero, oh I now what happened the next day, I also removed it. I did it to zero and had to remove it, after this DK also there was no one else tight here so there is an account degree in it or it is also done with that gas then we will go here in this I have only one underwear but this also became lips Now more writing has been done, it will automatically delete the ribbon, if you write Amazing under R, there is no person, it has become a cat, we will also start the site on the account with this, again you will see that it was the child of which The work was done for him, now he came out with dowry, it has been deleted, tight, he will delete his account, he has become a forest, the forest department is destroying this temple, after that we will give more above, now while doing extras, the sequence will go like this, the channel for which he is working will be seen. The work was done just now, that child has come and he has one side, which means that it is correct, it is not completely completed yet, resident Roshanlal, nothing has been done, but a person expresses that train, how will we live this work, he is at his place. First of all, you will have to create an account. Account request 204 Whenever I add a new child inside here, I have added the current account. Okay, I have added the current account. Make it a child. I will get it here. Let's come back, now my entire current is complete, the person for whom the work would have been done, this child had become a young man, but if the child does not want equal to zero, then it means that the accident of the root has reduced. Product Account - - Height 18 And Product Account - - Height 18 And Product Account - - Height 18 And if my which equation because we don't remove that note do n't remove the tight notes here will consider then you have the not agree to avoid it electricity which condition is that it is the root C is that the team You should have both cave lifts at the back, if you find this pick, it will be on and I will make 1000, here I am Aarti, friend, okay now, two or four cloves, what will happen here you have used less gas, your account is zero. Show those who will go back. After using it will be shown that if the account is from then it will automatically make a decision saying that it has been used as well. If I can't go then C This team has been used before, this is the one I have used. PAT tree has been used in BTS UP and we will go to it, I will go to an advice, it has been seen that a child zero has already been made, it will reduce itself too, now coming up, it will rise, later it will bring again. Cross on Crossword On the board that CLTS got here later here again C ad party unites Paytm app also got it Nee Jayenge Hum Lekar Jayenge e.t. Got it, will meet again. e.t. Got it, will meet again. e.t. Got it, will meet again. Here I will check that the person who is current has kept zero and four with him. The person who is current route has kept zero with him, so we will not go further and will return from here. Okay, so let's work here, whatever is the current or route, we will return it across the home account. Okay, this removing work is also done, tighten the thread, this is what it is doing on the car, let's remove the input and see the thread. Thriller Deposit 134 is better than before, it is hands free, it is okay, so she got one.
|
Word Search II
|
word-search-ii
|
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique.
|
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
|
Array,String,Backtracking,Trie,Matrix
|
Hard
|
79,1022,1433
|
279 |
Hello, this is a perfect square and take it four times and it will become the total. Okay, what else can you do? If you want to give it as a return, then let's see another example like if there is 26, then how can it become 26, so this answer becomes maximum 26 and How can it be made and how can it be made then how will we prepare it is very simple ok it is a very simple question why will we make us if we take them out then how will we come out 149 16 25 ok now what do we have to do now we have to write then perfect square And we have to make the target its 26 and we can take one element any number of times. Okay I can take another 25 once, I can do it like this, or I can take it once for Lenovo, I can do it like this Okay So what can we do, will we take it or not, okay so if this Okay, so what will I do with it, I took it once, so what is it still my friend, this is it, now I take it back one, okay so I will be targeted, it will be 24, okay like this because I can take man back from ok so my function what will I call I will call that I want minimum number of square number this is my target so I can take back so my hey remains the same so my ai also remains the same meaning i0 remains the same and what has happened to my target? my s has become off i and if i take calls on this number then what will i do then my target will remain the same but now i am not taking it so what will i do I will do OnePlus One, it is ok, I will call Plus One and my target will remain the same, so it is ok between these two, now for whom will my function be called, now in note take, if I am not taking that then I will not take OnePlus because I have not taken it, the minimum of these two will be our answer, okay now what will be the base condition, what will be the condition, either this is my target, the target should become zero, how many squares are required, okay and the second match condition. What will happen if my first condition is not met that my target becomes zero, okay when can this happen, now if you return then what will we give in return, then we can make it, if we can never make it, then what will we return by giving infinity? And if the target becomes zero here, then we will not take any element from it, then we will return zero but zero should be infinity, okay, we go to the target mines, now we go to its storage, how can we store it, so Look here, what is the meaning of this call, so this means that 149 1625, this means, solve this, then who is this function here, it is repeated again, after solving this, what will we do with this, we will store it. So where do we store any target, what will it become, then it will be target plus van is ok, we will have to make it till 26, so now its code is first of all, perfect square, its size shoe is ok, this is the problem with plus van, minimum point is ok. Is it ours and the perfect square How will we call Perfect Square It will take so many calls Okay Thank you thank you
|
Perfect Squares
|
perfect-squares
|
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`.
A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not.
**Example 1:**
**Input:** n = 12
**Output:** 3
**Explanation:** 12 = 4 + 4 + 4.
**Example 2:**
**Input:** n = 13
**Output:** 2
**Explanation:** 13 = 4 + 9.
**Constraints:**
* `1 <= n <= 104`
| null |
Math,Dynamic Programming,Breadth-First Search
|
Medium
|
204,264
|
92 |
wasn't it quite here dude tech encoding stuff on twitch on YouTube check the description for all my information I have a patreon if you want to support me on there I do the premium problems discord is a great way to get in contact with everyone building the community there and then you can follow me on github too thanks for that reverse link list - we thanks for that reverse link list - we thanks for that reverse link list - we did a reverse link list one recommend learning that one before this but we'll go over it a little bit here this is a medium problem a lot of likes pretty easy it's not too bad same as reverse link list a little twist so reversal link list from position and the end do it in one pass so instead of reversing the whole list so instead of one two three four five becoming five four three two one we're only reversing from position two to four inclusive meaning the position two is reversed in position four and position three all reversed so you can see here we have one two three four five so this is position one this is position two so we start here so from position two - three - four here so from position two - three - four here so from position two - three - four these will get reversed so from two to four it gets reversed inclusive and you can see the output is two three four reversed is four three two so it's just one four three two five that's it not too difficult so what is the strategy here well the strategy here is you just use these counters kind of you can make your own counter or you could just use these and decrement them just get up to the position so just you know loop up to the traverse the list of the position so once you get here and then reverse this portion of the list and then just connect it make sure everything is connected and then you're good to go I mean that's it's pretty easy so to start off we'll just check if had is null so we can return null if it is because there's nothing to be reversed or returned or anything then we will set up our nodes so previz gonna be equal to null list no - current node equal to null list no - current node equal to null list no - current node will be equal to head and then we'll say okay while M is greater than one we will do pre equalization a current node equals current node done next so this is just traversing until we get to the correct position correct positioning and we're going to be decrementing m and n we're tink reminding both m and because we're going to do a similar loop later on where we say well n is greater than 0 so we want to decriminalization we get 2 we only have to go and spaces to get to the end of you know what I mean so like for example like and we're passing in 2 & 4 example like and we're passing in 2 & 4 example like and we're passing in 2 & 4 right so the first we're just going to traverse so the current node starts at head we go current node equals while M is greater than 1 so 2 is greater than 1 we go okay this node let's go to this node so then we get here it breaks out of the loop we're at the right positioning so previous will be here current node will be here and then we can start to actually do our second loop while n is greater than 0 n is 3 now so we would do a 3 to 1 and you know that it's 0 so you know what I mean that's the whole point of decrementing n the only thing we're going to need to do as well is create some variables one's a connection variable list node variable for we're setting that to prove this is gonna we're gonna use this to connect to the head of the reverse part of the list I'll explain that in a second tail is going to use to connect to the end as well so we're just gonna set this one to current node so while n is greater than 0 obviously decrement and while we loop and then this is just the same as reverse linked list so I'm hopefully you guys are familiar you just do you get the next node as you traverse so we're at position 2 we're saying okay get the next node 3 and then we're saying okay current node dot next is equal to prove so we set the previous node as the next node then we do previous current node and then current node equals next node that's why we needed the next node variable so we didn't lose reference so you grab the next node before you update it so don't lose reference then you set the previous as the next node obviously this is just how you reverse checkout the reverse link list for a more in-depth reverse link list for a more in-depth reverse link list for a more in-depth explanation I did it one time pretty professionally and yeah that's how you reverse it and then we're gonna be returning ahead at the end of all of this but we're gonna say okay if connection node is not equal to null then what we're gonna do is we're gonna say connection dot next is equal to prief and we do this else head is equal to prove and let me explain this is probably the these are probably the only tricky parts is we do that Chino's sorry I don't know what's going on we do this because connection is previous before we start so when we end when we get out of this loop when you're if you know anything about reversing a linked list when we turn 2 3 4 into 4 3 2 it doesn't exactly look like this it's it is like this but there's no reference from 1 2 4 3 2 is all set up like though the list gets reversed but there's no reference from you know where we left off at the that's why we make this connection variable because we break out of this loop up here at the correct position where we want to start reversing but we need to connect you know the 1 so we'd see 1 we'd get here and we'd be like okay let's reverse all this one in 4 3 2 are not connected so we have to connect those down here and if connection is equal to null then you just set head to prove because that would just be the reverse list right and then this is pretty much the whole solution there's only one other thing is this tail variable that we also need tail dot next is going to be equal to current node and yeah that's that should be everything current node dot next not a statement sorry about that I don't even or that is line 20 current node equals current node next that's how you traverse sorry about that there you go and you shut tail dot next to current node because tail is the end of the list so you want to connect sorry let me think about this current you loop through tail gets at the current node - yeah tail is that tail is the you - yeah tail is that tail is the you - yeah tail is that tail is the you could see if you were looping through and you get to this initial point it current node leaves off at 2 and you want to set to dot next equal to current node at the end of so you're sorry I'm not that good of explaining I guess but this it's a little talk to explain the current node after this is the head of the part that you want to reverse so this chunk it would be like - in this chunk it would be like - in this chunk it would be like - in this case you want to have a reference to that with tail so that once it's reversed you have to we connected the 1 to the 4 3 2 but we have to connect the end of the reverse part to the rest of the list so that's what tail necks does it equals to current node because I'm the last iteration loop current node equals current node necks so it equals the last part of the list Susa tail dot next to current node to connect all the lists together then you return head to get everything you know straightened out and yeah that's it I mean I think I went over every part in detail now so let me know if you guys have any questions check out the reverse one first if you didn't understand I know I was fumbling a little bit there but these are long I don't have you know I'm doing hundreds of these so I don't have time to just keep redoing or editing all this stuff so I think just watching think ever on that sports me and see you guys in the next one
|
Reverse Linked List II
|
reverse-linked-list-ii
|
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass?
| null |
Linked List
|
Medium
|
206
|
1,726 |
hey everyone this is steve today let's go through one legal problem 1726 tuple with the same product uh let's take a look at the problem first given a random number of distinct positive integers written the number of tuples a b c d such that a times b equals to c times d where there are constraints of a b c d so the abcds are elements of nums and a doesn't equal to b doesn't equal c doesn't equal to d so none of them are equal meaning they all of them are distinct all right so and all of the numbers given in this array they are all distinct positive numbers all right let's just take a look at one example two three four six all right the output is eight why eight because there are eight valid typos let's take a look two six three four this is a valid tuple why is it valid that is because 2 times 6 equals to 12 and 3 times 4 equals to 12 as well so a b c d a times b equals to c times d both of them are 12 right and then we can take a look at the rest all the other seven tuples so two six four three still it's the same two numbers right two six and four three but they permitted the number the permuted the order so it's a different permutation so it's always two six three four it could be three four two six or six two four three right you see permutation two six four three so three and four order changed or six two order change three four but it doesn't didn't change so you see this is completely permutation but all of them is the same two integers times together so they get the same product it's 12. all right a total eight valid tuples with two pairs right one pair is two and six the other pair is three and four but with only two pairs we can form a total of eight valid tuples so the output is eight right all right and then let's take a look at the second one is given one two four five and ten these five integers the output is sixteen why sixteen because there are sixteen valid tempos so see here this one a b times these two integers time we get multiplied together we get 10 and 2 and 5 times multiplied together we get 10 as well so a permutation of these two pairs we get eight right we get eight tuples that's the first eight tuples the product is 10 and then we have a second product which is 20 2 times 10 is 20 4 times 5 is also 20. so another pair right another two pairs two ten four five we can have another seven tuples the permutations of this one right so a total of 16. so what can we undo from this observation the observation is that we can calculate since all numbers in this given array are distinct positive integers what we can do is that we can find all of the total distinct products and then we can use a hashmap so for the key of the hashmap is going to be the distinctive product then for the value of the hashmap we can store all of the frequencies see how many pairs could form this could form to this product right and if the frequency of this particular product is more than one that means at least there are two pairs right and then we can find all of the permutations right see it basically comes down to we have say uh if there are two pairs that's going to be c of 2 right so that is going to be there is no way to type superscript and the subscript here so this is basically a combination of two they're given two options we'll just take two right and if there are three pairs that could form to the same product say 24 or 48 there are a total of three pairs that could form to this product now what's the number of permutation so that's going to be given three options we'll pick two at a time so how many permutations total in this way we just add up all of the total permutations when we go through first we form the hashmap second when after we form the hashmap we'll just go through the hashmap take a look at its frequency if it's greater than one that means we have at least more than one pair that could form to that couldn't multiply to this product then we'll just calculate is its permutation then we add up all of the permutations by permutation we can simply calculate it by using a simple math yeah that's the idea so now let's put the idea into the actual code let's take a look right let me erase all of that so first we'll have a hash map both key and value out of type integer hashmap and then we'll just go through this length plus g plus one just go use a master volume to go through this integer array and then we'll have product that is nums i times j and we'll just put this product into this get all default if it's the first time we get this one product default is zero otherwise we'll just increment the frequency right and then we'll have um another variable this is the final count of total permutations and then we'll just go through so first with this lasted for loop we have built out the hash map the key of the hashmap again is going to be the distinctive product right of every single pair that multiplied together what is the product that is going to produce and then the value of the hashmap is the frequency of how many pairs in this given integer array that could form that could be multiplied together to form this product with this hashmap form we can key set we can just go through so frequency map get key so we'll check if frequency is greater than one oops if it is greater than one that means there are at least two pairs right one pair formed by two integers another pair formed by another two integers that means there are at least two pairs so if there are two pairs we'll just form the permutation could be understood as simplified as frequency minus one times frequency divided by two and then times eight why do we need to so first okay let's do this one step at a time so what does this one give us this is basically a combination of the given numbers see given there are three pairs will take two pairs at a time so how many options that we can form right so if i'm if there are four options we'll take two at a time remember we always form two tuples right so and every two pairs we always have eight permutations right so you see here this is two six three four either two six or six two compared with three four or four six it's always eight permutations right for this example there are two pairs that formed to the same product which is 10 and another two pairs that form to the same product that is 20 that is why 8 plus 8 is 16 right so here we'll have times eight here all right uh this is the entire idea and the code let me hit run code to see if it's going to work wrong answer output is 24 expected is eight two three four six it's this one something is messed up here so let's see uh we initialize a hash map and then we use this first for loop we'll go through this and we use instead of one it should be i plus one so that this way we can always go through instead of one because i keeps incrementing right i could go from one zero one to three but if j always starts from one instead of i plus one which is the right one the one on the right of i that's going to make duplications right so i believe this should do the job let me hit rank one more time yeah all right accept it now let me submit all right accepted uh 68 not too bad um all right this is the entire idea of this problem and solution so hopefully it makes sense to you guys if that is the case please do me a favor and hit that like button that's going to help a lot with the youtube algorithm and i really appreciate it and don't forget to subscribe to my channel and as i have accumulated quite a lot of different youtube videos to talk about legal problems data structures algorithms dfs bfs all sorts of different technical problems to help you better prepare for technical interviews so hopefully i'll just see you guys in just a few short seconds in my other videos thanks very much for watching
|
Tuple with Same Product
|
coordinate-with-maximum-network-quality
|
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**.
|
The constraints are small enough to consider every possible coordinate and calculate its quality.
|
Array,Enumeration
|
Medium
| null |
117 |
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video this time guys we are going to solve question number 117 populating next write pointers in each note part two before i start with the problem statement guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos let's get started with the problem statement now so basically guys we are given a binary tree with the following structure this binary tree is obviously having left node and right node and the value of the node but it is also having a next pointer okay and this next pointer basically points to the next right node on that particular level in the binary tree if there is no right node then the next pointer is null and by default also it is going to be null but if there is a right node we have to assign it using some logic okay so let's see the example here guys try to understand it you can see that on the first level one is not having any right node next to it so obviously the next node is going to be null but for 2 and 3 2 is the left child and 3 is the right child so obviously for 2 the next node is going to be the right child and that is 3 okay so 2 simply next pointers to 3 but for three there on this particular on this same level there is no right most uh right nodes are present now so that's why the next of three is null in the last level you can see that because two is having two children left node and right node so it's very simple that for 4 the next node is going to be 5 but now we have to assign the next node of 5 okay so 5 definitely is going to 0.27 here because that's the only node 0.27 here because that's the only node 0.27 here because that's the only node in that particular level which is right towards five it's go it could have been the left child of three as well but they you can see that because three is not having any left child so 5 is definitely pointing to the right child of 3 which is 7 okay so that becomes our output guys and another example very simple if the root node is null then the output is simply an empty list okay the number of nodes in the tree is in the range from 0 to 6 000 the value ranges from minus 100 to plus 100 and the follow-up is to use a constant space the follow-up is to use a constant space the follow-up is to use a constant space uh we can use recursion and we can assume that the stack space used by recursion is uh is not counted as an extra space okay so now that the problem statement is clear to us guys let's jump to the solution part okay so let's do this condition by condition so the first condition is let's say my root is equal equals to null then what we are going to do then we are going to simply return null right so that is my base condition that because i told you we are going to solve it using recursion so that becomes my base condition that if my root node itself is null then i don't have to worry about going anywhere i can just cut my code here and you know return something okay now the next point is that let's say my root is having both child so if left is also present and reboot dot right is also present then it is very simple that just you have to assign the next node of left to the right node of your root node okay because what is going to happen is that in this case especially you can see that one is having both left and right child so it's very easy that just assign the next node of left child to its right node okay the problem comes when you have to assign the next node of your uh left node when there is no right node so problem is if the right if the root dot right is equal equals to null then what are you going to assign the root dot left dot next to because the right is null now another problem is that uh obviously you are able to uh you know assign something to the root dot left dot next but what about root dot write dot next right because on this level there are two nodes i have to assign the next pointer to the left node and the right node obviously it's easier to assign the next node of the left node but what about the right node what i'm going to assign to that so these are two question marks which we actually have to solve and both of these question marks are going to get solved with a same function so let's name this function called as find next okay and let's uh just pass the root node inside this find next function and now we are going to try to implement this find next function okay let me just assign the finance function to these values okay so to implement the find next function guys it is uh very important to look at this tree let's have a closer look at this and understand that uh in understand an example like this one so you can see here obviously i can assign the next node of 4 to 5 but when i go to assign the next node of 5 it is being assigned to 7. now how do i reach from this 5 to this 7 the path is pretty easier guys we always have the access to our root node okay in this case my root node is 2 right what if i access the next node of my root node so if i check that my row dot next is null or not so if my root dot in fact not if while my root dot next is not equals to null i am going to keep on traversing okay let's say i this is my root obviously two i am at two position where my root dot next is not equals to null it is a value called as three okay so now i go and i simply take a uh take hold of my next node okay so my next node is three and i just wanna take holder of it okay so let's say i make that i'm create a new variable called as root next and that becomes equals to root dot next okay so this root next is my next variable of my root node now to reach 7 from 3 is pretty straightforward all you have to do is access the right node of root mix right so if i simply do like this if i simply do you know return root next dot right so let's remember root next is 3 and root next dot right is 7 i have actually assigned 7 as the next node of 5 here right so that's the logic guys that's the basic logic then what you have to do is you have to traverse until your root dot next is not equals to null why i actually have to traverse that because there is a possibility then in this particular level there are multiple leaf nodes right in this case there are only three leaf nodes but there is a possibility there are multiple leaf nodes here and all the roots of those leaf nodes might not be having any you know any left or right node so we have to keep on traversing all the root next nodes until we find a root node or we find a parent node which is having at least one child okay at least one child to assign our next pointer to so that's why while root dot next then we are simply getting hold of my root dot next variable then i have to actually check that if root dot next dot left is present then you return row dot next root next dot left right but if it's right is variable is available that means if left is not available then we check the right and we simply return the right in the end guys let's see if that parent node if this root dot next node root next node is having no children if it is having ah not left child or not right child then we simply do root becomes equals to root next and we basically go to the next of this root now root next okay because what we have to find if you have to keep on traversing the next of my parent nodes i have to keep reversing all the parent nodes in that particular level until i find a parent node which is having either left or right if we don't find it simply go to the next node in the parent level okay so once you find that node simply assign the left and right to it and your tree will become exactly like uh it should be in other in the output okay so uh that was the problem uh solution guys i hope the solution is clear to you now that i think it is let's start to implement it because that's the easy part now we know what we have to do so let's take it step by step first thing we have to check the base condition right so if root is equal to null what you have to do simply return null here and the job is done now we have to check the next thing if root dot left is not equals to null then what you have to do is simply check if roo dot right is also not equation null it means root dot left dot next becomes equals to root or right but in the else condition what we have to do is calculate what should be the next of root dot left so to calculate that obviously i told you we are going to use a function called as find next so find next and pass the root node in it now that we are done with the left assignment of next pointer for right we just have to check if root dot right is not equals to null if it is not then we have to obviously use find next function to assign the next pointer of root dot right so find next and then pass root once we have assigned the next pointers on this particular level of left and right nodes of the left and right child we simply have to go and do the same for their subsequent children okay so then i will simply call the recursive function connect again this time i'm gonna pass two dot right and row dot left i mean sorry first left and then right oh sorry first you have to update the right nodes first and then you have to update the left nodes guys because uh it is important so why we have to update the right nodes first because it's important that you get their next pointers uh then and there if you get your next pointers then it's easier for the children to simply you know uh point to that okay so uh in the end you just simply return root because uh this is the connect function which actually returns the node which is your parent node or your root node of the tree so indian features returning group now the interesting part simply creating the find next function so private node find next and then we simply pass here root now what were the conditions we have to check the payment nodes until the parent node is either having a left node or right node so we keep on checking until the root is not equal to null so keep on traversing the parent nodes until either the parent nodes becomes null or they are having at least left node or right child left child or right okay so while root uh dot sorry not root not group dot next is not equals to null root becomes equals to root dot next now we simply want to check if root dot left is not equation null first we are obviously checking left because uh left is more closer than the right node then we simply return row dot left and in the else condition uh in the other condition we simply check if right is not equal to null then we simply return root dot right if this while loop just gets over so for example if we have traverse all the parent nodes and we did not find any return statement from here or here then simply we just return null which means that the next pointer of that on that particular level there is no more right most uh right nodes present so just return the next pointer as well okay so let's submit this code guys let's see if this works and hopefully it will work so there you go guys you can see that our submission is accepted now let's talk about the uh space complexity and the time complexities the space complexities obviously order one guys because we have not used any extra space we are using recursion where the stack space is implicit and not counted as a space here time complexity is obviously order of n guys phi order of n because we are going through each and every node only once and then just updating their next pointers okay so that's why the space complexity is order of one time plus the order of n and i hope guys this solution was clear to you and i hope it helped you to better your coding practice uh if it did help you guys and please don't forget to like this video and share this video with your friends if you have any alternative solutions if you want to discuss anything regarding this problem feel free to write down in the comment section i think you want to say to me all the feedback uh you know all your uh things are definitely welcome and uh do subscribe to my channel guys hit the bell icon for future notifications and um thank you so much for watching guys i'll see you guys in the next video until then take care and bye
|
Populating Next Right Pointers in Each Node II
|
populating-next-right-pointers-in-each-node-ii
|
Given a binary tree
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,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above 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, 6000]`.
* `-100 <= Node.val <= 100`
**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
|
116
|
231 |
hey everyone today we'll be solving lead problem number 231 power of two in this problem we will be given an integer n and we have to check whether it is a power of two or not if it's power of two returning true otherwise we will return false they have also given the definition an integer N is a power of two if it can be written in the form of this n = 2 power x if this expression is this n = 2 power x if this expression is this n = 2 power x if this expression is true we're going to return true otherwise rning false I hope the problem statement is clear to you so how we are going to achieve it so the first Brute Force coming to my mind is like checking all the power of two that is what is the power what is a zero power of two that is 1 2^ 1 is 2^ 2 is equal to 4 2^ 3 is 1 2^ 1 is 2^ 2 is equal to 4 2^ 3 is 1 2^ 1 is 2^ 2 is equal to 4 2^ 3 is equal to 8 and so on and let's say if at any moment 2^ X is equal to at any moment 2^ X is equal to at any moment 2^ X is equal to n we have got the answer or let's say 2 s^ X - 1 is less than n so we will move s^ X - 1 is less than n so we will move s^ X - 1 is less than n so we will move one unit ahead now 2 power x is greater than n it means we have not found the answer this is not a power of two so we got the idea that we will be checking all the power of two if 2 power is equal to n and to^ 1 is equal to n and to^ 1 is equal to n and to^ 1 is equal to n and we will keep on incrementing the powers until it becomes equal to n or it is exceeding the S exceeding the N if it is equal to n we are going to return true if it is exceeding the N we going to return false so I hope that is clear to you and what is going to be the time in this case here uh the expression is n = case here uh the expression is n = case here uh the expression is n = to 2^ X and if I take a log of both side to 2^ X and if I take a log of both side to 2^ X and if I take a log of both side log n is equal to log 2^ X x will come log n is equal to log 2^ X x will come log n is equal to log 2^ X x will come to the front so log 2x 2 is 1 so X is equal to log of N and X is what x is the number of operation we have taken so first is 0o power 1 power third to second power third power so X is the number of operation we took so these number of operation are equal to log of n so the time complexity will be order of log of N and no space we are checking so this is the time complexity if we have to check whether it's a power of two or not but we are also given a follow-up not but we are also given a follow-up not but we are also given a follow-up question could you do it without using Loops or recursion it means we did this using Loop and we can also do it using recursion so in the recursion we will keep on reducing n first it is n if n is divisible by 2al to equal 0 we will reduce the to n by2 whether n by2 is power of two if n by2 is also even we will reduce it to n by 4 whether n by 4 is the power of two so it will keep on reducing it until n is becoming equal to 1 that is 2^ 0 and we can return that 1 that is 2^ 0 and we can return that 1 that is 2^ 0 and we can return that there is no more two can be accommodated to This n value and it is a True Value okay so this was The Brute Force checking all the possibilities of two so how we are going to achieve it without using Loop and recursion in this case we are going to be using bit manipulation as uh this n is having a power of two it means its binary form should be something like this 1 0 like this or you can say 1 0 or 1 0 let me make it more clear to you it is to^ X so all the power of 2 if you it is to^ X so all the power of 2 if you it is to^ X so all the power of 2 if I write in the binary form 2 power 0 is nothing 1 2^ 1 is 1 0 2^ 2 is 1 0 2^ 3 nothing 1 2^ 1 is 1 0 2^ 2 is 1 0 2^ 3 nothing 1 2^ 1 is 1 0 2^ 2 is 1 0 2^ 3 is 1 0 and 2^ x is equal to 1 x time is 1 0 and 2^ x is equal to 1 x time is 1 0 and 2^ x is equal to 1 x time 0 okay so um we have got the idea that uh if it is a power of two its binary form should have only one set bit now our problem statement has reduced to the problem that we are given a binary number and we have to check whether it is having only one set bit or not or it is in the form of this or not so for this how do we check now we have to check the number of set bit if number of set bit is equal to one return true otherwise return false so we just have to go the idea like how do we check the number of set bit here what is the least possible value of a 2 power something that is 2 power 0 which is 1 and 2^ 2 is 1 0 2^ 3 is 1LE 0 1 and 2^ 2 is 1 0 2^ 3 is 1LE 0 1 and 2^ 2 is 1 0 2^ 3 is 1LE 0 something like this so if we keep on reducing one power at one step let's say from 2 power x we reduce it to 2^ X - from 2 power x we reduce it to 2^ X - from 2 power x we reduce it to 2^ X - 1 then 2^ x -2 or you can say 2^ 4 we 1 then 2^ x -2 or you can say 2^ 4 we 1 then 2^ x -2 or you can say 2^ 4 we have 2^ 3 then 2^ 2 then 2^ 1 if 2^ 1 is have 2^ 3 then 2^ 2 then 2^ 1 if 2^ 1 is have 2^ 3 then 2^ 2 then 2^ 1 if 2^ 1 is equal to 1 it means this is really a power of two if at uh if we keep on reducing one power from this 2 power x or you can say n and in the end it is becoming 2^ 0 n and in the end it is becoming 2^ 0 n and in the end it is becoming 2^ 0 that is 1 it means this was really a power of two this was the Bas this was the main idea behind this problem so let's say our n is 2 power x and what we are going to do is we'll just keep on reducing this 2^ x to 2^ 0 so first of reducing this 2^ x to 2^ 0 so first of reducing this 2^ x to 2^ 0 so first of all it was 2^ X and we will be right all it was 2^ X and we will be right all it was 2^ X and we will be right shifting it to one when uh till when we will be right sh right shifting it to 1 if it is in the form of like this 1 0 that is n is greater than 0 it means if n is greater than 0 and n and one is equal to zero it means we have zero in the right most like right rightmost digit what I'm going to do is I'm shifting this one to right more significant bit so if n is greater than zero and n and 1 is equal to Z that is on the right side it is zero we can just directly do the right shift by one while n is greater than zero and the right most significant bit is zero we will just do the right shift it means we are making uh we are shifting the bits to the right side until this one bit is coming to the right most rightmost bit so initially it was one 0 I'm shifting it to 1 0 that is right shift by 1 and then shifting it to one more right side right shift by one then again it is greater than zero then again shifting it to one unit on the right I shifted by one if at any moment it is becoming equal to one that is the rightmost bit is not zero so we don't have to check further if it is equal to 1 it means that answer is true if it was something like this 1 0 then 1 if at any M this moment it is getting 1 one that is three instead of one if it is not equal to 1 we are going to return like false so how do I write the code in this case uh first of all let's say U this is function and we are given n as a input and we have to return Boolean what I'm going to do is while n is greater than Z and n and 1 is equal to Z that is we have zero in the rightmost bit if it is a zero in the right rightmost bit if it is greater than zero we will do the right shift by one so this is a step one and what is the step two that we have reduced all the right zero which are on the right side that is now the binary is in the form of one and these zeros have we have reduced so it can be one here or it can be zero here we don't know so now at this moment if it is equal to 1 we are damn sure that there was only one set bit so what we are going to do is are going to return n equal to 1 if it is one after reducing all the zeros it mean then it means that it is in the form of like this 2^ in the form of like this 2^ in the form of like this 2^ x otherwise it's not a 2^ x 2^ X plus x otherwise it's not a 2^ x 2^ X plus x otherwise it's not a 2^ x 2^ X plus something like this so these are the two step for our problem I'm checking I'm making this check to not going it to tle let's say uh if the problem statement given is something like this n equal to Z and if we keep on doing this forever so we have to check first whether n is greater than Z and n and 1 is equal to 0 in this case we'll just make the right shift otherwise if we are not able to make the right shift we will check whether the N is reduced to one or some other number if it is reduced to one it means it's a power of two otherwise not a power of two okay I hope you this problem statement is clear to and what's the time and space complexity here the time complexity is order of 32 because we have 32 bits and at most we can make 32bit operations so we will consider it a constant time solution so it's way better than l L of n so we are solving it in a constant time okay I hope you understood the problem let me let's start writing the code for this problem here we have to check whether n is something like this one Tri 1 0 in the binary form or if it some or if it is something like this 1 0 so if it is in the first form it is definitely a power of two in the second form it's not a power of two now first of all we have to remove all of these zeros if it is a zero remove it making a make a right shift so for that first of all we have to check whether n is greater than zero if it is not greater than zero so it is of no sense making a zero and right shift so n greater than Z and n and 1 equal to Z what is this condition it means if I'm making an add operation of this and the one that is on this rightmost bit I will get to know whether it's a zero or 1 so if it is a zero just do the right shift n greater than equal to 1 so now we have reduced these values to something like this here I just have to check whether my remaining n is equal to one or not so for that I can directly return whether n equal to 1 if it is 1 it's a power of two if it is in this form it's not a power of two let me run over sample test cases on the sample test cases it is working fine submitting the problem it Go submitted successfully hope you understood the problem and we have also uh another method that if I take a n and n - method that if I take a n and n - method that if I take a n and n - 1 what this operation is going to do remove rightmost set bit so this operation is removing the rightmost set BD if after removing the rightmost set BD my number is becoming equal to zero it means it was a power of two so if we remove the rightmost set bit from this number from this 1 0 it will become 4 * 0 or you can say will become 4 * 0 or you can say will become 4 * 0 or you can say directly zero so let me write that solution as well for you if n is greater than 0 n should be greater than zero and n and nus1 equal to Z it means if it is true n and taking and with n minus 1 is equal to Z it means there was only one rightmost set bit that we have removed and after that it is become equal to zero it means it was a power of two so we can directly return this expression return n greater than zero and taking this n value yeah if taking a and with n minus one is equal to Z that is there was only one right set bit that we have removed after removing the rightmost set bit if we are taking zero as answer it means it's a power of two so let me run this problem okay first of all I have to comment let me Mark it old i r running this function passing all the test cases if I submitted the problem it is also submitted sucessfully okay thank you guys
|
Power of Two
|
power-of-two
|
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_.
An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`.
**Example 1:**
**Input:** n = 1
**Output:** true
**Explanation:** 20 = 1
**Example 2:**
**Input:** n = 16
**Output:** true
**Explanation:** 24 = 16
**Example 3:**
**Input:** n = 3
**Output:** false
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion?
| null |
Math,Bit Manipulation,Recursion
|
Easy
|
191,326,342
|
1,655 |
hey everybody this is larry this is me going over q4 of the recent lead code uh by weekly contest 39. uh wow i'm just taking a notice that um it's a six pointer but that was kind of hard and a lot of people kind of took the time of it like the top people so i think they kind of under i mean the way the points don't really matter uh as i try to finish all of them anyway but i would say this is a harder than normal sex so uh don't feel bad about it um but yeah so let's look at the code first so yeah so this problem is called distribute repeating integers um so this is a really tricky problem and i think this is a problem where you know you try to do the best you can with identifying states and the first thing i would do is that um you know just make look make sure you look at the constraints so my when i first look at this and some of this is from experience during the contest is that when i read this problem i was like this is too hard to be greedy um and when i say hard i mean in the computational sense i and this is something that when you do enough competitive programming problems you'll recognize these patterns where you know that if it's greedy um it has to be something weird about it that gives it greedy true otherwise it's like some sort of variation of mp right um like you have to do exhaustive search or exponential time stuff so i took a look at the constraints uh the first thing i do after that and the two key things to notice one is that they're at most 50 unique values and nums and the other is that m is equal to 10 which is the quantity that you have to fill so immediately that gives me a hint that it has to be dynamic programming the fact that m is equal to 10 gives me hint that i can kind of you know think about how to handle it um and for me with these kind of problems um what i would try to do is try to impose a structure to the problems in a way such that you or you when you go left to right on a suffix or something like that um you don't have to go back and you know there's no need to go back or going back does not give you a better answer because you've already answered it um and for me the amazing 0-10 was the and for me the amazing 0-10 was the and for me the amazing 0-10 was the biggest crew and i'm going to explain my states but i'm just right now explaining my thought process hopefully that's more interesting if not you know fast forward i'll explain the solution no worries um watch it on 2x but yeah so the idea here is that well because there are only 50 unique nums this numbs away even though it has 10 to the fifth element this nums array is essentially um you know an array of 50 elements just like a collections of calendar right which is what i do here basically you could just compress it into an array of 50 elements and that'll be good enough uh and now you have to and now basically what you have is 50 elements that you cannot um or actually that you can't divide and then you have to have some you know summation things there uh from quantity right i know i'm hand waving a bit but that's how i do it at the time and the next thing i thought was okay can it be some kind of knapsack right like you know um but then just working it out um but i was like okay that's gonna be two um uh given that each number in this collections that counter can be up to ten to the fifth or like something smaller say but um you know knapsack was gonna um like the range of numbers is too big um maybe you could do it i couldn't really figure out how to make the numbers work for sure um so i didn't do it that way i might have a pursue it if i had no other choice but i was thinking about another way um and then the thing that i took notice again is that m is less than 10 so we can really brute force on 10 right and the idea now then is that we have a bit mask of okay you have 10 elements so because 10 is small enough you could do some two to the 10 things like 10 to 24. oh sorry 10 2 to the 10 which is 1024 and you know you could do some bit mask thing there and from that i joined about the idea and you know okay that means that we have 10 items and we either satisfy some subset of the 10 items and we want to satisfy all sub or 10 items so and there's only ten again two to ten possible possibilities so that's going to be an index and on the left side we have this counter thing so we just have to kind of implement it in a way so that the transition going from left to right once we used um a number a column i call it a bucket or something because this is just i go i count these as buckets of numbers but once we use the bucket we could throw it away right so they basically that's how i grew this up um i actually also wrote uh a cache that uh just sums up the things which i'll explain in a second so that's basically my states index is uh and this and if you kind of follow through there are a couple of steps to each of these so that's what makes this hard is that it's not straightforward it's that there are a lot of like little problems that you have to sell to get to this state and so index is actually like for example we to document this code um cv is just um the number of i'm gonna just say boss us in a bucket uh and this is just the implementation of it right um i'm going to explain the cash flow later so indexes um what current number bucket we're on we don't need we over or we already considered all buckets to the left of index and mask is just a bit mask of all the quantities that we already filled right um and in this case i go i count from one to zero to make certain math a little bit easier so for example if this bit mask is this that means that all num or quantities need to be filled so i would say right now a prerequisite for understanding this part does require big mask i have a video that i'll put in a link below so that you could kind of learn more about bit masks in general and how to use them to solve this problem but i'm not going to explain it here because i want to keep this video short but you know i'll give you the tools but assuming that you already know how a bit mask work so yeah um but just to kind of give a 20 second overview so if you have something like this then um that means that first quantity needs to be filled or is first second fourth and six because we have once in the first position second position fourth position and the sixth position right and you know you could do some math about um lower significant bit versus more significant bit but that's a general idea um and then now we could go through our states right if mask is zero that means that if all our quantities are filled we could return true because that means that there is a path to get there um we can you know that means that we can actually uh return true if the index is equal to m that means we already used all the buckets and that means that it's no good um no good because we only use all the buckets and mask is not true not zero that means that you know there's still mass to be filled but amazing or index is true um and m of course is just the number of buckets we have and then this part is just going for all the possibilities and this is um a little bit advanced technique though there's um though i think and i'm just uh thinking about how what would alex do as a python person because this is a little bit more c uh you could actually use uh edit tools and combinations to kind of do the subset of your bit mask um so basically that's what this does is that this gets me the subset of the bit mask so that we don't have to um count it this is a little bit magic i'm not going to explain it again um i'll put a link below on the explanations but basically this just lets me get all the subset of the bit mask so that for example we have this bit mask here then this goes through one zero it does zero one zero and basically um basically all the subsets of uh this thing and the key thing to note is that because we don't iterate all for either of the zeros in these uh in the original bitmask this allow us to be faster and the key thing to note for that is that as a result and the math is a little bit tricky i'm a little bit hand waving um i'm not going to prove this but it drops our complexity from four to the n to over three to the n and i'm gonna go over it in a little bit but that's why i kind of write this in a funky way because i was trying to be a little bit make sure that i'm a little bit faster um anyway yeah and then the recurrence is okay we have so given that we have um you know let's say we want to fill the first second fourth and the six right well what are the criteria to fill this well the criteria to fill this then is that if the quantity of these four the sum of these four buckets is less than um the number of balls in the bucket then we can you know mark them as being off right so that's basically it um but i knew that if i do a for loop to do the summing it's going to take a little bit long so i actually preemptively for all combinations do the sum here so that's basically what this does i'm not going to go into too much but you can kind of see that and this requires some understanding of bin masks as well but you can basically see that for each bit mask combination for example for this one we just do a for loop so that it looks at all these numbers it sums it up to this total amount for a given bit mask given the quantity number so that's basically what i have here and basically here i just retrieve it instead of doing another for loop so that it makes it faster and yeah oops and that's not and if this condition is true meaning that if the number of balls that we have in this bucket is fewer than the bitmaps that we're satisfying then we could check to recursively um the rest of the constraints which is that you know we use this bucket so it's index plus one and then we use this bit mask xor to check off the things that we're using now so now for example in this case let's say we use the one the first second and the fourth and the sixth bucket then in this case mask xor sub i will give you uh zero one so that means that now your recursion will be okay now the third and the fifth needs to be filled so that's basically the recurrence and it's pretty straightforward once you have all the foundations um and again there's a lot of foundations that you need to understand before this can be solved this way so if you're having trouble understanding my explanation i would advocate practicing bit mask problems that's one and also practicing bit mask dynamic programming problems that's two and then this will become a little bit uh easier because then you're able to do these optimizations and if you look at it like if you look at it that way if you look at how i described the prom i actually solved like four different problems almost right kind of thing and that's why this is hard right like first i have to put the balls in the bucket so that it's faster um and then now i do this caching so that the caching is faster right and then i have to do this bitmap dp on these things um and also you know constructing this problem in a way so that you can understand and putting it all together is not easy you have to be really strong at each step of the way so that when you're solving this when you notice these things you're able to go for it directly um yeah uh so the explanation for the so that's all i have for this explanation i'm gonna go over the time complexity here uh so this for loop is query um n times two to the n so this is going to be all of n times two to the n in this case it's a little bit tricky to explain this and it's actually easier if i do this bottoms up dynamic programming but basically you have over m state uh for so index can be obviously uh zero to m so that's all m number of states mass can go from zero to two to the n so this is of 2 to the n states so a naive interpretation of this is that and this is for each state uh okay so total number of states is equal to o of m times 2 to the n and for each state each day does this amount of work and what is this let's just say it's 2 to the n for now so naive um naive uh pro uh analysis of this is gonna be m times two to the n times t times two to the n um and that is actually not fat uh i actually don't know if this is fast enough but i actually think it's a little bit too slow but it turns out because of the way that i did this bit mask thing uh where it only counts the bit mask if you do the math and there are videos on uh that will explain this duration but it actually turns out to be m times 2 to the oh sorry 3 to the n which for m is equal to 50 times 3 to the 10 times 50 it's actually only uh so for m is equal to 50 and n is equal to 10 this is roughly equal to uh three million so this is fast enough for that reason um and this is only with these optimizations that this is fast enough uh in my opinion right so that makes it really tough because uh any well maybe in c plus another language maybe it's fast enough but in python this is the case uh for me uh intuitively because without this it's a little bit yucky uh and for example this loop if we have to do another for loop well this is going to times this loop by another uh by another end and another end with another 10 right so that's going to be 10 it's going to be 30 million which is usually too slow in python so that's why i had to do this look up table um but yeah and in terms of space well we have these this amount of state so that's going to be your worst case number of states or it's actually i guess n times 2 to the n plus m times 2 to the m so your space is just you go to this times two to the n uh whoo it's a long explanation because this is a long problem i hope that was understandable let me know what you think let me know if you still have any questions and you could watch me solve it live during the contest next uh i tripped on that huh really dumb washed it so good quantity is 10. bye i don't know how to solve this but i'm not sure a lot of people got it that's great okay no we'll see i think this is okay hmm oh uh you okay oh how oh but also come on okay oh so stupid on hey uh thanks for watching uh hit the like button hit the subscribe button join me on discord let me know if you have any more questions about this problem or another problem uh i will see y'all next problem bye
|
Distribute Repeating Integers
|
move-sub-tree-of-n-ary-tree
|
You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* The `ith` customer gets **exactly** `quantity[i]` integers,
* The integers the `ith` customer gets are **all equal**, and
* Every customer is satisfied.
Return `true` _if it is possible to distribute_ `nums` _according to the above conditions_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], quantity = \[2\]
**Output:** false
**Explanation:** The 0th customer cannot be given two different integers.
**Example 2:**
**Input:** nums = \[1,2,3,3\], quantity = \[2\]
**Output:** true
**Explanation:** The 0th customer is given \[3,3\]. The integers \[1,2\] are not used.
**Example 3:**
**Input:** nums = \[1,1,2,2\], quantity = \[2,2\]
**Output:** true
**Explanation:** The 0th customer is given \[1,1\], and the 1st customer is given \[2,2\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= 1000`
* `m == quantity.length`
* `1 <= m <= 10`
* `1 <= quantity[i] <= 105`
* There are at most `50` unique values in `nums`.
|
Disconnect node p from its parent and append it to the children list of node q. If q was in the sub-tree of node p (case 1), get the parent node of p and replace p in its children list with q. If p was the root of the tree, make q the root of the tree.
|
Tree,Depth-First Search
|
Hard
|
1650
|
113 |
we're going to look at a legal problem called path some number two so i made a video called paths on the number one so this problem is kind of similar to that and but this question kind of uh involves backtracking um not just dfs but also backtracking as well so if you have a look at that video i highly recommend to check out that video before this one so basically the problem is that we're given the roots of the binary tree and an integer target sum return all route to leave paths where each pass sum equals target sum right so a leaf is a node with no children so notice that we're going from the root to the leaf right so the roots the leaf path so if let's say if the binding tree is null right so if i have a tree that's null right and you can see the constraints that number of nodes in our tree can be range from zero to five thousand so that means that i could have a binary tree and the root is null so if that's the case then in this case we're just going to have no path at all right even though the target is on zero and the current binary tree is null then there's no path at all because we need to have a route to go down to the leaf right even though there's only one node then still right we want to have at least one node to traverse down if there's no node right if there's if the binary tree is null then in this case we don't have any path at all right okay so in this case you can see here we have an example right we have five four eleven two with five a four five which all has a sum which is your target sum 22 right and you can see that we're basically returned a list of those integers uh that captures the path right so in this case um you can see we can also have a empty list right so if there's no path right that has a sum equal to target sum then we're just returning a empty list um so in this case this is questions very similar to the path sum question um basically which we will involve backtracking um to solve this problem pretty much we have to use backtracking because in this case we're going to use a empty list right in this case when we are starting at the root the list is basically empty so if i want to traverse down this node then i have to add the current node or the current node's value added on to the list right so okay well then i have five four here right so and then i when i go to here is five four eleven and then what i go to here basically is five four eleven 7 right and then i know this is a leaf node so i basically see if the current sum right we also have a variable that keep track of the current sum uh for the current node right then we traverse so we keep track of the current sum and the current sum now is basically 9 plus 11 which is 20 plus 7 which is 27 does not equal the target sum so that means that we have to backtrack right because in this case the current sum right or sorry the current sum when we get to here is 27 and the target sum is 20 sorry 22 right so in this case we have to backtrack and to backtrack we have to remove the last element that we added onto the current list right now only uh you know in this case we have to backtrack we have to go down to a different path we also have to remove the last element right and once we remove the last element this is our list right 5 4 11 right and then we go down to this path so in this case we have 5 4 11 and 2 right so in this case we have a sum of 22. we know that the current sum which is 22 uh is equal to target sum right so then we're just going to add the current list onto the result list so we also have a result list variable that keep track of all the path right that has a sum is equal to target sum so we add this list onto the result list and then in this case we backtrack to the root right which is here and then we successfully traverse the right side so we go here this node has no right node right has no right subtree so we backtrack to the root which is no five this node has a right sub tree so we traverse down right we add five eight right and then the current sum is thirteen so we keep going down until we reach through a leaf node we know this is 13 so we have 5 8 13 right and we know that this is a leaf node and this does not have a sum that's equal to this right so we backtrack to here right in this case now we keep going down to the right side so we have five eight four okay so now we have uh we also have this is not a leaf node so we continue so then we reach to this node right here um in this case we have five eight four five right we know this is also a valid path so in this case we are going to add a current list onto the result list as well right and then we backtrack again to this level right so to this list we remove the last element that we inserted onto the list right so then we go down to the right side uh because we haven't go down to the right subtree yet right so in this case we have five eight four one and in this case this does not have a so the current sum does not equal to the target sum and this is a leaf node so in this case we don't add it on to the result list right so we can see that this is basically how we solve the problem using backtracking um and then you can see in the code it's kind of very similar to how we did in the path some number one question and what we basically do in here is that if you know if the tree is null right the trees and all basically would just return an empty list otherwise we just do a dfs we pass in a empty list right and then you can see that for each and every single uh recursion stack we're basically um updates the target sum right so if i want to go down if i want to do a dfs to go down then i have to update the target sum and then i also have to add the current node its value right onto the path so in this case we check to see if this is a leaf node if it's a leaf node we basically add the current path onto the result list notice that we're basically creating another instance of this list right and we also have make sure that target sum is equal to zero um and then you can also what you can also do is you can basically do another variation of this like if target sum is equal to zero inside this if condition right if the target sum is zero then do this and then at the end we just return right but in this case it doesn't really matter right if the if this is a leaf node and target sum does not equal to zero like if you go to the else statement we still won't be able to go down right so you can see the root.left does right so you can see the root.left does right so you can see the root.left does not know then we just go down right and then same thing for the right side um and then at the end you can see we're doing backtracking right we basically remove the last element that we have in our path right it doesn't matter if we go in this path or this path we still have to remove the last element out of the list right so that we can be able to go to another path right so you can see this is how we solve the problem time complexity in this case is going to be big o of n where n is number of nodes that we have in our tree and the space complexity in this case um is basically just going to be the height of the tree right because in this case we're going from the root to the leaf node and this path right here only stores those number of nodes right basically big o of h number of nodes right we're basically the height of the tree um and then we're always doing backtracking to remove the last element right and then uh down to another path right so this the maximum space that we can have right in this list is basically the goal of h right and then of course uh this list will capture um basically uh you know number of lists right but the thing is basically the space in this case is big of h right so there you have it and thank you for watching
|
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
|
1,346 |
Ko Absolutely Do A New Video This Video Or Going To Discuss Any Rate Problems From Digit Code And Problem Is Part Number 134 6 And 222 Problem Statement Problem Share And Subscribe Must Subscribe 2001 Any Particular That If Example If this is the current example, is there any double of your tank, otherwise is there no double of this, 5055 is there double of this, then for 10:00, is there any 5055 is there double of this, then for 10:00, is there any 5055 is there double of this, then for 10:00, is there any double of this tank, will circle to the front and subscribe to the 5555 element, then inside this if Subscribe if you subscribe 9216 I click here if there is any reaction place here I click Shubhendu 110 into that is 0 only then in this you make this decision here to us that this is our second so here if 920 820 and 620 here ours is not doing any here ours now in school and our second one by subscribing how do we subscribe this question first see the channel go for reach so if we see all on the route for this question So our brute force approach to this question is quite simple, what we will do is we will run our loop and from where will you guys drive i20 till where Plus and here see us here we compare this subscribe here and this is ours subscribe here But we subscribe, if you were to-do, meaning if you are equal to zero, to-do, meaning if you are equal to zero, to-do, meaning if you are equal to zero, then we should not get our answer there. Where is our answer? When Bigg Boss is not equal to toe, then what will we do now with our body and face? If subscribe You can subscribe that subscribe the youth in this case, like the accused on both sides, if anyone returns us, I will give the chords, if we run this for our initial example, what is the example 10225, then the loudest and here and what is the example 10225, then the loudest and here But subscribe here that war subscribe into two so then what will happen for our whole life will be cost then came that they will increase and our this our today this ours will go so here we came home And this is ours and our channel subscribe and subscribe here we subscribe modern is doing its specific when Bigg Boss gets tight latest soak for pimples quotes on ourselves first of all we take our potatoes from here to here Subscribe to our channel, let's make it here, now subscribe to our ghagra dot, within this we will reach us on Plus, here we will check here, subscribe to the difficult toe, along with this, what should be the check mark, the area of which I came. what should be the check mark, the area of which I came. what should be the check mark, the area of which I came. Is that by its corner, if we multiply this by the other, then you should see that if both of these are unsatisfied, then what do we do here, do our return to return form and if this if either of the two conditions is not satisfied and After both of these are finished, we do not return them. We will do so. We will return here. Subscribe. Thank you that we have submitted this Bloody Mary. We submit our sample with cloth for discussion and also see the results for market space. Yes yes and this will be our successful submit 5 tons more online C plus mission is that 1061 percent at this time Malik has used this is our speech if you want to join us then we can cut it and edit this subscribe here our daughter-in-law daughter-in-law daughter-in-law We paste ours and we present it before the court If we submit it for Java and see the result, what comes is the result and this is our success in Java also, submit in the morning OK which is Councilor and its first online job submission is that laddu is used by innocent people as family if we see here what we have to do here we have to use new activa sapoch 4 marks sapoch if you share the example 10225 people do we do We do it, we do it first of all, if our friend does not subscribe to our channel for us, but there is no enmity between the two, we will put it here, we will put tan, it is okay and along with us, we will put someone, it is okay, put one. Given so that basically we will put ours on time, if we get it, what will we do with it, here we will see the appointers, we will do it in 2002, here Tutu once again let us subscribe in it example2 here now Let's do school thing, we get this opportunity, we get half of the intake, 3.5 but if this is middle, then we were we get half of the intake, 3.5 but if this is middle, then we were appointed here subscribe that Ravana in the war, subscribe for August, so that if our first then what will we do, if we are subscribing to this, then this We will store a vacancy for, now see what happens from for intake, if we talk, here we subscribe here, subscribe, then our this or we can do this, if our number, then we do Here we have subscribed for the subscribed village, what will we see today? We will always see double division. If you consume it, if you do not subscribe till 500 and 1000 villages, then you will not pay for the subscription. Mid-2014 Why did you not subscribe? Insider on April. Subscribe to Ganth 299 56001 This is the point of this point and ours, what will we do if we don't get it, then this is our channel, subscribe first of all, type and with and stack where from where till chali thi this is done and the I Plus Okay, ours will be basically clear, what do we have to do here, we should check if ours is here, first of all, we should not go into this is ours here, what is available in this, use the account function, village then This is our into consideration for here, so we did it, now what we have to fold here, so what will we do here from device person 2.0, so this is exactly our from device person 2.0, so this is exactly our from device person 2.0, so this is exactly our result in double or we can divide it and type it. If you can do any of the two things, then I will work, I will type it here, what do we have to do here we will divide yours, okay and if both of them subscribe, otherwise we will end it, then our Which is our glue, from where to where, if you subscribe to our channel, you can use it here, what will be the quantity, soak off and here we have to type video, hotspot, on, mix it is, which ones have come where, so let's go. And first of all, let's fold it today on our editor, what will we do, first of all, we appoint here subscribe, so we use for you, subscribe, first of all, rest of the world and subscribe with him and this attack is disgusting. And this is our map is ready, what should we do in it, we should start requesting our phone, from where to where it will last, this point will last till 06 sex, whatever is our length plus inside this, we will add if our which is ours. Here, instead of our account, we use the content function, if our here, we have the elements of the element, our ghagra, this can be melted again, if our can be on the other side of the tense, if can be on the other side of the tense, if can be on the other side of the tense, if its we have you are not a. Here let us type in type now is Hey from I we will divide when it is okay if this which is our this result then we will return so one what we will do is this close loop our potato. After the end, when we will call the returners because any of our elements must be subscribed for subscribed 25. First of all, if we are not appointed, then every time we are here, there is no harm in doing something here. This sentence of ours does not allow you to put such a limit, what will we put wap dot food and here we will do the previous report Hey off I will support and what will we post with it, we will do it one foot, now keep watching, now we should be accepted C Is I still what incompatible types of ours cannot be in these double then we will have to typecast this rumor also in double-double I also in double-double I also in double-double I can type this too let's e no oo ok what result comes now A B P our for result aa There may be a mistake in this here, our map is made from Ghrin Hour Life but let's test it and see it and subscribe to it that Ajay, it was our mistake yesterday, there was a problem in our apk file to start, this too we are double We will have to pass time, now we submit it and see the result. Basically, what is Quora? And this is our successful acceptance with 76 cents of online submission and for the cent of violence on dieting, subscribe, do it here. We will make our double and here we have made its double, those who do this will have to make 409 plus, so first of all we will make ours in 10th, now what we have to do is the total dot size of our school Noida size, okay, now we are inside it. What we have to do is one if our tense here we use this function tense here we use this function if our ray I start to contains first or second if our does first or second if our does first or second if our does that used to last to subscribe then we use this Type in double subscribe and if this is our then we have to make an entry for this. After the follow is over, if we did not get the answer, will we return and Sagar, we run this and see what is our result. Let's see. And the wrong answer is coming, let's see, here we have made a mistake, what have we done here, I put that balloon of mine, then what will we do here, whatever map of ours is off, we will burn it. Will give a big one If we run this then now we should have successfully run Front C was a mistake and this is our successful accepted If we submit and see here is the result of let's C Here is our wrong answer 317 appointment 7.2 If you look carefully at the appointment 7.2 If you look carefully at the appointment 7.2 If you look carefully at the mistake we made that we subscribed, we should type this once again and double our results and subscribe and for this, try and copy paste it in the test case and read it again and again. Okay, so this is what we were doing, our distic was that if we put this parent inside it, because of this the problem is gear, so if we remove this thing outside the parent, now our typing is possible, before this we type and Let's see and now we are accepted, let's submit it and while watching our final, the test should be completed for this and see this fast Ronit nonstop Kodak subscribe time subscribe thanks for watching this Video if you practice and our channel Subscribe to Na
|
Check If N and Its Double Exist
|
maximize-the-topmost-element-after-k-moves
|
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that :
* `i != j`
* `0 <= i, j < arr.length`
* `arr[i] == 2 * arr[j]`
**Example 1:**
**Input:** arr = \[10,2,5,3\]
**Output:** true
**Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\]
**Example 2:**
**Input:** arr = \[3,1,7,11\]
**Output:** false
**Explanation:** There is no i and j that satisfy the conditions.
**Constraints:**
* `2 <= arr.length <= 500`
* `-103 <= arr[i] <= 103`
|
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
|
Array,Greedy
|
Medium
|
134
|
316 |
hey guys peng here so today we're going to talk about remove duplicate letters so given a string s remove duplicate letters so that every letter appears once only once the result is the smallest in lexicographical order among all possible results so if you see this example bc abc you know the result is abc's the smallest in lexical graphical order and b is duplicate c is duplicate so you get four choices you can choose so it's either b c a b e b c a or c a b or a b c or you know c b a c you know four choices among these choices we're gonna find the smallest less graphical order so what's our algorithm so we can try to see you know try to create a red array to keep track of the last index of the given string given character appears so in this case you know because this duplicates right so we will have a way to keep track of the last index of the character that appears so for example this one is like one zero one two three four f4 c appears the last index and then we create a boolean array scene you know each time we you know access a character want to see if we have singing or not before so for example that is in this case b we haven't seen yet but in this case we see b again means we sing it and we want to kill a stack to keep track of the elements we want to keep and we look to each character you know if we sing occur if the character is seen you know we continue if it's not seen then we check until the stack is empty and then see if the character at a stack is greater than the current character you know and also will create a stack to store the animus want to keep so let's look at the example right here let's look at the algorithm so here's the array we look to the each character to keep track of the last index of each character in this stream and seeing the bullying scene you know keep track of the current character it was incarcerated or not create a stack you know to for the character want to keep loop to each character in the string you know he's the first here's the current character if seeing before will continue and then if it's nothing we check until the stack is empty and if we check if the element that stack is greater than c it means we don't want it you know because we want to keep the smallest that's called graphical water so if it's bigger than the current character we want to throw it out we want to pop it and if it's not the only character in the string then we pop it you know we pop it here and we set sing with false because we pop the element we pop the character so now later on we add the character to stack and then we set the we set it to true to sing at the end we have a string builder we want to add all the characters in and then we reverse it you know we change it to string that's the result so it should be it you know and then the runtime is open and the space is for one time is open this time because we won't do this then space is one space is all oh and two because it depends how long is how long just does that thank you guys take care
|
Remove Duplicate Letters
|
remove-duplicate-letters
|
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
|
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
|
String,Stack,Greedy,Monotonic Stack
|
Medium
|
2157
|
62 |
hello and welcome today we're doing a question from leaked co2 called unique paths it is a medium let's get started a robot located at the top-left corner a robot located at the top-left corner a robot located at the top-left corner of a M by n grid mark to start in the diagram below the robot can only move either down or right at any point in time the robot is trying to reach the bottom right corner of the graded mark to finish in the diagram below how many possible unique pads are there and here we have a 7 by 3 grid so actually 7 is going across and 3 is going down M is the number of columns and is the number of rows so in our first example we have a 3 by 2 grid we would output 3 because going from the top left to the bottom right there are only three total ways to go there if we go right and down or right down then right or down right then right I'm given a 7 by 3 grid we would output 28 and this is the grid that we had up here so for these questions we should always start with our very base case and see if we can work our way up from there so if we just have a 1 by 1 grid what would be output so that's obviously just one right if we had a 1 by 2 or a 2 by 1 grid so if we just had these 2 blocks right here and we wanted to get to this block we would still output 1 there's only one way to get to here similarly down here there's only 1 way just going down now if we had a 2 by 2 we wanted to get here what would our answered me well if we're over here we know that we can only ever travel down or right so if I want to get to here I can only come from the block over left or the one up and I know from here we only had one possible way to get to here and one possible way to get to here so anytime I want to get to here I know that I only come from here so I can only come from two total places and I can actually extend this over to our three by two example so if I'm over here I can only come from here or here now I know I just calculated a second ago that there are two pads over here so I know I will have at least two just from the left now how many can I get over here well since this is directly right from our starting point and can only ever have one straight shot down so there's still a total of one right here so this is why I can get to from here one from here and that makes a total of three so if you can see the pattern here we can only ever come from the top or the left that means if for any block I know how many pads there are to the block above it and how many pads there are to the block to the left of it then I can always find how many paths there are at the block because I simply need to add the one above and the one to the left and that's going to be my answer so this is a classic dynamic programming problem if we just keep continuing this toward whatever our M R and that last block we'll have our final answer so let's go ahead and code this up first we want to make a base check if M equals 1 or and N equals 1 so if M and equal 1 and we want to return 1 if that is not the case then we want to make our ADP array so CP equals we're going to start with a list of 1 times give me times m and then that is going to be the number of columns and then I want to multiply all the columns out of number of rows so times n this is our DP array and all the blocks in there are initialized to 1 I want to take a loop so for row in range 1 length of TP or call in range one lindo bro why am i arranging starting from one well let's take a look here right if I want to get to this block from this starting point I can only ever go down or right so here to get to here there is no possible way I can ever go down so I can only keep going right and every single block in this row has a path of one there's no other way to get to these blocks similarly going down that first column all of these are also one so the first column and the first row they're all marked by the value one and since I initialize my GPA to all be one I can just start from here and that way I don't really have to worry about going out of bounds either I can start from here see what my path is from above to the left and sort here but as I move on I can use these new values that I've calculated to continue calculating further so now that I'm starting from one and going forward I'm gonna store DPO Pro column equals DP of row minus one column plus DP of row column minus one so this is going from the left and the top to calculate that new value for row column and once I have filled my entire array out I just need to return this last value here so I'm gonna be returning DP minus one and this is just accessing the last element in any list let's run this code there is in error oh this should be a TP oh group went into code accepted submit and it is accepted so if you have any questions let me know down below otherwise else
|
Unique Paths
|
unique-paths
|
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100`
| null |
Math,Dynamic Programming,Combinatorics
|
Medium
|
63,64,174,2192
|
394 |
hello everyone so today we will be solving lead code problem 394 that is decode string so we are given an encoded string and we have to return its decoded string so there are certain rules mentioned here let's move over to our drawing explanation and write the code and then do a dry run and understand this problem statement more we are given an encoded string and we have to write its decoded string so this decoded string will look something like uh like whatever we have in the square brackets multiplied by the number that is before that so this one would look something like three A's and as the whole of BC is there which is uh going to be repeated twice so our BC would be repeated twice now we have another example that is something like 3A 2 so now here we can see our C would be repeated twice our a to c would be repeated Thrice so the string would look something like let's first uh the thing that is in our square brackets like let's first write this part so it would look something like a and we have got 2C now this thing is going to be repeated Thrice so this is once twice so the string would look something like this now let's uh write up the code for this and then do a dry run to see how we achieve this so for this we would be using a stack we would be maintaining a current string and we would be maintaining a current number so our current number will represent our number our string would represent our uh the whole string that we will be repeating like our output that would be our current string so let's uh let's write it up so we would initialize a stack we would initialize a current string and we would have a current number which we will initialize to zero so now we will for every character in s first we will check if it is a digit then we will update our current number which should be current number into 10 Plus indc now we are doing this we are doing multiplied by 10 just because uh suppose instead of 3 we are having 13 so to get like both of those numbers we will do multiplied by 10 into integer of the character because our 3 is in the string so it is in the character format so we will convert it into int or else if our character Is An Open Bracket so if it is an Open Bracket we would append our string and our number to our stack so first we will append our current number then we will append our current string then we will initialize our current number back to zero so that we can keep track of the other numbers forward and we will initialize our current string back to empty string else if our character would be a closing bracket our we will have a previous string we would have a previous string which would be stack dot pop like whatever string we would have appended we would pop it like whatever string we would have made that far we would pop that out we would understand it more than we drew do our dry run and in the previous num we would have stack Dot pop like first as we have appended number we will be popping our number second uh so our current string we would update it to our previous string like whatever is in the stack till that and our current string multiplied by our number else like else of course it would be a character so in our current string we would just update our character now if you see in example 3 we have got just E and F to the very end so what we will do is we will just check if there are some elements present in the stack in the end so we would be in our current string we would be popping it out from our stack and we would be appending it to our current string and in the end we will be returning our current string viewed first initialize a stack and we would have our current string as an empty string our current num as 0. later in our code we also have got previous string and we have got previous num so let's begin so first we will encounter three which is a number so we would come to our current number and update it to 3 then we encounter an Open Bracket so we would come here and we would append our current number that is 3 and we would append our current uh string that is an MD string and then we would be updating our current number and our current string to an empty string so as we already have an empty string I'm not doing anything so let's move on so we have got a now we would come to the else part as we have encoded and encountered an A and we would update our current string to a now we encounter a closed bracket as we have encountered a closed bracket we would update our previous string and previous number so our previous string would be an MD string and we would be popping that out from the stack and then we would pop out three so we have popped this out now we would update our current string so our current string would look something like previous string which is an empty string plus our current string that is we have got our current string into previous number so Three A's so now our current string would be Three A's so let's update that so our current string has become something like this now we will move on in our iteration and we will get a 2. so we will be getting a 2. so we will update our current number to 2. then we would move and we would encounter a Open Bracket so as we would encounter Open Bracket we would append our current number which is 2 and then we would append our current string which is a and then what we will do we will re-initialize our current string to an re-initialize our current string to an re-initialize our current string to an empty string and we would have our current number as 0. so we have done that now we will move we are now getting a b so as we are getting a b view depended to our current string here we would add that character B now we will get a c so we would go to the else part and we would add that character C now what will happen is we are encountering a closed bracket so as we are encountering a closed bracket we would update our previous string to our and we would pop this out AAA and update our previous string so our previous string would look something like this and our previous num would now be updated to now we would write our current string we would update our current string so that would be our previous string plus our current string into previous number so our current string is BC into previous number that is 2 so twice of BC so now what we will do is our current string has been updated and it has become Triple A and two uh like two BCS so it has now become a and BC so after that we have reached the end of our iterations our for Loop has ended we won't be entering our while loop as uh like we have popped this out as we encountered a closed bracket and we have updated our previous string in previous num we have popped these out from the stack so our stack is empty so we won't be entering this while loop so we would be returning our current string which is AAA bcbc now you can do your own uh dry runs with the other example that is given and uh yeah so that would be uh it and I'll see you in the next video thank you for watching
|
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
|
822 |
hey everybody this is Larry this is me doing a bonus extra question trying to get myself you know I mean try to get myself to do a problem that I haven't done before uh that's basically and get my money's worth on uh you know RNG give me a good one L I mean a lead code AI why am I talking to myself it's kind of weird all right today's problem is uh and it's not a premium problem but it is a problem with a lot of downloads a22 card flipping game uh yeah so you're given two zero index Inger R front and back of length and where di card has to POS and then back on the other side uh each card is placed on the table the front size is on the front Okay okay then you may flip over any number of cards after flipping the card an integer is considered good if it's facing down on some card and not facing up on any card return to minimum possible good integer after flipping the card so there no good integers return zero all right uh what does this mean I think the critical part is just like this right an integer is considered good if it is faed down on some card so basically if it's on the back if you will and not faced up on any card all right and we can flip any number of times okay um okay so well this one's a little bit awkward immediately because um the first thing I wanted to check is n and if n is equal to 1,000 I think that's it that's like to 1,000 I think that's it that's like to 1,000 I think that's it that's like GG right what I mean by that is that because then now you can do an N Square thing they only n distinct numbers I guess n * two distinct numbers you could guess n * two distinct numbers you could guess n * two distinct numbers you could just check all of them in a greedy kind of way and that'll be n square like um like you can for each number you can see if it can be good and it is good if um all the um if you could flip everything here um to like if that number is not on the front side after flipping right so I think that's basically how I would attack this uh I'm a little confused about the download cuz I mean it I mean is it an interesting problem not really um but is it a I don't know I don't see any like weird like edges for this one cases uh I mean the only one that I had considered was actually this one but uh but you know they have it in an example so I don't even think that's yeah um okay so yes I don't know so the right so maybe you know um you know let's just say this is the set of numbers right so then now we sort them yeah so now for X inserted as right so then now we just try to see if x is good and we return zero if they're no good integers so yeah so this is good if uh all right let's just say if good X then we return X I'm a little bit lazy right I'm a little bit you know we can abstract it so then X so the number is good if it is face down on some CT and not face so then for now for front back in zip of fronts backs um I mean maybe we'll discover a weird Edge case and then we'll see but uh but basically we have to be um okay so found maybe is going to force and this is just to show that it is faced down somewhere right so yeah so if but like you can flip every card so it doesn't even make sense right so the only time where you cannot do this number is if I don't know I mean I'm going to go with the N square one but yeah if front is equal to X or back is equal to X then found is equal to True right if f is equal to X or F is equal to B n is equal to X then we return Force because you cannot FP both sides and that's really it right like we just have to and because we always choose a number that's in here so this is always going to be true I don't think that this can be false because we always choose a number that's in here so I'm really I'm like i s f because I'm just like really confused about this problem or I'm really confed confused about like how you know okay I mean I don't know why there's so many downloads I guess that's the thing and now that um we kind of confirm it I mean this it doesn't change the complexity that's why I left it in otherwise you know um you can even just done something like this and then just return true right so then now this is you know slightly cleaner um and then now can we even optimize it a little bit more um yeah we just changed like a lot of operations but yeah I mean we can probably do it the other way right now that we know that this Pro I mean I to be honest I didn't really have motivation to optim prematurely optimize it because N is a th right like we said solve the problem that you're given N is a th I'm not going to prematurely optimize and this is n Square you know this is n yeah I mean this is still n even though we have sorted so it's n log n from the Sorting but you know it is an N Square solution so it's going to be do dominated by the N square and not the N log n so that's why it's n square but now that we kind of see this properly um now that we see this properly we can just kind of keep track of where all the things where this is the case right so then now we can maybe we don't even maybe need to sort it right so then now um maybe we can just do like for fun back and zp of fronts backs right so then now we could do maybe like doubles as a set and then um and then seen this set I guess I don't know something like that right and then now or we add fun we add back and then if f is equal to P then doubles. add F right then now we can just return the diin uh oh well I guess I think you could do that you could do scene minus doubles um with the default of zero something like that right I think default is the thing right I didn't make this up yeah so then now this is linear time linear space and yeah pretty straightforward I was thinking about this during the prom self but I just you know didn't want to um like if this was a contest I would definitely not have done it this way for sure I would have done the N Square way because I don't have to prove anything or I guess maybe there's a little bit of proof but it's not as um it's not that difficult of a proof but here you know you have to really make like you have to be really confident about the proof right so uh this one's really awkward um mostly due to um you can flip any number of cards I think if you have limited number of flips I guess that changes the problem a bit but yeah I don't know why all the download though I am curious I'm going to just check out the Sol I wish there like a forum or something is there a forum or something I don't know I'm just really curious why um huh I don't know I mean I guess it's not that important but I think I was just very curious why there's so many downloads I mean is it an like I said is it an interesting poem not really but is it a bad problem I don't know uh it's a little bit uh trixy but I don't know if it's a bad problem per say but yeah all right friends that's all I have for this one let me know what you think stay good stay healthy to your mental health I'll see you later and take care bye-bye
|
Card Flipping Game
|
unique-morse-code-words
|
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).
After flipping the cards, an integer is considered **good** if it is facing down on some card and **not** facing up on any card.
Return _the minimum possible good integer after flipping the cards_. If there are no good integers, return `0`.
**Example 1:**
**Input:** fronts = \[1,2,4,4,7\], backs = \[1,3,4,1,3\]
**Output:** 2
**Explanation:**
If we flip the second card, the face up numbers are \[1,3,4,4,7\] and the face down are \[1,2,4,1,3\].
2 is the minimum good integer as it appears facing down but not facing up.
It can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.
**Example 2:**
**Input:** fronts = \[1\], backs = \[1\]
**Output:** 0
**Explanation:**
There are no good integers no matter how we flip the cards, so we return 0.
**Constraints:**
* `n == fronts.length == backs.length`
* `1 <= n <= 1000`
* `1 <= fronts[i], backs[i] <= 2000`
| null |
Array,Hash Table,String
|
Easy
| null |
298 |
Hello friends welcome to my channel let's have a look at problem 298 binary tree longest conductive sequence in this video we are going to share a treatment based on recursion first we'll read through the statement to digest the problem requirements and then we do the analysis and share the code first the statement given the root of a binary tree return the length of the longest convective sequence path so here is consecutive sequence path is a pass various values increased by one along the path and note that the pulse can start at any node in the tree and we cannot go from a node to its parents in the path in other words we can only go downwards right so let's look at the two examples here so in example one so the output is 3 and the corresponding longest convective plus is three four five so in example two so the output is 2 so the corresponding longest conductive path is 2 3. so notice that we have another pseudo um conductive um path so starting from 1 then to two and two three however this is in the reverse Direction which is not codified so in this problem we are going to return to so with the examples went over let's look at the constraints the first constraint is the on the number of nodes so it's between 1 and 3 times 10 to the power of 4. so in particular the tree is not now right in other words our return is at least one right because we have event at least one node the second constant is on the Node value it's in the range given by the negative three times ten to the power 4 and it's absolute value that is positive three times ten to the power of 4. so in particular the node value can be zero or negative so with that said we are ready to look at the treatment so here the treatment is based on recursion so recursion here is very natural so if we consider the two of Parts below first the banner tree has a abstract data Tab and it's recursive in nature right the second one is the problem logic so this will be made clear in the coding so let's look at the idea so the idea actually is very straightforward so for each node we are going to compute two pieces of information compute two right and not um we can call them L and R so in other words we want to write a function let's call it f so it returns two pieces of the information L and R where L is the longest conductive path length starting from node towards left and R is towards red so this way at each node we could find the longest consecutive path stemming from that node so this length is nothing but the max of L and r so we just need to update this quantity during our traversal of the tree in order to return the result so as to how to get LR for a node so this is actually very straightforward so if we initialize F note and to be one in other words R equals 1 and L equals one then if note left exists and note left value is very larger than the node value so we are going to update L by L increments by Max LL and LR in other words the longest conjective path lens stemming from the node left right so you can interpret LL and LR as L and R information for node left so similarly we can do the update for R by considering the red substitute so in the recursive process we just need to update the quantity Max LR for the result so with that said I guess the writing the code is a straightforward so now let's look at the coding so in order to do the continuous update I'm going to introduce a attribute let's call it result so I'm going to initialize it as one due to the fact that the root as a tree is not now and then we are going to look at the hyper function so I'm going to accept a node so I'm just use this as a root just for convenience so you can write it here node so we use the root so that we can write this left Symmetry and the red sub tree so let's first treat a special case if not root so we're going to return 0 right so this is a stop condition or base case for the recursion so next I'm going to set L and R to be 1 and 1. in other words currently we Loop the paths only containing the root node itself and then let's check if root left so in other words if we have a left sub G then let's first get information for the leftover tree right root left and then we are going to check if root value Plus 1. equals root left value right so in this case we can connect the root with the uh the root the left subtree root so this way we can update this L to be incremented by a Max of LL and LR right so this is the one case so next we are going to check root or rate so in this case so we're going to get RL and RR to be F root rate right so now we want to check if we can chain the root with the root the red subtree together by considering the king's activity right so root Value Plus 1 equals root red value so this expression here root rate value is Meaningful because we have because it's at this if block similarly above for root left value so now if this is the case so we are going to increment R by Max RL and RR right so this V we have found the information LR for the root and then we are going to update our result set of result that's going to be um the max of its previous stage and the max of L and R So Max L and R is the longest conductive path stemming from the current root right so that's actually the logic so we're going to return um L and r so this is the hyper function so next we just need to call this the function so I have called f root so this actually is going to return L and R but we do not need them so actually we can do this if we like or we just the right effort and then what we are going to return is uh self result so this is the final stage of this attribute so with that said so we are ready to do the check yeah it passes one example now let's look at generic case right it passes all the cases so let's check again yeah it passes all the test cases I guess for this problem so that's about it for the coding so you are welcome to check out other videos in my Channel or playlist for explanations on algorithms and political problems without said I guess that's it for this video thank you
|
Binary Tree Longest Consecutive Sequence
|
binary-tree-longest-consecutive-sequence
|
Given the `root` of a binary tree, return _the length of the longest **consecutive sequence path**_.
A **consecutive sequence path** is a path where the values **increase by one** along the path.
Note that the path can start **at any node** in the tree, and you cannot go from a node to its parent in the path.
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,null,null,5\]
**Output:** 3
**Explanation:** Longest consecutive sequence path is 3-4-5, so return 3.
**Example 2:**
**Input:** root = \[2,null,3,2,null,1\]
**Output:** 2
**Explanation:** Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 3 * 104]`.
* `-3 * 104 <= Node.val <= 3 * 104`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
128,549,1416
|
994 |
hello everyone welcome to codas camp we are a 29th day of october eco challenge and the problem we are going to cover in this video is rotting oranges so the input given here is the m cross en matrix with values 0 1 and 2 so here the values represent 0 represent an empty cell 1 represent fresh orange and 2 represent rotten oranges and it is said that every minute any fresh orange in four directionally adjacent to a rotten orange becomes rotten we have to return the minimum number of minutes that must elapse until no cell has a fresh orange so it is impossible to return minus one so let's understand this with an example so here is a given input matrix where the actual inputs will be in the format of 0 1 and 2 but here for a better understanding we have the pictorial representation of the same input array so now we have the condition every rotten orange will rot in the fresh orange four directionally adjacent to it at each minute so what does it imply is for a first minute from the first rotten orange the adjacent oranges in four direction will be rotten also so starting at the very first minute the orange at 0 is rotten so now the minute is equal to 1 this rotten orange will rotten the fresh oranges adjacent to it four directionally so four directionally means there is one at the right side to it and there is one down to it there is also a diagonal orange which is fresh but that can be affected by the rotten orange since they affect only four directionally so at the minute one the oranges that gets rotten will be this and this so once this is done moving on to a minute two so now the minute is two and we have to rot in the fresh oranges which are four directionally adjacent to the rotten oranges in this case this orange will get rotten as it can be rotten either from the left side drop in orange or the upward rotten orange and this also will be rotten because the orange which is left to it is already rotten so now we are at minute two now let's move to the minute three to check if there are any more fresh oranges left to be rotted so yes there are still there and at this minute only this orange will get rotten because the next orange which is fresh is adjacent to the rotten orange so now the minute is three we had brought in only one orange and let's move to the minute four and we still have one orange left to be rotten and that will be rotten at this step so now all the oranges are completely rotten we have no more fresh oranges exist in the grid which means our time has elapsed to 4 minutes to get all the oranges rotten in our given matrix and 4 is going to be our output so how are we going to approach this problem if you have watched any matrix problem which needs to find a path or find minimum distance or something similar to this from our channel you must be now figured out that we are going to solve this using bfs technique why because we always choose bfs whenever there is a path to be traversed or uh we need to explore all possible direction or four direction in the grid these kind of problems will always use bfs to get best possible outcome so let's see how we're going to implement this so as we said we are going to solve this using bfs we are going to use the same pattern of code where we use to solve any bfs problem so any bffs problem would actually require q where we add the coordinates where we have to visit and once visited we are going to explore its children or neighbors four directionally and add them back in the queue so now let's start with adding 0 comma 0 since the rotten orange is there and start exploring from this path as per the problem statement we have to visit the oranges which are four directionally present from any cell in the grid so from zero comma zero the four directional grids we can visit are either zero comma one and one comma zero so let's add both of them to our queue so let's check the values both the cells are having the value one which is nothing but fresh oranges so here zero comma zero is having rotten oranges so from here we are going to rot in its neighboring cells as well so add the minute one by the same time we are going to have variable count which is going to count the minute also another variable count fresh which is going to count the number of fresh oranges in the grid why because we need to end the loop when all the oranges are rotten we don't have to explore all the cells to complete our iteration in order to do that let's first have the fresh oranges count so there are one two three four five six fresh oranges at the initial stage when we start exploring now we have made two other oranges to uh rotten which means we are going to update the value to 2 which is the value of rotten oranges so we are going to rotten them which is nothing but we are going to update the values to 2 in those cells which will be 1 previously that represent a fresh orange and now the fresh orange count becomes four because we have brought in two more oranges in the fresh oranges so now we are going to explore its path and put them here so from zero comma one first we can uh check zero comma two or one comma one so both the paths are not already there in the queue so we are going to add zero comma two as well as 1 comma 1 in our q same way 1 comma 0 from 1 comma 0 you can either visit to 0 comma 0 which we already put to 2 so we are not going to revisit them again and again instead we are going to add one comma one is also there so this minute one has been done so now we are entering or incrementing our counter to two which represent the minute so again same way it updates both the cells 0 comma 2 as well as 1 comma 1 to 2 and rotten them and decrement the count of rotten oranges now there are two left at the next step from here you can't explore anything that is from zero comma two so from one comma one you can explore two comma one other than that you don't have any other uh or cells which has value one because these are empty and this will be zero so again at the third minute we are going to uh increment our counter to three decrement our rotten oranges sorry fresh oranges to one and update this cell to two and that the next step we are going to update our queue to 2 comma 2 and now it's time to increment our counter to 4 and update the value to 2 which means the rotten oranges and update our fresh oranges to 0 so now our account trash becomes 0 which means we have wrought in all the oranges in the grid now what is the value in the variable count will be the result we are going to return so hope you are understanding this brief concept lets go to the code now so lets first declare the basic variables so let's check the base condition that if the grid is null then return null so first let's iterate the given array and find where the rotten orange starts and wherever it starts start putting its neighboring cells to the cube so yes we have iterated and checked where is our first rotten orange and added the rotten oranges or what are all the rotten oranges in the cell because if there is a rotten orange in the very first cell and the lost cell both its neighbor will be simultaneously getting rotten so wherever there is a rotten orange we are adding that coordinates to our cube same way at the initial stage itself we are checking if the value is 1 we are incrementing the count fringe variable to count the number of fresh oranges in the table initially so now what if there is no fresh oranges at all which means all the oranges present are rotten oranges so we are simply returning 0 because of the 0th minutes itself everything is rotted and we are declaring an array direction in order to explore 4 directionally the neighbors so whenever we explore a coordinate from our pfs queue we are going to increment our count variable to indicate that the first minute has started this is similar to any iteration we use for bfs where we take the size of the cube currently and then explore its neighbors once those neighbors are explored and added to the cube we will pop or remove the elements in the front of the cube so we are finding new coordinate for our each neighbor from our directions array so once the new coordinate is added we first have to check whether the new calculated coordinate is outside the boundary of the given array or it is an empty cell or it is a already rotten cell so the values should be having one only then we have to rotten them otherwise it is empty or rotten already we don't have to really care and we can continue with our next cells if not if all the values are not there then the grid value must be 1 so in that case we are going to rot in it and we are going to update the value to 2. so once we update the value to 2 we are going to explore its neighbors and add them to our cube and then once we updated the oranges to rotten we are going to decrement our count fresh variable to indicate that we have wrought in a fresh orange so yes that's it the whole iteration goes until all the comp q becomes zero and finally we are going to check whether our count fresh becomes zero then which means we have expanded this many minutes count minus 1 minutes if not minus 1 though minus 1 is not possible as per the given statement but still we cover the condition so let's run and try yes our solution is accepted let's submit and try yes we completed today's problem and it runs in 2 milliseconds which is faster than 97 percentage of solutions so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Rotting Oranges
|
prison-cells-after-n-days
|
You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`.
| null |
Array,Hash Table,Math,Bit Manipulation
|
Medium
| null |
146 |
here today we are going to be doing a very popular delete code and that is leak code 146 LRU cache LRU steps released recently used if you're not aware and yeah let's hop right into it this is a very popular programming question and that is quite difficult hard I don't think if you unless you've done it before I don't think you have a really good shot at doing it and one second let me just make sure that I started up there we are and yeah and I've personally failed it in interviews as well but it's a very interesting problem and I think once you have a grat a good grasp on it is interesting to think about what data structures and algorithms it's something interesting to kind of think about so with that let's hop into what is LRU cache actually mean so LRU is a type of cache replacement policy so it is reading right off Wikipedia here and computing cache algorithms also frequently called cache replacing replacement algorithms or cache replacement policies or optimizing instructions or algorithms that a computer program or a hardware maintain structure can follow in order to maintain a cache hey Paul sending thanks for stopping in today and let me just turn down the volume so to manage a cache of information stored on the computer when the cache is full the algorithm must choose which items to discard to make room for the new ones so least recently used let's hop into one right here so this is the example on Wikipedia the access sequence for the below example is ABCDE D F so this has a capacity of four we add an A and it becomes rank zero then the B is added next as you see here and so we have a B a with rank 0 B of rank 1 add the C comes rank 2 and D becomes rank 3 the interesting thing happens when we add the e we need to now replace something and we replace the least recently as thing so a was a rank 0 you replaced the lowest rank and then E uh is now added where the a was when we add the D these are D in there it's already in the cache but it was rank 3 but now becomes rank 5 so it's kind of been like refreshed it's now the most recently used thing and then when we add an F well we need to replace the lowest rank thing and that is now a B so it becomes e FC D for the final answer so to do this I'll just kind of spill the beans right away to make sure that we have time for debugging before I do that let's actually walk through the problem statement and leak up so it'll design implement add a structure for release recently is cache it should support the following operations get and put get of a key gets the value will always be positive of the key if the key exists in the cache otherwise it'll return a negative one put the key value we'll set our insert the key value if the key is not already present when the cast which is its capacity it should invalidate the least recently used item before inserting a new item that was that a being replaced like we talked about before the big thing is could you do both operations in a one-time complexity both operations in a one-time complexity both operations in a one-time complexity so if you have some familiarity with data structures and algorithms you just think you see a get ok you get the value and you want to do that in constant time complexity or o1 time complexity well you just take a dictionary and then that is the case but with just a dictionary you would be unable to keep track of things you want to use a different data structure in to compliment the dictionary and here we're going to use a doubly linked list and I'll get into a little bit more of how that works but let's go through the example right here so we instantiate a LRU cache with a capacity of two we put a key value pair of 1 and one end then we put a key value pair of two and two so at this point at the end of the second line the put the 1 key value pair is the least recently used but once we get that well first off we're gonna return a 1 but when we put the 3 we have it now key to because by getting the one we kind of refreshed it then if we get the two well it's not there anymore because it's been evicted then if we put the 4/4 it's been evicted then if we put the 4/4 it's been evicted then if we put the 4/4 and then we get rid of the one so we have three four we get the one it's no longer there when you get the three returns a three get the four trans before so let's hop right into it we're going to use it something called a doubly linked list so we're gonna have that class it's gonna have a node and in an Annette it's going to take itself and the key value and for those of you not familiar Python self is similar to this and a few different languages such as Java JavaScript so self that key equals key self dot value equals value self dot pre evils none and self dot next also equals none not nandi so let's hop to the big board real quick so in a singly linked list which you may be familiar with we just have nodes and they point one way with it with usually in next what you see and the doubly linked list as you can imagine in addition to the next now we have priests so that's all we have and to anit those nodes we say their necks and their premiums are none to start so let's hop back in to the code so we're also gonna have that LRU cache as a class that is also going to have an annette and that's just gonna take a capacity and we're gonna say well the self death capacity so we can use that elsewhere for this instance that's going to be the capacity we're gonna head in stan she ate that dick like this which is not technically correct i don't think you should be you should write self dot dict for this because i think dick is reserved I think it works for now and it's the way that I'm used to doing it oh by the way I'm recreating a leak code solution by a user called to Susie so thanks a lot to Susie which was a very interesting one yep and then we're going to have the self with Bessie the self dot dict now we're going to have heads and a tail and that those will be in ten shaded as instances of nodes with key value pairs of zero and zero each and that'll become a little bit more clear while we're using those and a little bit and the head next will point to the tail and the tail previous will point back good so we're gonna want to have two helper functions for this and that we're gonna want to help to like keep things as refreshed as they should be so we want to have a remove first and then we want to think about nad so let's go to the big board so if I'm given a node that I'm passing into a dot a an underscore removed function how do I actually remove this node so with a doubly linked list how you do it is or one way to do it is to find well what's the previous of this node and you can just do that by saying previous sequels no duck previous and what's the next of this node find that very similar similarly and then you just rewrite well so previous the next of the previous points to node but if we say instead of that if the next of the previous points the next and for the next node if the previous of the next points to the previous well like we kind of bypassed this note it's like it's pointing out but it's not nothing's pointing to it and so for all intents and purposes it's gone G gone so that is no longer there so that's how we write or remove so let's get into it so the remove will just take a note and will just do exactly what we just said so the previous equals node dot previous/next equals 9x and the previous/next equals 9x and the previous/next equals 9x and the previous bypasses the node so the previous got next was previously of a node get a little confusing it but now the previous/next now equals the next and previous/next now equals the next and previous/next now equals the next and the next step previous was the node but now the previous of the following node will become the previous and that's all there is to the remove make one then we have an add so we're gonna be adding to tail and I'm a little big board for this one as well but that's also gonna take itself in a node and so how we're gonna add so we're gonna add from the tail and we're gonna pop from the head which i think is a little bit backwards but you mean should be comfortable to them both so we have had we have a head up here when we got a tail all the way back here huh and in the sake of brevity I won't draw both arrows for this except for these last two because we're really adding to the feel so we know what the tail is it's called the self cocktail that previous and those kind of like stay as like little landmarks so here's our tail and let's say we want to add a note here so this is called the tail we can find this previous because that's just self that held up previous so this becomes a previous and we have our node here so how do we insert this how do we add this to the tail I can see now it's a little small what's the best we got name it so what we're going to do is just say well the previous we know the previous is the previous dot next is going to equal the node the tail dock radius is also going to equal the node and then we just draw from it up then the note that previous equals the previous and then the note that next equals 1/10 and that's how you that next equals 1/10 and that's how you that next equals 1/10 and that's how you do an insert with a doubly-linked list do an insert with a doubly-linked list do an insert with a doubly-linked list or an ad so let's hop to it so we want to find that previous that's just self dot tailed up previous then we say well the previous/next is the node and then the previous/next is the node and then the previous/next is the node and then we say well the self dot tail that previous now is no longer the previous it's also the note now we have to draw those lines back from the node that produces was the previous and the node next equals the self dot tail and with that we're done with the helper function so let's hop right into the heat of the meet we want to do self dot get which takes itself in the capacity that is not how you write this there are no cells for there sorry about that little syntax error for you good thing I caught it and the gate does not take capacity it takes the key and all we do with that key is well if it's there we do something right so if key and that dictionary cuz this is that constant time lookup we're gonna do something if it's not there then we do return negative one but the key is in the dictionary well we want to do that refresh steps so I close the Wikipedia page but when we access everything that we access that's already in the dictionary needs to become the most recently used so how do we do that we just remove it and we add it back again we remove it gets removed for the linked list and then we add it back again it becomes in the most certainly use spot by virtue of our addition method so that's all we do so we just say no equals the self got of key and then we just remove it and we just add it back in and that's all there's to it for again then we need to add the put so put self key this needs a value as well we're not just looking for keys whilst looking for values similarly to get the get Haeckel rely thanks for stopping it similar to the get we see if the key is in the self-taught dictionary because if we put self-taught dictionary because if we put self-taught dictionary because if we put something already in there needs to be refreshed and to refresh it first need to remove it so we're then we're going to self dot underscore remove that self got of key so a little water for you these removes look a little bit differently up here i assign a node because i use it twice down here i don't so I don't use it twice I just remove the subjective key not the node so it's no need to be confused there if it's in there we remove it and then now we need to add it back in or add it in the first place so the node is going to be of the node an instance of the node class with keys of key with a key of key and a value of value and then we just add that in to our linked list with just like add like that and then we also make the dictionary value for the key that's passed in equal to that note because that's yet doubly linked lists is serves as the value of our dictionary that's kind of like the main point of this now the put is interesting though because remember when we got rid of the least recently used things so when do we do that we get rid of those if the if we were over our core pack our capacity so if the length of the self nicht is greater than the self at capacity now we want to remove the least recently used thing and like we talked before we're removing from the head so if I go too big more if I added I did this step right out of this now I'm gonna remove this note right here and that'll be redrawn like so to get to the code if the length of self dicta is greater than self that capacity then we also make an assign a note this time the note is going to be that head next we're not removing the head or the tail those service little markers that keep us on the straight and narrow but then we want to self underscore remove that node and we want to delete that key value pair from our dictionary citizen influence our capacity so how we do that in Python is just write fleet self dot dict and what the key is just the node key so about 13 minutes left I did this problem twice before hand the first time everything worked properly and the second time it didn't the second time I couldn't figure out what my problem was but I think I was messing up my selfs like I was doing earlier so let's take a walk through the code and then see if it works so the main idea is correct the syntax might be get this here so we're using a doubly linked list to do at least recently used cash the doubly linked list we use nodes that have key values they start off with the key the self that keeping key set up by being the value and previous and next of none then we have an LRU cache itself which has a capacity south that capacity of capacity self that dick does dict its head starts off as a node of key value pair of zero similar this tail and its head points to a tail and those are kind of just like a little empty notes that we can use to keep track of things itself that head that next equal to sup that tail and the self that tell that previously was itself that head before we get into the get input let's go to our helper functions I'm actually gonna I don't like the cheat on these type of things but I think yeah we're in a good spot obviously oops no little bananas something they look right for function definitions it's always good to write a def wondering why does this not look right so when we remove we find out where the previous is from the node we find out where the next is for the node and then the previous next points to the following node and the previous of the next node points to the previous so that's how we remove when we add a node we find the previous we're adding the tail the previous of the next becomes a node the previous of the tail becomes that node and that node points to those two as well so here's where we want to look at constant time and for getting and putting if the key is in the self picked which is constant time lookup then the node equals the self addictive key so the values are our nodes of this linked list we were moving and add it back to refresh the how recently used it was and if it's not we just return negative one oops and it's very important to return note value otherwise yeah we're not returning anything properly and then if the key is in the self dect for a put which is this should also be constant time we remove it and then if it's if it is or it isn't in there we at we make a new node we added we make we set the value of that key in the dictionary to that node and it's greater than the dictionary length becomes rated in the capacity we removed from the front so that looks to be on the up-and-up so that looks to be on the up-and-up so that looks to be on the up-and-up let's go ahead and submit the solution and cross our fingers that everything is good no whammies and it's accepted so it's surprising you before this I'm not sure what I was doing wrong I think I may have been leaving out this returning the node dot value but this is a very interesting problem I think it's probably one of the most difficult that you'll see for most interviews it's a leak code hard and like only about 140,000 out of 750,000 like only about 140,000 out of 750,000 like only about 140,000 out of 750,000 have solutions to it there are ones that are simpler there's even some in the comet chains for this solution that are simpler that don't use a head or a tail but I think that's actually more confusing by leaving those lines out for me thinking about ok we have this like markers that's a little bit easier for me to wrap my head around some gotchas well I also say this as well you know in a 45-minute if you're well you know in a 45-minute if you're well you know in a 45-minute if you're practicing for coding interviews you will not see many problems much longer than this because this is 50 lines of Python and it's just you don't have that much time and a 45-minute interview just much time and a 45-minute interview just much time and a 45-minute interview just like the physicality a write writing net that much out you're not going to see that much out but beyond just practicing for interviews I think it's an interesting application of the strengths of two data structures of using a dictionary and a doubly-linked list to dictionary and a doubly-linked list to dictionary and a doubly-linked list to get constant time putting and getting time complexity so let's do some gotchas things that I got hung up before I wrap things up here just general syntax things I when you do the in it's you have to point your head next to the tail and you have to point your tail out previous in the head I forgot that a few times when I was practicing for this one I at this time I forgot to return the node that value it's silly things like this you always remember what I do if catches I think okay if you don't hit this conditional inside shouldn't say it catches that's not a real thing if I do an if conditional I think okay you know if I don't get that what do I return it is always very important to remember what you return if you get it as well and just general syntax things there's a lot once you get a little bit lengthier in the in these problems just a lot of places to get tripped up but with that said this was at least recently used cash leak to a problem number 146 from programmer Mitch thanks for stopping in this Sunday I'll be live on next Sunday at 6:30 p.m. doing on next Sunday at 6:30 p.m. doing on next Sunday at 6:30 p.m. doing another programming question I hope to see you then I am no longer doing the hot sauce challenge because my stomach was really disagreeing with me so sorry for people that were tuning in for that but like I said that's the end of the show here today thanks a lot for stopping in and I'll see you next time
|
LRU Cache
|
lru-cache
|
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Medium
|
460,588,604,1903
|
905 |
9:05 saw it away by parody given in a 9:05 saw it away by parody given in a 9:05 saw it away by parody given in a way a of non-negative integers we turn way a of non-negative integers we turn way a of non-negative integers we turn in a way consisting of only given elements of a file by order odd element effect you may return any answer away that satisfy this condition okay uh I mean I guess it is just what it sounds like that shook there's a anything tricky about it I mean yeah so what I would generally try to doing these sorting function is just for starting problems is to just write a comparator and in this case that should not be that hard you just want order give a number stood before the odd numbers so okay I know if it is even then it becomes beginning maybe someone like that oh I guess that's in Texas not in pipeline it's that other ternary operator just like someone like dad or something if I remember correctly academic number so despite what come on I'll just write a little thing right and now I have to look it up they do how is it there thanks for something and uh thanks for coming SN 314 yeah I think it's something like that it's just a spin a while and also uh I think in general I don't think that's code that I've dad like I may be a other people have different opinion about if I think it's probably not good production that would code because these do a lot of confusion in China mo so that's why my first though was doing that but let's see if that works cool so that works I mean yeah it's kind of what it sounds like I did a little hacky thing to kind of make it easier to code though you could definitely have white something based on comparator meaning came in two numbers you compare which one is bigger or which one comes before and so forth the way I did it is I actually said uh I mapped each number to a key and if it's even we put it in a while we set it to a negative number which always puts it in front of all the positive numbers in theory well given that it only contains nine non-negative integers for this problem non-negative integers for this problem non-negative integers for this problem so yeah a simple problem I think this is probably easy for a phone screen in general but it could be like I could see it being like a you know 10 or 15 minute problem at the beginning of a couple of problems and it's kind of like was it phase bus or something like that way where the people just want to know double checked in to see if you actually know programming like you claimed you do kind of thing and you know you can do this in a number of ways so but however you do it as long as you don't do something crazy it should be okay I mean like you could ride your sword or something but given ten that should be like four or five lines of code if you do it correctly so I don't know but at the end of the day it should not be done much coding for this ball yes I think one additional thing to point out about this problem there's a little bit after the fact is on stream I just liked having farms and I actually because this is a easy problem I didn't really give this as much thought as I should have probably imagined I actually did not solve this optimally I think in these kind of age when you do things online it's easy to kind of do the easiest thing that works yeah do the easiest thing that works but not necessary to optimal solution right in this case I think if this was an interview or something like that maybe I don't know why they chose end to be so small in that case though but you can actually so this is n log n because we do a sort but actually you know you could another way to think about this and there's linear way to do this there's a things that are kind of similar to like bucket sword or something like that or you know weight X radix sort or something like that one of those linear sort so you could do toes in linear time and in fact and or you could depend how you want to phrase it but you guys have like a period or you could kind of do like a like in quicksort where you know you sort around period example in this case you just goes through the entire list and then kind of maybe keep you know pointers along the way and you could turn over end time right so definitely on an interview definitely try to think I definitely jumped into this bomb really quickly because I was raised where you know it's very simple to understand and it's very easy to implement and when you look at the constraints it's very small so you to understand where you could do it and very easy ways but doing them do we're definitely slowed down a little bit because I think Isis finished this in like less than five minutes you have to you know you have more time so definitely pace yourself and make sure that you go forward the possible answers before you know you figure out what you want to do and especially coin and every day
|
Sort Array By Parity
|
length-of-longest-fibonacci-subsequence
|
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers.
Return _**any array** that satisfies this condition_.
**Example 1:**
**Input:** nums = \[3,1,2,4\]
**Output:** \[2,4,3,1\]
**Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted.
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 5000`
* `0 <= nums[i] <= 5000`
| null |
Array,Hash Table,Dynamic Programming
|
Medium
|
1013
|
76 |
this is the recap of singapore javascript in a real meet up on August 25th the first question is a little question given two strings find the minimum window in ass by window it just means substring find the minimum window in ass that contains all the characters in T now you do not have to maintain the same order for example B and C this is omit this is a window within s it doesn't have to be the same order as ABC so some of the other valid windows is a DOB see you can also include this D you can have BBC oh the EP a full of all these windows we want to find the minimum of it meaning the length should be the shortest your tale you can have duplicate so you can have multiple age multiple based multiple sees it's just in this case it's unique pause the video and see you can solve it what is the intuition behind this question your intuition is pretty simple we want to find a valid window for now let's not concern about a minimum window let's just say how shall we identify this is a valid window once we identify a valid window we start shrinking it until we can't shrink it anymore so if you have a window like this you start shrinking so you shrink from the front it will become like this it's not valid anymore once it's not valid anymore you start expanding again so you start expanding all the way until where are you valid again when you reach another a so when you are this window you are a valid again you start shrinking from the front so you shrink will become like this you are still valid so start shrinking is this valid it is still valid you shrink until here this is valid but you're shrinking again it's not valid anymore so if it is not valid anymore you start explaining again until the end this is a valid window you start shrinking shrink all the way until you reach yeah anything so let us set it up loop through my R represent right index and L represents the left index of the window are cannot be out of bound expand to find a valid window it valid Frank tell invalid or can't shrink anymore also update result because it is a valid window how do we know if a window is valid we can have a count map that keep track of how many each characters do we need to match for example ABC we need to match a once B 1 C ones if you have a BB CC you need to match a twice B twice C twice so we can have a comp match can't count map is in the right of 128 for the love with zero or cost char t + + count love with zero or cost char t + + count love with zero or cost char t + + count map chart dot Tarko and if you are familiar of an ASCII table each character will map to a decimal value there's less than 127 so a capital A will map to 65 similar it's BMAC so in our case a capital ABC would increment the position of 65 to 67 by one all the rest of the array will be 0 that's what this line is we are keeping track of the count of each characters if there are no characters there is default to zero because we fill it up as zero this should be square bracket okay how do we know our current window is a valid window we can have another window called window another array called window initialize to zero and we fill it up as we visit each character as we are visiting the character at position R remember R is the right index we increment it increment the window at the position s dot R K and s no so let's have a helper function that tell us is valid it's gonna take in two things the count map where the count map is what we should match and the window is the current window so when is it valid let's see when is it not valid we look through all 128 if the window I is less and count map hi it's considered you match less than what is minimum required return false you can have more but you can't have less if you fulfill all 128 you return true I think there should be a bracket here okay so the idea is if your valid we just keep shrinking we can use a while loop while is valid count map and window our left index also need to be less than you call so right index because left should be to the left or right we update the result now here you can have a reload string and keep overriding it as long as the current window has shorter length than the result string but string slicing is actually expensive so instead of initializing a string I'm actually gonna initialize the index I'm going to call it low and high my negative one meaning is not a valid in that it also signals to me it has never been written before so if my low is less than zero I should write it low will be left index high will be the right index else I should only override it when the current window has a shorter length so my right - length so my right - length so my right - left is shorter than high minus low so here we are updating the result where low and high represent final result index they are both inclusive range now we need to shrink it now before we Frank we should decrement the count at the index of left because we are shrinking the left basically we do the reversal bears when we expand when I expanding on the right so u plus the position on the right but when we Frank we - - and we shrink but when we Frank we - - and we shrink but when we Frank we - - and we shrink the left then we plus left if you want you can put plus here it has to be posting them in you cannot put it as pre increment it has to be post increment now the final result will be if low is less than zero meaning it is not a valid index meaning there's no valid window anywhere we return an empty string else we return the substring no high plus one because this is actually exclusive range so it works the time complexity for this curler is all event it's linear your outer wire loop the index R will travel through the string once although you have an inner wire loop but in a while loop left will be upper bound by r and once left is advancing to the right it will never be set back again so left will also traverse through the string once you essentially have two linear or two all of em which is Oliver although it is all of them is not optimized specifically this is valid function we check for 128 times I know you have early stopping but so this is not optimized however I must stress that the optimized solution is pretty complicated it took me quite a while to figure it out so I'm not going to go in-depth into that instead I'm to go in-depth into that instead I'm to go in-depth into that instead I'm just gonna give you the solution and a very brief explanation so instead of using this is valid let's get rid of it we will use a variable called to match let's initialize it to the length of the word we're gonna match so ABC lengths is three we have three two Mac instead of saying is valid we will say as long as there's nothing else to match it is valid is the same concept we will not use the current window array instead we will operate on the same array which is count map so this line is not valid anymore expand to find a valid window previously we are incrementing window now since we are operating on the same count map we can do the opposite of plus with into minus a star at our make it more readable this is too far you can think of this as we are initializing how many counts we are missing or how many we are yet to match but inside this world whenever we are visiting index are we are fulfilling the count we are only fulfilling account if there is account their account map are greater than zero - - to match this means you than zero - - to match this means you than zero - - to match this means you have fulfilled one of the account you can also do to match - - this condition - ipoh - very good now how do we shrink - ipoh - very good now how do we shrink - ipoh - very good now how do we shrink the window we will do the reverse of this instead of shrimp now we should shrink the left our two mesh will class equal to left greater than equal to 0 plus blast count of left and lastly let's see if it works now why is this greater or equal to let me ask you what does zero represent zero represents my current window has exactly the same count as what is desirable right for example if my window is this my window has a one what is desire is a one now if I shrink it I will have less than what is required so if you are zero your to match will increment by one what does a positive count MathML represent it means in the current window you have less than what is required so if you shrink that you have even one less than what is required again it gets pretty complicated so I'm gonna stop here let me submit and see what is correct so there we go
|
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
|
961 |
Ipu Hegar Horseman You I Hope For Doing Welcome To Jalan Khor So English Play List Will Have Complete Web Complete Yesterday Should Be Pretty Something Or ₹100 It Today Will Do Should Be Pretty Something Or ₹100 It Today Will Do Should Be Pretty Something Or ₹100 It Today Will Do And Repeated Element In Size Dresses Painting Is Your Nutrition P Like Subscribe And Comment And Humble Request to all hua singh this video please do a complete video and don't forget to like subscribe and comment hokar show specific btc course in this you can solve this discussion with in writing 300 will not want to take modifications but its first year and ubuntu forces Equations Were Not Going To Waste Not In This Manner In This World In This Two Minutes So What Is Given Question In Amazon To Drops And Subscribe To Ghaghare Element Android Andher Plus And Unique Place In This Issue Attacking Adjectives For This Vikram Thakur Suicide Vikram Thakur In 3D Ki Shobhan Many Naxalite Bandh Se Limited Repeated OK 100 Cities Of This One To Three Is Unique And Exactly One Month Of This Element Jupiter And Times So S One To Three Se Zameen Spanish Two Three Times In This 12345 6% Is Nuvve 3513 Times In This 12345 6% Is Nuvve 3513 Times In This 12345 6% Is Nuvve 3513 plz subscribe comment and subscribe the Video then subscribe to the Page if you liked The Video then Prithvi Are Going To You Have Happened This Very Fierce And So Let's Do List Ek Aisa Ghrit Map An Order Cancel Dictionary So Every Element As A Brilliant Is Like This unique shift I is not in Delhi dried effigy of media and subscribe mid-day counter element and nowhere in the mid-day hua hai the mid-day counter element and nowhere in the mid-day hua hai the snow dictionary app on a reply a north Indian a and sorry itna dictionary app hai or needle threads understanding minute Submitted then today I am Summit for education and action master handed over vendors pei 10 inches setting in life in shirt vansh vikram samvat 1212 subscribe - - - 99 999 9999 33333 unique and elements without hindrance-vighn not unique and elements without hindrance-vighn not unique and elements without hindrance-vighn not in miding element meeting morning Note of straight zigzac limit veeravansh feeding him and asked for a drink of speech and behavior in counting element with the wording counter sudesh dhawan sir because it only phone number cheating jobs in this video and don't forget subscribe my big guide please like us Two
|
N-Repeated Element in Size 2N Array
|
long-pressed-name
|
You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times.
| null |
Two Pointers,String
|
Easy
| null |
105 |
hello viewers of algorithm videos I'm Nick white I do technical stuff on Twitch in YouTube check the description you get all my stuff like and subscribe this so I can grow my thing I'm basically walking people through a code for algorithms data structures because they don't understand it they get it confused this is basically 105 construct binary tree from pre-order and inorder binary tree from pre-order and inorder binary tree from pre-order and inorder traversal if you don't know what a tree is you're not gonna be able to do this but a tree is just a data structure binary tree is a tree where the nodes tree nodes are like this they have a value they have a left and right child so a node has a value like 3 then it has a left child with a value a right child with the value even 9 has a left and right child they're just set to null ok so we can construct a tree based on information you know like this like we get a pre-order array of values and an get a pre-order array of values and an get a pre-order array of values and an inorder array of values we can construct a binary tree using these values because we can figure out the structure of a truth now pre-order and inorder are truth now pre-order and inorder are truth now pre-order and inorder are types of traversals there's also post order and this represents you know what order the route is traversed right so pre-order the route is traversed free pre-order the route is traversed free pre-order the route is traversed free left and right so it's there's route left and right those are the three notes right now in a sub tree or tree root left right ok what order is the revert the route traversed pre-order its traversed first traversed pre-order its traversed first traversed pre-order its traversed first so pre route left right in order it would be left route right post order it would be left right route so it's whatever order the route is traversed now with this data we can kind of build this so first thing we're gonna do a helper method we're gonna need a helper method to actually build the tree doing this and what we'll notice is pre-order is route left right notice is pre-order is route left right notice is pre-order is route left right so we already know what the root node is it's gonna be 3 because the first node Prix in pre-order route is 3 you know Prix in pre-order route is 3 you know Prix in pre-order route is 3 you know that's just by definition right so but we're gonna return the root to the tree we construct from our helper method we're gonna take in where the pre-order we're gonna take in where the pre-order we're gonna take in where the pre-order traversal where the pre-order boundary traversal where the pre-order boundary traversal where the pre-order boundary we're gonna keep an index to find where the route is that we want and we're gonna use this pre-start as an we're gonna use this pre-start as an we're gonna use this pre-start as an index of the root node at each recursive call we're also gonna keep boundaries on you know our inorder array because this is how we're gonna construct in traverse on the left and right side so we're gonna keep an in start and in end boundary okay and then we're gonna also just pass in the pre-order and inorder just pass in the pre-order and inorder just pass in the pre-order and inorder arrays again pre-order in-order and arrays again pre-order in-order and arrays again pre-order in-order and these are in two rays so you gotta make sure you include the types you're gonna have errors that are annoying like okay there we go so here's the method we're gonna just call this method with our initial data right so pre start is where we're the index where we're gonna get the current root node at so that's just going to be 0 right the first root node is 3 that's an index 0 the boundaries right now for the end start and in end these are the boundaries of the inorder array that we're going to be looking at for each node this is just going to be 0 2 in order LAN minus 1 so like the whole array basically and we're just gonna pass in the basic pre-order in-order you pass in the basic pre-order in-order you pass in the basic pre-order in-order you know arrays right and we're gonna be returning what we get back from this method because this is gonna return the route to the tree so you know we're gonna check these boundaries each time to make sure that they're not wrong so first boundary we're gonna check is pre-start greater than is check is pre-start greater than is check is pre-start greater than is the index that we're gonna get the route from greater than the possible indexes from preorder length minus 1 well if so that's you know that's not good so we're gonna return null also if in start is greater than in end that's not good either so we're just gonna return all these are you know incorrect here ok we're gonna return route right so we're gonna return roots which will build the first root is going to be the first node and pre-order to be the first node and pre-order to be the first node and pre-order that's just by definition root then left right so you can see 3 9 23 920 left right that's pre-order definition left right that's pre-order definition left right that's pre-order definition root is the first node in pre-order root is the first node in pre-order root is the first node in pre-order array so we're just going to build our tree node so we do it with a constructor would you say root is equal to new tree node and we pass in that index that we want to pull from so pre-order of want to pull from so pre-order of want to pull from so pre-order of pre-start so pre-start is 0 pre-order is pre-start so pre-start is 0 pre-order is pre-start so pre-start is 0 pre-order is this array so index 0 is that 3 so we make a root with node 3 we're gonna be returning root 3 but before we return root 3 we have to set the left and right nodes right now how are we gonna do that well we want to find what we want to do is we want to find where the root node is in the inorder array so that we can figure out what's gonna be on the left side and what's gonna be on the right because in order is left root right so you know that whatever is on the left of the root is gonna be on the left side whatever is on the right is gonna be on the right side so we just do we're just going to make an index we're gonna make a variable called in index and we're gonna loop through I equals in start from in start to I less than in n so the in order boundaries we're going to loop through and we're gonna say if root Val if our root value is equal to in order of I we found the index of the root in the in order race we could set that in index will be equal to I great now once we find that index in the inorder array we can now set our left and right notes right so root dot left will be equal to helper and the boundaries for the inorder array will be from in start on the left side it's almost like a binary search but not really because it's not a binary search tree it's not by choice but like how you're splitting it up to left and right side so the boundary is gonna be from the 0 from in start to the index minus one so it's gonna be from the beginning to where we found the root minus one that's what's gonna be on the left we do have to the pre-start the left we do have to the pre-start the left we do have to the pre-start variable is just gonna be plus one to get to the left because pre-order is get to the left because pre-order is get to the left because pre-order is root then left then right so it's root then left so it's just pre-start plus one so that's the index pre-start plus one so that's the index pre-start plus one so that's the index for the left side of the tree so three dot left is just gonna be you know we're gonna access the root node is gonna be 9 because pre-start plus one you know it's because pre-start plus one you know it's because pre-start plus one you know it's just gonna be the index plus one is just gonna be one and then you get you know new tree node of 9 now the SOT the boundaries for the inorder array are going to be in start to in index minus one and then you're just going to pass in pre-order and you're just gonna pass in pre-order and you're just gonna pass in pre-order and you're just gonna pass them the same pre-order and inorder race them the same pre-order and inorder race them the same pre-order and inorder race okay great now what you're gonna do on the right side is a little bit different and there's an explanation for this you're gonna do for the in the inorder boundaries make sense you're gonna do from in index plus one to in end so just the right side of where you found the root in the inorder array right because that's gonna be the stuff on the right side that makes perfect sense so from in and X plus 1/2 in end sense so from in and X plus 1/2 in end sense so from in and X plus 1/2 in end you know that's the it brown juice now the where you find the right node the right child root in the pre-order array is gonna be the pre-order array is gonna be the pre-order array is gonna be determined based on this it's gonna be determined based on pre start plus in index minus in start plus one and we do this because there are left sub-tree this because there are left sub-tree this because there are left sub-tree sometimes not in this example but there are left sub trees and those like oh no there are in this example the left sub trees will be traversed first before we ever access the right nodes it'll actually traverse the left sub trees first in an inorder traversal that's how it works by default the right are the very last things to look at so you want to skip those left sub trees by looking at in - in start + 1 because this is the stuff - in start + 1 because this is the stuff - in start + 1 because this is the stuff that is on the left side so all the stuff on the left side and the in order array it's not really clear in this example but all of the stuff on the left side in the in order array could be left sub trees and stuff so you skip that boundary so you plus this boundary of all that junk you want to skip and then you add one instead of you know you would have liked to just do add two but it's not that easy you have to skip all this stuff cuz in order traversal isn't like you know it's a little more complicated than you think it's not just laughter root right xx you actually do these you have these left sub trees that you traverse before the rights ever get hit looking at reversals and you'll understand this a little more this is basically the solution hopefully what is happening expected something int n end sorry we didn't do a type hopefully pray still wrong what is wrong now memory limit exceeded oh gosh guys in the index minus 1 I just had this error so I can I got right root out right oh my gosh guys sorry again less than or equal oh my gosh okay this is bad alright I'm not redoing the video there we go okay that's the solution sorry then I had so many errors okay but what I'm saying is you have to look at this is the hardest part to understand about this problem the rest is pretty straightforward right it's free you split the in order you know what's on the left side in the in order the right side in the end order you keep the boundaries you get the pre-start the boundaries you get the pre-start the boundaries you get the pre-start where it needs to be every time the just understanding where this index come from this part they this person explains it here if I didn't do it clearly enough you can go to this part in the you know the first one in the discussion and the most voted you just look this person explains right here it gives all of the reasons like we're member preorder traversal always goes on the left will visit the left branch before the right ever gets hit therefore we can get the immediate right trial by skipping all of the sub-trees the left skipping all of the sub-trees the left skipping all of the sub-trees the left branch sub branches so we can do this by looking at the in order and getting rid of all the stuff on the left and it gives you the formula and everything so there you go that's pretty much it thank guys for watching please like and subscribe so that you know the channel grows and I think that's watching I'll see you in the next video that's it alright see ya later peace
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
560 |
hey everyone welcome back and let's write some more neat code today so today let's solve sub array sum equals k so simply we are given an array of integers nums and we are given a target integer k and we want to return the total number of contiguous subarrays which sum up to the value k this is our target value so how many continuous sub arrays sum up to two well we have one sub array with the first two elements and then we have a second sub-array with the last two elements sub-array with the last two elements sub-array with the last two elements that's two how many different sub-arrays that's two how many different sub-arrays that's two how many different sub-arrays sum up to target value three well we have one sub-array from the beginning have one sub-array from the beginning have one sub-array from the beginning and then we have another sub-array at and then we have another sub-array at and then we have another sub-array at the end now let's think about the brute force approach first that's to be n squared why is it going to be n squared because we have n squared different subarrays inside of the array so if we just check every single sub ray right we start here is this uh sum up to the target k nope okay does this sum up to the target k yes it does then we check the entire thing does this sum up to the target k nope it doesn't and then we can start over here does this sum up to the target nope does this sum up to the target yes and then we can go here does this sum up to the target no it does not and then we're done right so we checked every single subarray that's n squared time and then your next thought might be okay n squared maybe we can improve that maybe we can use two pointers maybe we can even do a sliding window so for example this is our first subarray right it's too small so we add values this is our next subreddit it's the perfect size this is our next sub array and this is too big so what would we want to do then well maybe we could try you know taking the left part and moving it right moving our left pointer here because we want to decrease the size or the total sum of the window after you read the constraints you'll know that's not possible the reason why is because the values in nums could be negative so just by adding a value to our sub rate like adding another value doesn't guarantee we're increasing the size and removing a value doesn't guarantee that we're decreasing the size because some of the values could be negative now it still is possible to improve the brute force solution into an a linear time solution and it's not super intuitive but you can use the brute force solution as some intuition to get to the better solution so that's kind of what i'm going to try to explain and then once you know it the code is actually pretty easy to write so let's kind of go through that intuition now so yes we are going to be using a hashmap in this problem where the key value is going to be the prefix sum and the value of the hashmap is going to be the count of how many times that particular prefix sum occurs but let me actually run through why that's going to work for us so we see that the target value is k so let's try out the brute force approach so we're going to first start at this subarray right just one value or sum so far is one then we're gonna do the first two values the sum so far is two then we're going to add a third value now the sum so far is three right so we found one sub-array right we can kind of keep one sub-array right we can kind of keep one sub-array right we can kind of keep track of that we have one sub-array so track of that we have one sub-array so track of that we have one sub-array so far next we are going to go to this part then the fourth element right now our sum is four and of course we're going to do the same thing for the remainder right this is going to be 5 this is going to be 6 etc but let's just notice a tiny bit of repeated work we're doing next i'm going to start over here at the second element right brute force it from here so far we have one now we have two we added a third a second element and now we added a third element so yes now we reach the target right this is some k so we can add another one to our total the number of subarrays we found with k right the first one was these three elements the next one is these three elements but notice how we computed this entire sum right when we're computing these three values we're basically doing a ton of repeated work that we just did right so how could we have gotten this three sum a little bit quicker right these three values summed together a little bit quicker well when we were over here right when we had iterated through these first four elements we could have just said okay take the entire sum minus the first prefix right just the first value minus that would have given us three right but if we're trying to compute every single subarray right because we know the next go-around right because we know the next go-around right because we know the next go-around when we iterate through the loop we're going to be starting at this value right and then eventually we're going to get to a sub-array like we're going to get to a sub-array like we're going to get to a sub-array like this so when we were going through it the first time with this blue portion we could have gotten this pretty easily as well we could have just taken the entire sum minus the first two values which is a prefix of the array right but that's also brute force right we're not doing anything better all we're doing is still creating every single subarray so is there some intuition we can use can we somehow be a little bit greedier notice how when we've gotten this subarray our sum so far is equal to 4 right so what we're looking for in other words is can we chop off some prefix of this array of this entire array can we chop off a prefix such that we can make this sum match k the answer is yes because we can calculate it right our sum is four so let's get some minus k which is going to be four minus three which is one right so we know that so far the entire sum is four if we can chop off a prefix of one we will still have a contiguous subarray right that will exactly match k now the only question is does there exist a prefix in this subarray right not in the entire array does there exist a prefix in this portion starting at the beginning that we can remove because remember we want a contiguous subarray can we chop off a prefix that has an exact value of one well we can if we maintain a count of it right if we if every time we compute a prefix if we add it to our hash map and count how many prefixes have a value of one and the reason we're counting is because remember since we could have possibly negative values like this could have been a negative one there could be multiple prefixes that have a prefix of one because you know this is one prefix that sums up to one this is another prefix that sums up to one right because we have a negative one in the middle so that's why we have to count the numbers but also one thing we can't just go on and compute every prefix before we actually start building up our result we have to do it simultaneously right because if we just compute every single prefix then when we get you know when we're at this point right we're trying to get okay how many prefixes have just a sum of one well if we have gotten every single prefix already then that'll have been added to our hashmap we might end up removing a prefix like this right we can't do that we're not allowed to do that when we're at this portion we only want to remove prefixes that are a subarray of this right and of course we don't want to remove the entire array because it's possible our k value could actually be zero in which case we don't want every you know we don't want to take this and say okay remove the entire thing that sums up to zero and there's one last edge case we have to worry about so let's say our k is three right once we've gotten to this point we our sum is three right so we're going to take 3 minus 3 which is equal to 0 right at this point we don't have any prefixes with a sum of 0. so what we're going to say is okay since no prefix has a sum of 0 right then we're not going to end up updating our result but we don't want to do that so as a base case what we're going to say is to our prefix sum we're going to add a zero value and say that the count is one basically we're saying there is a prefix you know the empty prefix that has a sum of zero so now let me walk you through the algorithm it's going to be a linear time algorithm i'm going to change this to a negative one just to make the problem a little bit more interesting so we're going to start at the beginning add every single value that we can to our array on each iteration add that to the sum and every time we compute a prefix after we are done updating our result potentially that's when we're going to go ahead and add that prefix to the prefix map so we start at the first value we get a sum of one minus three is negative two does negative two exist in our prefix map nope it does not so we continue but before we continue we're gonna take this prefix that we just computed one and add it to our prefix map so prefix of one has a count of one so far next we are going to get the next value so now we have a sum of zero minus three is negative three do we have a negative three in our prefix map that we can potentially remove from this array that would give us the total sum of the array as being the target nope we do not so we continue but before we continue we see okay we computed a prefix of sum zero so let's increment the count of prefix of sum zero so this is now going to be a two and now we're going to add the third element to our sum so now we're gonna have a sum of positive one so we're gonna take one minus the k value three negative two does a negative two exists in our prefix map nope it does not but we can say that okay we computed a sum of one again right so now we can take the sum the prefix sum of one and say that there's two different prefixes this one and this one that sum up to one and we're just going to continue so at the next iteration now we have a sum of two minus k is going to be negative one do we have a negative one in our prefix not just yet so let's continue and now we add the fifth element so now we have a sum of three right so we're gonna take three minus k which is also three right and we're gonna get zero do we have a prefix sum of zero finally we do so what are we going to do we're going to take the count the number of prefixes that we had that summed to zero and say okay there's two different ways that we can create a subarray of k so we're going to take our result which is initially zero increment it by two but hold on what did we just do let's think about it for a second we said okay the entire sum of this subarray is equal to three and we said okay three minus k is zero that means we need to remove a zero sum sub array from this subarray to get us to the target value right so one sub array is okay if we remove you know an empty subarray right why does that work because take a look this is a subarray that sums up to three right that's the obvious one so that's where our two comes from right so far we have one of the two ways but let's continue there's another subarray this subarray right that has a sum of zero so if we remove this subarray from our you know original sub array then we're removing zero from the sub array so this sum stays as zero so this is the second subarray that sums up to three that we have found that ends at this position so great so our result so far is two and don't forget this subarray had a sum of three so let's say one prefix has a sum of three so far and next we're finally at the last iteration of the loop so now our sum is four minus k which is three is going to be positive one so how many prefix sums do we have with sum of positive one we have two so that means we're going to add two to our result because what we're saying is ending at this position how many sub-rays could we get that sum how many sub-rays could we get that sum how many sub-rays could we get that sum up to three well we because the total sum of this is four and we know that we have two prefix sums that start here that sum up to one we can remove two different prefixes that will make this equal to three we can remove this prefix right that's one prefix that sums up to one and then when you look at this is this sums up to the target three we can move remove another prefix sum remember this also sums up to one if we remove this then we also have a pre we also have a sub array that sums up to three so we have two different sub arrays that end at this position that sum up to the target three and once we've done that we've iterated through the entire array once we're done right we did an exhaustive approach so we ended up getting a result of four there's four different subarrays in this entire thing that can sum up to three obviously it's a linear time solution as well as linear memory because we're using this hash map but that being said now we can jump into the code and the code is pretty easy once you can figure this out so we are going to have a result variable which initially is going to be 0 we're also going to maintain the current sum which is initially going to be 0 as well and we're also going to have a hash map let's call it prefix sums and it's not gonna initially be empty remember we have a base case of zero uh we have a single prefix sum that sums up to zero so that's what we're gonna say like you know the empty subarray and then we're going to go through every single value in the input array add it to the current sum right we want to know what the current sum is and then we want to know what's the difference that we're looking for the difference is current sum minus k because we know if we can remove a prefix sum of size diff then we can find a potential result and we could have multiple prefix sums that sum up to diff so we want to take that and add it to the result so we're going to say result dot add to it whatever prefix dot get sum up to diff now it's possible that this diff does not exist in prefix sums and in python you can return a default value of 0 if this diff does not exist in prefix sums and then after we do that's when we want to add to prefix sums the current sum that we just computed so prefix sums at position diff or the key value diff we want to say 1 plus whatever it already is so let's copy and paste this oh and by it's actually not diff we're computing the current sum right that's what our prefix sum is right now current sum and this also can be changed to current sum so with this line all we're doing is just incrementing the number of prefix sums that have this particular sum value and believe it or not this is the entire solution right we only have to iterate through the entire array once maintaining some hash map and as you can see the solution is pretty efficient so i hope that this was helpful it's not a very easy problem even though the code is pretty short and easy but 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
|
Subarray Sum Equals K
|
subarray-sum-equals-k
|
Given an array of integers `nums` and an integer `k`, return _the total number of subarrays whose sum equals to_ `k`.
A subarray is a contiguous **non-empty** sequence of elements within an array.
**Example 1:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 2
**Example 2:**
**Input:** nums = \[1,2,3\], k = 3
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-1000 <= nums[i] <= 1000`
* `-107 <= k <= 107`
|
Will Brute force work here? Try to optimize it. Can we optimize it by using some extra space? What about storing sum frequencies in a hash table? Will it be useful? sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1.
Can we use this property to optimize it.
|
Array,Hash Table,Prefix Sum
|
Medium
|
1,523,713,724,1016,1776,2211,2369
|
1,492 |
Hello Hi Everyone Welcome To My Channel It's All The Problem Wicket Factor Of And Give Into Positive Interest And K Factor Of Sciences And Models i20 Straightforward List Of All Factors Sorted In Ascending Order Return For - 110 Edison's Return For - 110 Edison's Return For - 110 Edison's Factors Which Are Very Straightforward Problems What we do we need to start from check the number of units mention more will start from subscribe 303 third factor off do that similarly for 70 specter is dynasty tax inspector is unknown flying seven four this is the first Ronit mode switch off subscribe minus One very straightforward like and comment for start from one inter cast oil garlic and plus and will check the first week after mid of subscribe and subscribe the Channel subscribe 4 Quin 371 Light System Kasam Taxes and Tribes in It's All Subscribe to Om Shanti Sat States At That Time Company History Of The Solution Middling Till Death Swiss Open And Space Complexities Which Candy Father Optimize Solution So Let's Understand Who Have An Nm Device Factor Of Nitin22 Factor Of Mouni Roy In This Period Envelope Is Three Layer Pendant Three Layer Subscribe Must Different Rudolph you will find all from here meeting with one and will go like routine and from here will get dressed in the life in the year will defiantly what we will do first number syphilis k using code just need to change the condition that will check current Affairs Quiz on a browser first he will return the is not a fact otherwise what we will do for sacrifice to check weather and why is this factor of measure not what we will start from root will decrease every time we wake up side towards in this Will Return Android Hawaii Second Trying To Find All Dirt From 100 To 120 10-10-10 Here's In First Look To 120 10-10-10 Here's In First Look To 120 10-10-10 Here's In First Look After A Year After Starting From To Like This So Hans Know Who Will Check Is That And Why Is Factor Of Fire Green In Instead of doing is written and why is west is the solution for black triad to compile scored a swing and sorry I need to change his condition which starts from root in which is like root of and you will go is still greater root of and you will go is still greater root of and you will go is still greater noida west In the left side subscribe button is there Nitish Expected solution NCR running to for roof fruit and so its overall and fruit and the time complexity of dissolution is mock root in which square root of display light solution subscribe To My Channel thanks for watching
|
The kth Factor of n
|
time-needed-to-inform-all-employees
|
You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12, k = 3
**Output:** 3
**Explanation:** Factors list is \[1, 2, 3, 4, 6, 12\], the 3rd factor is 3.
**Example 2:**
**Input:** n = 7, k = 2
**Output:** 7
**Explanation:** Factors list is \[1, 7\], the 2nd factor is 7.
**Example 3:**
**Input:** n = 4, k = 4
**Output:** -1
**Explanation:** Factors list is \[1, 2, 4\], there is only 3 factors. We should return -1.
**Constraints:**
* `1 <= k <= n <= 1000`
**Follow up:**
Could you solve this problem in less than O(n) complexity?
|
The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed.
|
Tree,Depth-First Search,Breadth-First Search
|
Medium
|
104,124
|
19 |
yeah what is up there's a being on here today I'm going over Amazon asked question I think Facebook acid as well so remove Ed's note for any of this medium problem and leak code there scription reads given a link place moved and snowed from the end of list and return its head so they just give us a linked list we want us to remove the second node from the end so they want us to move forward we returned the updated linked list with the four removed and that's it so I drill have two examples on my iPad I'm sorry it's a little bit small but so the first thing we're gonna want to do is create a dummy node that goes before the first node I'm gonna show you guys why we need that in this example after we're going to use two pointers so we're gonna put both pointers at the dummy node so first in a second and this is the head we want to create a pointer to reference the head so we can return that later so dummy dot next it's going to be set to head and the intuition behind this well first n equals two so if they want us to remove the six the second node from the end of the list is gonna be six we want to get a pointer to this one so we can just do pointer down x equals pointer next so how did we get a pointer to the node right behind the second from the end one can't just move it to because I'll get here but if we move one pointer n plus 1 nodes so three so we move the first one here three times there and second stays the same and then in the second loop if we move it until it reaches null so we're going to move it one two three four five so five it's five away from the second happens to be one two three four five away from null or not away from though from the note that we want to remove so we just do that we move them at the same time until first equals no so we move the second one and the second is here and now we just do second dot next equal a second time next step next so sorry getting all these notifications the reason we need dummy is we if we do first here N equals one they want us to remove the first node you know second if we move first n plus one it's here we just do second dot next that equals second time next we can't do that it's not gonna work we need to put a dummy here so when let me redraw this dummy dot next is still the head and we move N equals one so we move the first one to well first is already no seconds already here so we just do a second dot next you go second dot next and then we return dummy dot next that's why we need the dummy we could actually not use the dummy in this example here and it would work but it wouldn't work for a linked list with one node so that's like an edge case that we're gonna check for so now let's just code it out so let's create the dummy node give it a value of zero get my iPad out of the way in dummied next is gonna be set to head we're going to return this at the end it's pointing to the head basically and we're gonna create the first and second pointers so I remember we set them equal to dummy because we want them before the linked list in case they give us something to us with one node second equals dummy and we're gonna have a for loop so this is where we're gonna move the first node or the first pointer I'm sorry at the first corner so why is less than n plus 1 D plus 1 comes from the dummy node that we created we have to account for that I plus let's just loop through and we're doing first we're just moving first along the list and then we're gonna have a while loop so we remember we wanted to get the first node or the first pointer equal to null and we're gonna move first in second at the same time and then if where we have second it right before do you know that we want to remove so we're just going to set second done X equal to the node right after and I open a new tab for some reason so second time next that next we'll remove the node from the list and then lastly let's just return dummy dot next because it's still pointing to the head so we return the head of the list well you know I tried shooting this video like four times already but OBS does not work on my 5k screen so I had to switch to my laptop and there you have it 100% laptop and there you have it 100% laptop and there you have it 100% oh then runtime just good we're moving through the link fist constant space complexity because we're not creating it in your data structures if you guys have any questions please don't hesitate to ask if you guys have any criticisms I'm open to those as well you guys want me to do any problems I will just let you know in the comments and I will respond to you thanks for watching
|
Remove Nth Node From End of List
|
remove-nth-node-from-end-of-list
|
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[1,2\], n = 1
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is `sz`.
* `1 <= sz <= 30`
* `0 <= Node.val <= 100`
* `1 <= n <= sz`
**Follow up:** Could you do this in one pass?
|
Maintain two pointers and update one with a delay of n steps.
|
Linked List,Two Pointers
|
Medium
|
528,1618,2216
|
1,027 |
And friend, today's question is very important for you. Interview and today's question is a very good question but it comes in the category of hard question. If you look at Expert Vijay, then what is an expert in gaming, what to do in this? We are given a number and we have to find out the length of the longest subscribers. In this way, we have to find out how many longest numbers we can make in this. If we talk a little about the question, how do we solve it? Wherever clove gas is the largest then what do we have to do, understand the parent question for the group force that we have three, six, if we try to put milk in it, whenever we can make it, that There is a part of a sub-sequence, it part of a sub-sequence, it part of a sub-sequence, it will increase to do a part of the sub-sequence, we will read that we have two it will increase to do a part of the sub-sequence, we will read that we have two it will increase to do a part of the sub-sequence, we will read that we have two it treated, one and one in a way, it will not be less, if we give that brother is three or three is alone, power is there, otherwise we have to take our two variables. Due to which we will have to decide, we have moved forward whatever is there, see what is there, 9 - 3 - 3 - 3 - 3 So in this manner, now in this manner, we have moved our tractor forward with the X - 3 element, so you can also move We have put this loop, after applying the rough, I have created my own here, the answer is maximum, this is on our index, I friends will see together, we have this, which is ours, now what is ours comes less, which is what we have created our function. Idea then what did we create? Now first of all our idea comes in it so what to do and if we made this house ours then become India, give it now what will we put here then what will we do One Plus How to improve your thinking level Let us do that in this. Now let us talk about what we can do in this. Now we will have to do this in this. First of all, we will solve this by memorization from D.P. First of all, we will solve this by memorization from D.P. After all, what will we have to do, we will have to make BPL, what will we have to do in DPR. We will have to score, first of all, who is the DP? How are we going to maintain our DPR? If we look at it, what do we have in it? We have the particular index and we are checking how much is his account. So what does it mean that the particular index is on payment? Coming to date and history index So what do we have to create for this We have to create for this So this is my solution for this we have to make our own Let Now what will we do Now here we do n't have to do anything here That's it From here the understanding is that I do whatever it is, I comment and I enter it and the password will do the Kirtan as if it is ours, here we have put Deepika, we have made this and Deepika, we have made that and after making it, now in this We will talk about it, whatever it is, brother, I am copying it from here, we have copied our milk from the solution here and here we also need it, I think for DP and for this, if we watch this video carefully, it is important. Our account is fine So for this we have to see And after that we asked what is the problem is that we have put sleep from I to N. Now what are we doing where our zero is the one. Initial starting He is taking us to where He is taking us to where He is taking us to where we have come, how far behind him are we becoming friends, see this has been solved and with this our daily challenge to him gets solved then you solve yours.
|
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,611 |
hello hi guys good morning welcome back to the new video in this video minimum one bit operations to make integers zero firstly it's a hard problem but the only way to think of these problem is to break it down to the smaller problems but it is easy to say that we can break it down but to know how and when and what to break down is the most important part so you will see many videos on YouTube people will be explaining this question but firstly they will not teach you in flow and secondly they will not let you know that when to break down and what's the intuition behind breaking down what so let's see that same specific thing again it's a hard question so yeah let's go um so it just says and again it has been asked by Oracle McKenzie in the last 6 months you see Oracle has asked quite a lot on McKenzie and in one year VM Expedia cool let's go on uh it just says that minimum one bit operations to make inte zero it's very straightforward that we are having an integer n and you must trans transformed into a zero so basically we will have an integer n and we have to transform that to integer zero so you can just imagine the number n in the binary form which means one 1 0 something like that and then ultimately make every bit as zero now why I transform this so much into bit because it is saying that the operation you can perform it itself is on the binary representation so what we will do is we will transform this end to the binary representation and I did not think of myself I just said question is s want you to convert that number to a binary form and then apply Transformations on that number so the First Transformation which you can apply is change the rightmost bit as you can see the rightmost bit of a number is just the bit on the extreme end if I write any binary number so the extreme end number is the rightmost bit so I can just transform this which means I can just if it is a one I can make it a zero if it would have been a zero I can make it a one remember I'm not saying unset or set I'm saying just change which means 1 to 0 and 0 to one that every word I'm saying every word I mention will be helpful in choosing what we do and what we aim to go forward cool that is the first operation second operation is change the ith bit in the binary representation of n if the IUS oneth bit is set to one and all the other bits are actually zero it's just ultimately trying to say I can only if I have a pattern like this in which my I bit is one I minus i- 1th bit is one and the one I minus i- 1th bit is one and the one I minus i- 1th bit is one and the remaining bit which means IUS 2th bit to the zeroth bit is actually zero only then again only then I can make my this I bit changed and make it to a zero again it's a word as change now I have to return the minimum number of operations to transform into to zero we will have a quick check on the examples and then we will just start off very imaginary and intuitively on how to break down again it's a very hard so we cannot just directly say that okay random number because you can end up in multiple possibilities because in these cases what end up happening is you end up happening with a multiple cases of multiple possibilities but we will not go in that way we will see that how we will go so uh we will have the number n as three we can represent the number as binary form which is 1 one now First Option or second option which option to choose again in the example itself let's think which option we will choose sh if I try to choose the option number one then I will replace this one to a 1 zero right but then to replace this I ultimately also need to make a one again so it's a flow point so what I will do is I will first and I want minimum number of operations so what I'll do I'll firstly make this a zero by using operation two okay this has become a zero and ultimately by using operation one I can make the last b as zero so operations required are two for example in the question number six again I have one Z again option two I can directly see it is happening so I'll just directly use option two to actually make this bit as zero okay it has become a zero now the number remaining is one Z again uh for one Z I want to apply any of the operations operation two I cannot see is being applied so what I'll do is I'll for short apply operation one because operation two I cannot see being applied here so I apply have to apply operation two I'll apply the operation two and it will become a one now with one now I can apply the operation two so I applied operation one and make it as a 1 one now I apply operation two and make it as a 01 and then I apply and then ultimately 0 so that's example uh which is kind of okay we know that okay when we can apply operation we will apply that operation else we will not but that is not much useful so what we will do is we will start off with an imaginary number let's imagine any number like in this case I just took any imag number again you will see that in mid you have a one it is not directly it is neither directly you can apply option one neither you can like neither you can apply directly option two so it's both ways no one can be applied here so that's the we just took it but looking on back to your two Transformations which you can do is the First Transformation just said that you can only change the last bit so the First Transformation can only change the last bit I cannot change the other bits because of the First Transformation but because of the second transformation I can change any bit so this is for any other bit I should be changing now you will say uh any other bit but what if it is not even transformable we will go into it but you will see that to change any other bit I will have to apply operation two so why not let's start with seeing that how operation two we can leverage because to apply transformation on last bit it is Operation one for sure but to apply operation on any other bit we will for sure use operation two so let's leverage operation two and see how we can actually use operation two it two itself so for sure operation two just says one thing that again how we reached because we can only leverage operation two so let's take operation two in our hands and see that how we can leverage operation two to reach to our final answer so operation two says that if you have something like ith bit IUS one bit both are set and all the bits are zero then you will need just one operation to transform this number to a 0 1 0 which means you will just make this number as a zero that's great but ultimately your aim was something else right your aim ultimately was transforming this number 1 0 to a final 0 again please remember the count right because it will be helpful for you to actually imagine in the binary form now multimate a was to make a 0 but I not reached that I just have used one operation what about this number itself I will ultimately have to reach to a 0 right so manually again it's a problem where you have to figure out the case so manually check how you can reach to a 0 again it will not be a case where you will okay yeah my entire uh hard work has gone to waste it will not happen it will be very useful now what we will do is we will try to manually reach because see this portion has already become a zero now my main aim is to become to make one 0 as the 0 so I'll manually write down and transform this of 1 0 to a z 1 0 apply operation one make it as a one okay now apply operation two on this bit because you need you see this is a one and I can apply I can change this bit and make it a I use operation two and transform this to a one now I'll use operation one and transform this to a zero again I'll use operation Operation again I use operation two and transform this bit to a zero so I got this bit as a zero again I need to apply some operation but I cannot see anything so I apply operation one and transform this bit to a one that's good now I simply have apply operation two on this bit and transform this to a zero lastly I apply operation one and transform this bit to a zero so you will see that you obtained again right now I just showed you again this will be very useful I will copy paste the same stuff later on also for other further observations but you saw that how we flow in like how we flowed in but now you'll see that okay you just got this transformation now if I just ask you reached from 1 0 to 00 right is was it possible to reach from 00 to 1 0 like just look at it just look at the images like I just have gone from 1 0 to 00 the same way I can go backwards I can just replace this again that's the reason in the beginning I said it's a change right so I can just change this bit make it a one I can change this bit make it a one apply operation one make it a one apply operation two make it a one again apply operation one make it a zero so there's a change I was doing so for sure if I can go for forward I can also go backwards It ultimately means from 0 I can also go to a 1 0 but Arin why is this helpful you will see you will go one step above but yeah right now so you have seen that how we reach to conclusion that for sure if I can go from A to B then with the above operation of change I can go from B to a also so that is for sure and you will see that operation requir let's say here are X so here also required will be X itself because it's just a backward Arrow which I have just applied same now why was this useful this was useful because here we took as a 1 0 and we transformed it to a 1 0 and then transformed that number to a 0 00 0 ultimately so you will see that 0 ultimately you will see that here I use x operations so if I just go one step above One Step Above This so if I had a one 0 and then I can transform this I know that if I have something as 1 0 and then if I want to transform it to a 0 00 0 then I need X operations to transform 1 0 to 00 0 I need X operations to transform 0 to 1 0 I need again X operations so I know if I just go one step above it then I will have 1 0 so I know to transform 00 0 to 1 0 I need X operations because it is same don't transform it I need X operations and for sure to transform this part from I'll use Simple operation one which is just one operation so that's good and to transform my 1 0 to 00 0 I again need X operations so you saw one thing that how ultimately you were able to if you have a bigger picture you were able to reduce to a smaller picture just by using your this reverse pattern concept that if you had your I bit as set then you were able to bring it down to IUS one and then you were able to bring it down to 0 so ultimately the same thing I showed here that if your I bit is set I bit I'm not saying what about the other bits but right now I consider an example where just the I bit is set and rest all bits are zero then you can just use x operations to reach to a place where actually you transform that number to a pattern which can be transformed using a operation two which means you have some big number where you imagined it has 1 0 which means I bit is set and remaining all the bits are zero you transformed using X operations to a number which can then be transformed using operation two in one step that's the reason I just went one step above of it so as from a number how from a number I can transform using some op operations I want a number above it so that I can transform it to operation two now in why how you thought of it ultimately how I thought of it was because here you have this imaginary number ultimately you have to transform this imaginary number to your number right here so that you can just use apply so that you can just use operation two and apply operation two in it right and then when I apply operation two I reach to a number like this and then ultimately I also saw if I have a number like this I can transform this using X operations to a number as 0 so why not I can just say that I have something as 1 0 so I can just say 0 to 1 0 and 1 0 to 0 same X operations will be applied here so that is one thing which is kind of that okay how will I think of it but still it is with writing and finding a pattern out okay that is one thing which cleared our mind so now that's the hard part is just this part being cleared that's all it's the hard part that's the reason why this question is becoming like is this question is why this question is hard cool now when we have figured out a pattern uh that this is happening so we will just say that F of I is nothing but if I have IIT as set then I can use x operations reach to a number I use one operations to reach to 1 0 and then again I can use x operations to reach to a final 0 so I write the same thing as F of I = to 2 I write the same thing as F of I = to 2 I write the same thing as F of I = to 2 into this X x you will see it is nothing but 2 into F of I write and then plus one for this operation number two why and you will see that you initially had I at the bit and then you will you was at you were at IUS one at the bit it and the transformation also itself was on the IUS one bit here itself so you will see that X is nothing but IUS 1 bit I minus it is i- 1 but IUS 1 bit I minus it is i- 1 but IUS 1 bit I minus it is i- 1 bit and that IUS 1 bit as set and remaining all the bits as zero and then we did transformation and then we count it as As an X so you can easily see the formula which you have made right now is f ofx = 2 into F of i - 1 + 1 now where f ofx = 2 into F of i - 1 + 1 now where f ofx = 2 into F of i - 1 + 1 now where I says I bit is set I -1 I -1 B set so I says I bit is set I -1 I -1 B set so I says I bit is set I -1 I -1 B set so this is one thing which you have got now why was this useful we will see but it is kind of that we again further blow down the problem to just say that if I have one and all zeros like earlier I had only one pattern earlier I had a pattern okay all zeros and ear I had a pattern that whatsoever and last bit either is a zero or one I had OBS I had a pattern one now next I had a pattern where I have one and then all zeros then I have a pattern two which is observation two or the other the transformation two now I have one more pattern with me that if I have one and remaining all zeros then also I know that the operation required are what let's say here it is X so I also know this fact so now for this operations required were one for this x I just figed out one more formula for me out of the two formulas which were given for me now coming on back what was this formula uh simply if you had a one you know it's just one operation by using operation number one if you had one0 then for sure it's a f of 1 right which is 2 into F of 0 + 1 simple like using the like 0 + 1 simple like using the like 0 + 1 simple like using the like previous value so it will be three so you know for this value it's a three operations required for this 1 it's required will be operations which are seven so you know that with this kind of one into something which is all zeros like the number you can easily figure out so to convert that to a zero you know that now you will need X operations and that X you can easily find out by using this simple recursive formula now coming on back that was not the question for us my main question was any imaginary number convert that number to a x like convert that number to a 0 right now the same thing which I wrote above I'll write that same thing down up below that's the reason I said everything you dry run or basically check out uh while formulating of fig out a form figuring out a formula that will be useful for us so you saw that you transform 1 0 to a 0 you saw what happened in between you when you transformed your 1 0 to a 00 you encountered every number which is of three bits so you saw you count 0 1 2 3 4 5 6 and seven so while transforming you encountered every number so I just I'll just say the same thing that this is a parent of any number in between what I mean by that is if I have any imaginary number of let's say 1 2 3 4 5 I have any imaginary number of five bits so for sure when I will be doing a transformation from one which means one at the at this bit let's name it as a fourth bit so one at the fourth bit so they basically the number of bits are five so this the four like the left most bit will the fourth bit and the left and so and the rightmost will be the zeroth bit so I'm just saying that for the leftmost bit that is the parent of everyone while I would be transforming from that 1 00 0 while I will be transforming this number to a 0 00 0 for sure this number would be coming in between and this is how we prove this by using the above Dr which we saw so because we know that every number in between will for sure come while transforming to a 00 0 so I know that okay uh to transform this one 0 which means if I have five bits and the fourth bit is set I know that for sure the operations required will be F of four I represented my f of four with this zor of four so that you don't get confused it's just a power right so F of four but ultimately the answer is f of four so I represented okay we know this fact that to convert this 1 0 I need F of four as my obviously this Z or power of four let's name it as F of four so I need F of four I know this value for sure and I wanted to find from this one one0 1 0 imagine number two my 0 what should be operation required that is X that's known for me so ultimately if it's unnown I know this fact can I just find out the number of operations required to transform this one 1 0 to this 1 0 can I know this fact yeah that is what we can get to know how simple uh can we just see what is not there which means you see that this part this one is same okay this part is what I need to convert which means I need to convert this one is 0 1 0 to 0 again although I saying I need to convert this 0 to actually a 1 0 1 Z but we saw if I can convert A to B in X operation I can convert B to a also in X operation so that also is being used again so I know one thing that I will convert this one 1 0 to a 00 0 again the same concept I'll just find out the parent is simply if I have four bits the third most the third bit which is the left note leftmost bit it is set I simply say he's the parent and from this bit to the 0 operations required are F of three operations are required that we for sure know previously we just simply precomputed ultimately my aim was to reach from 1 0 this to a 0 operation required of Y which is still unknown so I'll just simply do I can simply find out this value which means from 1 0 2 1 0 again I just say how to figure out simple it is same I need to convert my 0 to a 1 0 again convert your 1 0 to a 0 now you'll see it's a simple parent only so that will require F of let's say the operation required are Z now this Z is nothing but F of one because it is at the first bit and that is a one kind of like one and all zeros kind of formula so I can simply apply my f of that formula which I already have found out so I just simply say that for this Z my answer is f of one right now for this y answer will be F of3 minus F of1 because you saw F of one was the answer for this which is the z was the answer right and Z is f of 1 so I know that Y is f of 3 minus Z which is actually F of 3 - F 3 minus Z which is actually F of 3 - F 3 minus Z which is actually F of 3 - F of 1 it is y now again I'll just simply replace this why I know X is f of 4 - Y replace this why I know X is f of 4 - Y replace this why I know X is f of 4 - Y and Y is f of 3 - F of2 and the same and Y is f of 3 - F of2 and the same and Y is f of 3 - F of2 and the same thing I'll write that it will be F of 4 - F of 3 + f F of 1 now if I simply know - F of 3 + f F of 1 now if I simply know - F of 3 + f F of 1 now if I simply know that okay it is my final answer F was nothing but what we find out 1 2 4 0 1 2 3 4 it is nothing but like for the for this value F of four is nothing but representing for this value for this particular value what was the value what is the f value for this now this will say it is 0 1 2 3 it will say I am zero it will say I am 01 so I know for this correspond ing values I can simply precompute the value in the beginning and I know that for odd places because my random number where my random number my imagin number was 1 0 I write the same number here 1 0 you'll see Zero 1 second third fourth bit for the first bit I am doing a plus sign for the next I'm doing a minus for the next I'm doing a plus simply keep on alternating your bits and keep on okay adding a plus sign for the first bit for the next minus for the next Plus and keep on going and you know that you have your n as less than equal to9 which is nothing but 31 bits sorry 32 bits in to sorry 31 bits in total so thus you can simply find your answer that is how again a quick recap on what we did again that was entirely nothing we assumed and that was entirely in the flow of the question we saw firstly we figured out that we have a imaginary number now this imaginary number we know that we have just two operations last bit and the other operation which will actually be impactful for other bits so just to figure out for this imaginary number we just went on and figured out that okay we can only use operation two as our main operation Operation two is as our main operation now for that main operation of operation 2 we just went on and checked in that how operation 2 Works operation 2 works as if I have a 1 0 then it will transform to a 0 1 0 now when this is done so ultimately my aim was to transform this a like transform this number 0 1 0 to a 00 so I just like manually from my pen write wrote the same thing down then while writing I also realized that reverse is also a true for this so with this I have got to know one thing in my mind that the reverse is also true but ultimately my main aim was to find out that how I can do it for my any imaginary number so ultimately I thought of let's maybe if we can able to figure out some relation for that I went on to its parent now its parent can be any number which I can use and find a relation to in this entire sequence so I went onto its parent was one 1 0 from this I can know that this portion is same because I have figured out the reverse is true so I can just say if I have transformed my 1 to a 00 that's also the same as 1 to a 0 and I can just simply place a one here because it is same bit it is the same bit so that would not count as a transformation so I know that it if it requires X it requires one operation Operation two and then it requires also X so with this I have found a relation for my simple concept when my I bit is set and remaining all the bits are zero I found a relation for this now this relation is a third operation which I can perform and but it's just that the cost will be now X for this which is the which I can simply find by using a recursive formula now when this portion is done ultimately I went back onto my imaginary number and try to transform this imaginary number to a 0 again but while I was doing this my by expanding my number I figured out that as it is a parent and it will while making my answer reach to zero it will reach onto every number so for sure if the parent was a 1 while reaching to a 00 it will have a mid number in between so for sure if the operations required here are X I can simply able to figure out this operation y and this I can again go and went down with this again coming back the values a simple mathematics and then we got the relation that it is nothing but odd even which means plus minus by just simply going okay if the first bit add its F value M like next bit like sub add F value and so on and so forth and with this your time is O of 31 because you will simply go on to 31 bits space is also o of 31 because for sure you will need f thing so let's quickly code this up that how we will code it and now as we saw that it can leg go to uh although it should not uh but let's for Simplicity let's take it as a long it uh so what we'll do is we'll firstly want to have a f value but you know that F value can go up to 31 bits like it will entirely have 31 bits uh from 0 to 30 so I'll just say for the zero bit as set right you know it's just operation number one which is this operation right here so that is just one operation required for the remaining other bits which means from 1 to um I is less than equal to 30 and I ++ now if you just say equal to 30 and I ++ now if you just say equal to 30 and I ++ now if you just say that see 2 ra^ 30 is actually like that see 2 ra^ 30 is actually like that see 2 ra^ 30 is actually like around one9 so that will actually work for us so that's the reason uh we just took it now again we just simply go on and say that F of I is nothing but 2 into F of i - 1 + 1 with this I have got into F of i - 1 + 1 with this I have got into F of i - 1 + 1 with this I have got the F of f value now my ultimately my aim was to find the answer so that I will simply do again I'll go on from the very end extreme end right I go on from the extreme end of my bit so I know that I have 31 bits uh starting from zero I'll go on to the last bit I'll just check if this current bit is set how we check it uh we just make a mask uh saying I uh one left shift I times uh that is a mask and I'll do and with n so this mask will become a uh 1 like at the ith location if that is something if this is something which means if this is if this value is something and not zero which means my ith bit was set only if my I bit is Set uh I will actually have to apply operation uh but here you saw that okay I need to maintain my odd even kind of count so I'll just simply as soon as I have got any bit set I'll just check the count and then I'll just have a quick check if that count is OD which means um I'll just simply add that value in my answer uh add that F value in my answer else if the count is even I'll just subtract that F value in my answer that is what my final formula looks like right so ultimately I'll just simply return my answer and with this you will simply be able to solve it cool and you will see the time is actually o of N and space is also actually so o of 31 and space Also of 31 because 31 here and 31 for the space I hope you guys got it the entire intuition that's the reason I SP it is very directional flow and also intuitive bye-bye
|
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 |
1,697 |
Hello gas, I am Lalit Aggarwal. Dose on welcome discussion, I have understood the problem very well, the one who is sitting behind, there are six things to do. Look, this question was a bit of a trick, it is a genuine question method, because what concept is hidden in this question? In this question, only a normal graph is used and this question can be solved very easily, if the number is here then it is fine, now brother, if the number is more than one, then what has happened, you can apply the formula by putting the graph but you can do it. What will happen here is that there will be time complexity after seeing what will happen there, you see here, what is the era, when plus one complexity, then this means that there is a complex of number of notes, then there is someone else and then How to multiply these, you must be running them outside, so what happened here, this problem is not so loud, it is true, now what do you have to do, now you have to put some such method that you can compile the following list only once. Do the number of Paris different but tell me your answer. Okay, now how will it happen brother? Now if we go by the graph method then it will not be possible. So this much is clear. Okay, so now where and to whom the graph was fitting, after that. Think a little outside the graph because here I have also done Braille, I have found that the question is forcing itself to think in the larger part of the graph, the question was about the graph itself, this antennaless here, this number Of 12, we don't have it, okay, so now, so by taking a little bit of urine in it, what will be the acceptance that these two are zero and one, okay, if you belong to the group with this, then it means that it is possible that you belong to this group. If you do not belong to this group, then it is not possible for you, it is a little bigger and now those who have not understood this problem, there is no need to take tension, first of all, what are the questions for those who understand it very easily? There are six, after that we will build its approach and give the final implementation. Look, the question was going to kill everyone, it was saying something simple, the question was saying that I have to find a way to go from zero to one life. We have to find a way, but yes, I will open the way, there should not be any particular distance bigger than you in it, repeat sir, any particular distance, now let us first understand what is the particular distance, what is going on, this thing. What is happening is that you have three notes and okay, initially which note was C, which one is C, said zero one, and you have this, zero one, and okay, so you have three notes, 180, said okay. It is a simple thing, now the first note is saying to itself that the path from zero to one is going from zero to one. The path is going to be 2 units of time. Okay now what will be the second one said from 1 to 2. For the path of 1 to 2 lives, four units of time are being spent. There is no problem, so it does not matter what you have got. Okay, now understand this thing carefully. Now what is there to say here? Right now what I am saying here is that he had to go from zero to one and I had to go from zero to one and he should strictly take my time, which means I have to take less time than you and I also have to go from zero to one. So is this possible? Apna had said that there are two ways to life from zero to one. The steel man said that it is okay but here there is no shorter path than you, it will take you a unit of time, it will definitely take you, then he said no, you are a unit of time. It was supposed to be shorter than the time, but what do you say, take it quietly, fast. No, no such way is possible. From zero, you have to go from 0 to 2. The way you have to go to life from 0 to 2 should be less than the fair minimum five. So what will our people do if they become zero, then we cannot take this path first, then what do our people do, we go from zero to one, in this you are singing, okay, you are singing, then we go from our forest. And what is the way for you? You thought it was taken from 5. Understand the point here. Never add these two. If you add these two then tell me what will come. Six will come, not six. You are not concerned with it. By adding these two, he may want to. It doesn't make sense to you people that what is different, take it should be 5, the way to come from zero to one, take five, from one to you, everything you know should be < 5, one to you, everything you know should be < 5, one to you, everything you know should be < 5, this thing means to yourself, you should take this. It does n't make sense at all that what will be the solution of both of them, what will come after adding both of them, this thing has become clear, you said, if this is clear, then is it possible, what was your answer, okay, I understood, the question should be clear. Now you should see what it is a simple logic to read it, then you tell me to do it, you can do it, there is no problem, but according to it, how many numbers of notes are there along with it, so they Plus city is to move once and how many times will you have to move. To check saree varios said, if you have to move for all the numbers of Paris, then take the number of N. So how many times will it be N*A+ take the number of N. So how many times will it be N*A+ take the number of N. So how many times will it be N*A+ V. What was not heard, understood, said, understood, became clear, so now what method will have to be applied here, understand it a bit, this may be new for many people, there will be tension, so first let's understand very comfortably. After that, we will talk further about whether going to zero and seven is possible, then what will I do, I will do it to the parent of zero and one, it is possible, there is no problem, now you and going to zero is possible. Neither is it possible, so what will I do with you, I will reduce your parentage to zero, I did not run the graph and you are taking me in all these groups, it means it is absolutely right, so come, what will you say, Apna said 07 It was possible to go from 0 to 2:00. It was possible to play from 0 to 2:00. It was possible because 0 to 2:00. It was possible to play from 0 to 2:00. It was possible because 0 to 2:00. It was possible to play from 0 to 2:00. It was possible because everyone was parented, so according to this, you will have to look at yourself further, then what will you say about yourself? Now understand carefully, what are you looking at first, meaning here, what other thing will you look at first? If they say you can take it, then first of all, what is there by default software, then what will you say, because if it is less than you, then how many are there, not even one, it is correct, Apna is right in this, he said that this 5 is one sixth of 5. As long as it is there, it's fine, so I reduced the zero parents to zero and also reduced the one parent to zero. I went through so much and said ok, can we take this one too? Said yes, we can also take this one. Because what is this also, it is smaller than five, so what did you do here, did you say somewhere, yes, brother, then you came here, what happened to it earlier, what was there, it has come, unit of time, mother. Take anything mother, it is eight and you had to take it less than five, so you cannot take it. Okay, now tell me, these two were here, both of them had to take their notes, zero and you are these, both of their notes. They are their parents are from the balance of shaving, what does it mean here, what will we do in return? Did you understand? The child said, yes, I understand a little, but I am having doubts. Look, don't doubt yourself once again. Like. What you did first is okay, as long as it is less than the time five, then what you did first is okay, then what you did, I took this one further and yes I took this one also, the whole thing happened, it was not said, then After that, those who are in Paris, what were they saying in this, but people who are younger than you, what happened to you that you will have to run Ageless again, are you understanding the meaning of this? Now what have I said at such a point of time? He said, first I have sorted it, then what will I say in short, first run till the small one, that is, first run till you, then first ticket till you, if someone was coming ahead, then I took it, after that then what did I say, now run till 5. Now what does this mean? What is the minimum number of bears here? You can be there. Okay, if you are also there, then there is no need to repeat yourself again. Initial it or at this point of time, you can see where you are. If you are one, you and you, then it means one more in the further limit, there will be no add on and if it is different, it would be a bigger number, then first, if according to you are looking for a presenter, then pay add on here. It will be done otherwise I do n't understand this thing I said yes I understood this thing there is no doubt in it so I made both of them short and after doing these two shots, this is my number which is you, this is my strictly taken All the quantities are adjustable, so there is no one that can take less than this. Here, minimum of 2 bears is required. Okay, anything smaller than this is not possible. It is absolutely correct. Then what will happen here, what did you say, there are all the quantities that are smaller than 5, which can be taken. If the bullet is fine, then one has come to me, zero one has come, you have gone one, 12 have gone, so this one is not taking the open first. He said, okay, both of them had come, both of them were of such size, then what did your friend say? In these two agencies, tell me what are you and Zero? You said, Zero and you are possible. Now this is how you saw it. What did you say? Initially, you had got these two extracted from the parents. They said, yes, I had got it done, it is okay. So, this and this also got done in advance. Look, this question is simple, it is not asked in it, interviews like Google etc. can be given by Nepali own parents, they have made their answer factor their own factor, in which they have got the results returned after doing CAT. Said, ok. Are the parents of zero said zero, okay, understand carefully when to do this, first of all, make your cake profile, this is the first element and this is the last element, swipe them and now do this paper, whichever is your first number. Isn't it according to that, we had to shot it, according to the unit of time and here we have a little expensive post, you will have to type it is a simple thing, it was just that and a little more stressful thing. No, what did you do? Is it okay to make the elements with zero index as every and those with second index? This is absolutely right. Then what did you do? Shorten it. Okay, yes, now the sorting has been done with it. Said according to this. He said ok then or at 16 in this example, by defaulter, then what did you do after that, these queries are on one, but now in the square, is this Pushkar in the square, one is this one. Value one, this value has been stored along with the number of the square, like what is its number, the number of the circle is zero, its number is one because it is on the first index, according to that there should be no problem. Said yes. It is clear, we have sorted this also, so now if we sort it, what will be there in it will be sorted accordingly. First of all, okay, both the sortings have been done here, it should be clear, then we have sorted one wine. The look of the bell is running now, what is the look of the bell saying, what is your condition? Till the time he does it, he trades with whatever is his, adjusts the support of the saree and puri list, does not rate it or else or someone else pays attention. If you want to understand from this or this is okay, whatever you are and this is okay, whatever you are, if there is a comparison between these two, then this number will work as long as it remains small, it is a simple thing, if you said then your What did you say that either your number should reach the list of yes or this number should become smaller, then what will you do till then, if this query came to you first, then this one is fine. A query has come, Apna check kya yeh jo tu hai and Yeh jo tu hai, what is the first but of these two, it is okay. Apne said, kya yeh jo tu hai, it was not big, so it is okay in my Wi-Fi look. it was not big, so it is okay in my Wi-Fi look. I am a bullet, what is the second element of zero, so what is zero, first I stored it in my K, that is, I stored its index, what is its index, okay, if I took it in Took said, brother, it's okay, in There is zero here, it is not equal, it is okay, keep going till it is 5, so what has come in this, what did you say to zero, what did you do to one, you checked the parent of one, and you checked the parent of zero. So, what is divided in Po, parents and what is there in P, the layer of zero is fine, only then what will come here, said the parent, crossing the band of zero, there is no balance yet, what happened here, Apna said that if their parents No, if they are not from their parents, then do it first. Okay, so what did you do to both of them? If you did do it to both of them, then which one did you make their parent, that is, someone from the same family did both of them, there is no problem. Honey, now let's see how the parent check is going on here. Come here quickly. One of you had signed up and the other had passed that number. So here you were checking whether the balance of both of them is correct. If it is then return If there is a match on four, then this one on four will also come here. What happened back? Okay, so was the balance of both of them, how is it divided? Second element said, first element, what is the first element, said, are you yours, what have you checked, said these. What is the difference between both of them, if the balance check of both of them is absolutely over then what will they do? Apna is watching.
|
Checking Existence of Edge Length Limited Paths
|
strings-differ-by-one-character
|
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .
Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
**Example 2:**
**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.
**Constraints:**
* `2 <= n <= 105`
* `1 <= edgeList.length, queries.length <= 105`
* `edgeList[i].length == 3`
* `queries[j].length == 3`
* `0 <= ui, vi, pj, qj <= n - 1`
* `ui != vi`
* `pj != qj`
* `1 <= disi, limitj <= 109`
* There may be **multiple** edges between two nodes.
|
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
|
Hash Table,String,Rolling Hash,Hash Function
|
Medium
|
2256
|
1,092 |
1092 shortest common super sequence oh actually super serious not sub Stevens I come in two strings string one is going to we turn the shortest string that has folks sharing one and shrink to our sub sequences excuse me have multiple answers exists you may return any of them hmm like a cell phone related problem before but so n is a thousand so that already means you should be able to reason about n square I think it does I mean the century does still become even though the is super sequence so I think my intuition my first tour but I think about this club is that you still wonder sure so I it is you want to solve longest common subsequence and then the shortest common super sequence it's just the characters that are not in that list added to it and that makes sense and it's certainly that this test case proves that's not a proof that's just like at least it's not a calendar example but if that's the case you could solve the common the longest common subsequence problem and n square and then we just have to reconstruct or their way at that time cool and I think that's what I'm gonna start by doing it I mean put this prom and this is just me trying to learn to be honest one thing I'm trying me but a little bit better about is on doing Bottoms Up dynamic programming and not just always default is tough down memorization based dynamic programming but yeah dynamic programming there's a lot of people's arch-nemesis there's a lot of people's arch-nemesis there's a lot of people's arch-nemesis and maybe mine too oh yeah I say n is equal to one that to be sort of longest so that just says okay yeah I guess there was a good developer times and range we got out of the prevents maybe I went up by one actually what's off distance already needs to be yeah okay and one goes by painting it I don't think you could get away with one go in that sense we could I mean about the way you mean by one go but you need to reconstruct some of data in programming you need to kind of do what they have the construction and usually that just another commercial which backwards so it's about what you mean by one go but it's still one DP yeah it's hard to get right I mean I think takes practice but not super hard in theory our typing anyone come yeah our dynamic programming is I think this is a little bit beyond the scope of how I can explain it but it's basically a way of structuring a problem such that you serve the subproblems you enter a problem by answering problems that are related to that problem that's kind of the way to do it the canonical example is I would look up have something to Google just Google for dynamic programming Fibonacci and that's usually the one that everyone gets started on and then there are a couple of ways to go about that but yeah I mean we also recommend MIT thanks Aaron destroy and I also recommend for dynamic programming MIT albums radio course it's very good by Erik Demaine professor to me he's very good yeah so Phil destroy it to kind of answer your question actually I've been I got into competitive programming recently it's a it's an addiction so I've been just doing a lot of practicing for a competitive programming so that's kind of story yeah cool okay so anyway for excellent so yeah so without dynamic programming background I'm afraid that this is going to look really crazy hmm what are the transitions oka stranger I know what I want is dis looks right and then your pass is just oh it's gonna be you could do that within the same loop but I just like doing it in different loops for quality and yeah that's print out the pass and then you should return a placeholder for that yeah you're not wrong in that it's a waste of time but I do it for fun more than you know so I mean anything you do for fun is a waste of time mostly right did I do I might have swap the ends and amps I feel like I always do that a lot with these type of things what is the index that's our range not this probably this but I thought maybe I Smarties actually that sounds right actually yeah I think that I mean some of this is like Python specific because in watching McCoy and see I would never get this wrong this was the orders are always in a good or better maybe way but yeah you see that the most common is here but now we have to construct the array this is dad's the hard part hmm for this you generally have to kind of keep track of the previous one I'd like to just do open and then here just to prove oops there's quite see you hmm the way I do is a little weird I need to fix this time my programming isn't quite I mean it's good enough but it's not quite right but our city that is our good I don't know if I know what see the others no capture the flag yeah I mean any time you do things for fun it's okay I'm not a big crazy you know thing for it I need to clean this up a little bit okay one is bigger than my cross one can we do this thing otherwise and we want to get max of one of these mmm yes I would let us call this actually that's called destroy this is - I'm using mental bit destroy this is - I'm using mental bit destroy this is - I'm using mental bit masks there are other queen of ways to do this I think but hmm well me I guess the Queenie way is just to use younam's well actually doesn't even have to get housed technically this could still happen so let's relax those things okay cool so let's see making sure that doesn't cry I should be okay should still give me the answer and also now I redid it right we don't actually even need this best we could actually point out just the EPF and oops oh so mind you know how to type correctly which for me is not again okay what mistakes were made now cuz we don't yes usually people do this backwards because well it's just because we don't we do not to the last pose mmm okay fine but there now we have to add pounds to everything I don't know way I think the way I constructed I don't do I don't use this silver one so actually sorry I get a little bit confused about offline ones on DP so let me think about it are you also usually do it the other way I've been kind of trying to be better about it in general okay finance let's actually do it this way I'm actually what I want is if even to say supona well I guess that's already the case and then you'd go if now right we display that I start from the first one and D P of X Y is equal to DP X minus 1 plus 1 why should I check to the size it is a smaller than this and then I'm going to check the other cases which is X Y minus you don't kind of purse one because yeah because you're not cool enough and dynamic programming could look like gibberish I assure you there is some madness in the quality no the other way well okay British okay this should be good ivory voted so that this will definitely get populated look good proper cases right wait like an infinite loop instead advice you're taking so long okay cool so we do that get the right answer and in this case we only have to look up one Incept entire table let's get rid of this cool and now what does that mean right so that means in and what we call to prove one proof and times miss Yulan or Noddy goes to negative one then that's let's go backwards to construct a string actually don't even need to tape here way anymore technically and you can actually kind of reproduce this about this privily do it with a group of eight that can allow a more straightforward path construction thing so yeah nice to actually say X 0 and X Y is it gonna end x and y Juhi and let's subtract one from both of them and then we would just maybe backwards I think I have I printed now then I'll be back return and I'll be backwards better but that's just Crusaders are we so does he go to some empty string and then knows that I think in theory you want one because you're going backwards you need to reverse this but I'll be versus later that's not that hard way so yeah so they're mystic good stream is the same so at that point we just take one of them it doesn't matter which one let's get to count it before we talk about Osen X Y is equal to 2 and as to issue every ticket from the Y because that was a better path so this but again we saw it was one then we take it from the X again and again this should never happen but maybe just to make it never happen to both let's make this actually negative one but ok actually let's make this default just say 400 some negative infinity but then certainly give zero is zero actually that's print it n is zero thousands and let's make this like a big number this should never happen stone that's not worried about it yet and then let's see in this case actually to be worse is the same so maybe that's not a great example in my brilliance these are younam's but you're not wrong string of index maybe that's oh because I'm off by one because that's the way I did this I think was for X Y and X I choose x and y -1 so that's actually choose x and y -1 so that's actually choose x and y -1 so that's actually dupes you find out well Oh close but not quite hmm let me just print out passing just in case that Dow is the reason is that when you clasp it but then it would go in an infinite loop so that's probably not it so oh because I think I go to so this should happen once oh okay that's actually we kind of expected but you have to do it once because there's like to be fun to think about it's a route on a tree you get to the root so there's no previous so then you should you have to print that one case right but which one do you put okay let's just print out the extent of why yeah I think I actually have to distinguish right I think maybe I had to set my base case on a good way but yeah in this case obviously you want to go to why okay actually that makes sense because I never declare and you could kind of be stricken struck your base case so that does a little bit better but now you just go if Wow X is greater than zero we stop as the order I think should not matter in this case and now you do the same and remember that these are why one based one index oops well I mean it'll be easier for two not one thing for the loop if we decrement it up to its so and I think this is reversed so let's try another case because I'm really two views of this so let's just say this and then I don't know right in if this goes right then they cease to be on in the foot oh I died your string quotes air quotes no real quotes I guess that quick I thought I could ten quick correctly mm-hmm yeah okay so this is what I mm-hmm yeah okay so this is what I mm-hmm yeah okay so this is what I expect kind of maybe not actually Krishna in no universe is this very way but I think we needed to just reverse this and I should be fine because I'm we're putting in a real like I was saying we were going backwards so you expect ourselves to be reversed so yeah it's still a pie phonic way to be versus train is it just like let's that work yes that still Stranglers it's just a slice that way still learning a little bit about pie file and like weird things okay so that's right cool well that's kind of doing out a few cases that's it all right so I'm at least 190 okay I mean this just ends up paying some variation of a P I don't know how I'm how many times I said judging is kind of slow right now today maybe oh is it just me okay in the interest of time I'm just gonna actually I should do one where it's fully uh that's just fully uh whatever like overlapping intersecting fuse so judgmental okay so yeah so now that's just a man and then we'll see okay cool um yeah it could have been faster I guess I think mate it's always hard to tell sometimes whether you need to go top-down or bottom-up with respect to go top-down or bottom-up with respect to go top-down or bottom-up with respect to unreachable states and he strove out kind of doing it's possible at this one as well unreachable States due to the early non intersection but that's not a big deal don't know why so there are people maybe talk about later yeah oh we're string a pet oh because it creates a new string afterwards so maybe that is that's a good point you're definitely in that uh I mean I'm you know for the purpose of competitive programming and stuff like this I don't really think about I mean sometimes I do when I know that the running time would be depending on it in this case you know maybe that's why I so stop but you're definitely right and I think also like I think a common interview tip is that I always bring up strings just to kind of show that I know how shrinks work and I'd like I'm you fish I mean you're fishing in this interview because you know because for time purposes when I'm in an interview I'm just trying to get it to show that you know but I always over point out that like there's a production code I would do shrink buffers etc wearing buffer shrink builder depending on whatever language you are that's probably why my thing is too slow but that's why I mean I added to the end that I reversed it so these are just like unnecessary time but they're also like not the dominating times which is why I don't care about it this is always gonna be n times M but this is roughly always strictly less than n times M given though is that necessary I do in the chance I mean this is a little bit harder than a normal interview a question for sure path construction is not something that I would and I personally would consider in scope for an indie requestion because that's it's non-trivial for sure and that's it's non-trivial for sure and that's it's non-trivial for sure and it's hard to get right I did get a red one gogo and blacks kind of I mean well he's like I did testing along the way obviously if I knew my expected behavior each step of the way for the most part so I'm really happy with that but yeah this is a lead code contest form but that I did about 25 minutes by thing I talked for a little bit that's my you know like I've done it faster for sure and Maine confused he's maybe I would ever you see but oh yeah definitely this is actually very straightforward for competitive programming but for interviews I would not worry about it I mean I was worried a little bit about dynamic programming for certain companies of you do your research and they're a company that has time programming problem then you know you have to know about it because this is relatively straightforward like if the question is you know what is the length of the shortest common super sequence then you should be ran into this very quickly I got most of that code out pretty quickly about the previous traversal but and yeah and things to Google on for this problem is tiny I'm programming and have construction I mean I could explain it over in more detail but those are the kind of things that if you're watching it and if you're not like you're watching this denominator that's what I would go on but otherwise a straightforward application of bad thing but not you know but otherwise and the nuance is not on a path construction which is a little bit tricky but yeah again for an interview I would be shocked at that I mean sometimes like you know if an interviewer you just get palms you like but I will see you next year and I when I interview again or something like that because sometimes the luck is not in your favor you know GG well played better luck next year but I mean you know because you know you don't have infinite about hours you should study on things 10 you're not a strong one then a more fundamental than studying this that's what I would say what is the hint I'm just curious if we can find okay we knew this or that I knew this kind of already but yeah cool uh yeah so that was a fun park attractions thanks for a bomb that way something that like I said I have to I've been practicing their bottoms up a little bit and that's what I would like but still a little bit more as usual it's good
|
Shortest Common Supersequence
|
maximum-difference-between-node-and-ancestor
|
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`.
**Example 1:**
**Input:** str1 = "abac ", str2 = "cab "
**Output:** "cabac "
**Explanation:**
str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ".
str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ".
The answer provided is the shortest such string that satisfies these properties.
**Example 2:**
**Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa "
**Output:** "aaaaaaaa "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of lowercase English letters.
|
For each subtree, find the minimum value and maximum value of its descendants.
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
1,782 |
hello everyone let's solve this recall problem today it's a um this problem is the last problem used by weekly contests and it's actually a heart problem and the acceptance rate is pretty low it's only a little bit above 10 percent okay so let's take a look at this problem yes problem is actually um pretty hard to understand so let's take a look at the example so n is four means there are four nodes since this graph one two three and four and there are some edges it's an undirected graph and the edge can be repeated for example cell two edges between node one and node two and for this graph it means like um since we have four notes so there are six pairs one two one three one four two three two four and three four and for each pair we can get the number of edges um like these two notes on for example for node one and node two uh they have these five edges for nodes three and four only the mid middle three edges and middles uh has no three and no four so it's count is three okay so the question is given a query for example if prior is true it asks us to return like how many pairs that has edge that's uh that is greater than this square for example one query is two we know all the six numbers are greater than two so the answer is six one square is five we know the previous um five rows have numbers such as greater than three so we return five okay that's the problem how do we solve it uh first of all uh we need to uh for loops queries and for each query we need to get one answer for specific query when also naive solutions we can double for loop nodes but the number of nodes can be to multiply 10 to 4. so on square will become like four multiply 10 to a which will be tmtle so it's a slow solution um okay next i will talk about a solution that can pass the tests so this is the example and there are two edges between one and two and let's see one query six and three first of all we have three data structures the first data structure will use this graph so it's a vector of another map for example for number one and two is the neighbor of node one and 2 occurred twice and 3 is also a new neighbor of node 1 3 occurs once okay for sizes it's actually more like degrees so from node 1 it has two edges so the degree three for null two degrees four and four number four degree is two okay then comes the perfect sum actually it's not a perfect sum more like a suffix sum or i can explain it means like for if it's zero means there are four nodes whose degree is greater than or equal to zero for one we know uh excel for nodes excel group degrees are greater equals than one for two also four like four three we know that only three and four there only one so and this array is very useful let's say one query is three if for a node like for this node number one we know the degree of node one is three so quality minus the degree of number one is zero which means uh we need to find other nodes whose degree is greater than zero this can pair with this node one and make our uh mix that number of edges is greater than this query right so when queries is released this total is the result for three and note here i will for loop each node and pair other nodes with the current node and uh it adds the answer to this total node i need to divide by two here since one is where like i count two but one i is 2 i also count 1 so i count them twice and divide by 2 at last okay and this is our query and our target is quarry minus the degree of i since we want to pair second node like with another node and makes the uh like total number of edges or total number of degrees is greater than query okay so we can use this array to get set number for example one query is three and i is one we know that degree of i is uh we know queries three and sizes is three so target is zero so we need to find the number of nodes whose degree is greater than zero which means uh i need to find the number of nodes whose degree is greater or equal than one so this number is what we want here so i just um plus prefix and target plus one here but there are two uh wrong stuff two bugs here first of all we know what is three at most three other nodes that compare with node one how can we get four here yeah it's because we can't run itself so we need to exclude the current node if the degree of current node is greater than target we should minus can count first at minus it by one since it will be incremented in this line okay the second part here is that for the pairs set neighbors for example one two they have two shared edges so the total address is degree of one plus degree of two then minus the short edge which is two so we cannot just simply use this line so we need to separate the calculation of neighbors and non-neighbors node of neighbors and non-neighbors node of neighbors and non-neighbors node here we will iterate every neighbor of node one and we do things if the degree of node if the degree of neighbor is greater than target we will decrease and decrease the current variable since the effect will be added back into this line okay next we just calculate this neighbor so the total edge of my car node and this neighbor node is the degree of i plus degree of neighbor minus the common edge as long as number is greater than query we get one more data like one more pair here so here is the solution the tricky part is the quantum we need to minus the current here first since the effect of neighbor and the account node will be added back in this line since this perfect sum already contains like all the notes okay that's basically everything thanks
|
Count Pairs Of Nodes
|
smallest-string-with-a-given-numeric-value
|
You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as the **number of edges** that are connected to **either** node `a` or `b`.
The answer to the `jth` query is the **number of pairs** of nodes `(a, b)` that satisfy **both** of the following conditions:
* `a < b`
* `incident(a, b) > queries[j]`
Return _an array_ `answers` _such that_ `answers.length == queries.length` _and_ `answers[j]` _is the answer of the_ `jth` _query_.
Note that there can be **multiple edges** between the same two nodes.
**Example 1:**
**Input:** n = 4, edges = \[\[1,2\],\[2,4\],\[1,3\],\[2,3\],\[2,1\]\], queries = \[2,3\]
**Output:** \[6,5\]
**Explanation:** The calculations for incident(a, b) are shown in the table above.
The answers for each of the queries are as follows:
- answers\[0\] = 6. All the pairs have an incident(a, b) value greater than 2.
- answers\[1\] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.
**Example 2:**
**Input:** n = 5, edges = \[\[1,5\],\[1,5\],\[3,4\],\[2,5\],\[1,3\],\[5,1\],\[2,3\],\[2,5\]\], queries = \[1,2,3,4,5\]
**Output:** \[10,10,9,8,6\]
**Constraints:**
* `2 <= n <= 2 * 104`
* `1 <= edges.length <= 105`
* `1 <= ui, vi <= n`
* `ui != vi`
* `1 <= queries.length <= 20`
* `0 <= queries[j] < edges.length`
|
Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index.
|
String,Greedy
|
Medium
| null |
160 |
Hello, I am a developer child Gary Ni. The problem to be solved this time is Intern Section 160 of Two Linked Lists. Head a and head key, which are the heads of two single linked lists, are given as arguments. This problem can be solved by re-tanning the intersecting part. problem can be solved by re-tanning the intersecting part. problem can be solved by re-tanning the intersecting part. If there is no intersecting part, you can do part 2. For example, if you look at this and P, which are 2 of the single linked list of a, you can do part 2 of February. If this type of single linked list comes in. Since there is no overlapping part, you can return it. Let's solve it. If you try to solve it may be the man e01, so you may get confused. If head a is young or head P is inserted, there is no intersection, so you can do it in the second round. I will solve it using the y statement. Since the current variable will keep changing, let's declare it in advance. When 5% a and per rupee are different, we will continue to look at the y statement. When they are the same, it means that the same point When 5% a and per rupee are different, we will continue to look at the y statement. When they are the same, it means that the same point When 5% a and per rupee are different, we will continue to look at the y statement. When they are the same, it means that the same point will come at some point. So, I'm going to pretend like this here, so at that time, it will come out without running and return one of the two. You can use the container current p m. Let's solve it. If there is a current a, Kara Ink a will be reallocated to Next on Kara's Day. Well, if there is no current A, then if there is no such current an If not, Currupee will be the 1st party of the head. Now, in this case, let's say that it is Current A and Current P. Once you return to the gold and 1 door, there is Next, so Current is Hyundai, so each other's Next. It will point to and it will be re-assigned to 6 re-assigned to 6 re-assigned to 6 and if you turn again, the container will be 8 and the quarter P will be 1. If you turn again, current a will be 4 and current p will be 8. If you turn one more time, the container will be 5. The cur rent will be 4. If it is 2 once more, current a will be young and curl tp will be 5. When turning once more, there is no current a. Since it is null, it is caught in s in this section. Head p Head empty is recorded. This is now in the current. And if you rotate once more, the container will be 629. The current value will be 4 because it is young here. And then it will rotate again. The container will be 1, and the current value will also be here. And if you rotate once more, it will finally be a single list pointing to the same memory. Single linked list. It points to . single list pointing to the same memory. Single linked list. It points to . single list pointing to the same memory. Single linked list. It points to . Therefore, the and 1 statements are exited here and the single link list 2 is returned. Let's upload it. 4 You can check that it passed normally. It may be helpful to watch and listen to Discus like in the last video. I think that's it for this video. I'll see you in the next video. Thank you.
|
Intersection of Two Linked Lists
|
intersection-of-two-linked-lists
|
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
For example, the following two linked lists begin to intersect at node `c1`:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
**Note** that the linked lists must **retain their original structure** after the function returns.
**Custom Judge:**
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
* `listA` - The first linked list.
* `listB` - The second linked list.
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
**Example 1:**
**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
**Example 2:**
**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
**Example 3:**
**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
**Constraints:**
* The number of nodes of `listA` is in the `m`.
* The number of nodes of `listB` is in the `n`.
* `1 <= m, n <= 3 * 104`
* `1 <= Node.val <= 105`
* `0 <= skipA < m`
* `0 <= skipB < n`
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
599
|
1,679 |
Had happened here today's problem list number of time of sun given in food of interior and below jobs page numbers for every side reaction and at every step number subscribe to achcha lagata hai too many times alternative friend number side problem let's get into and solution are Number Three to subscribe and subscribe the Video then subscribe to the Page Torch Light and Counter to Calculate How Many Countries Are There Subscribe Problem First Step Three Points in 98 Calculate the First Thing Adding List Number and Greater Number Even Saptak Ke and Not Safar Tango Play these to-do list Play these to-do list Play these to-do list Main isi khol bridge notifications In that case What is the weather report Subscribe to this channel and subscribe for number two that decreasing and degree meeting ride point a moving into three Suno liquid please Subscribe I Saudi Steps And Pretty Simple Here Going To Find The Points 100 Hua Tha Deposit Were Going Too Short The Amazing Points 5302 This Point To Point Note Subscribe To I Pandit Left Pointer This Is A Great Civilization By This Great Content Arrangements Simple Logic So Let's Go and See Problem Solution Subscribe Channel Subscribe Hua Tha Shabd The Snake Champion of Saint Louis Us Post Element Mention Points Elementals Element At Index Android Alarm List Element Loot Sunao Pyaar Ko * Ya Dallu Viral Ho Ki Ego Ke Naam On Flat Point and Ride Point C Hours Spinner * Increments C Hours Spinner * Increments C Hours Spinner * Increments Account Increment Flute and Decrement Se 0.2 Smooth Next Element Note That Se 0.2 Smooth Next Element Note That Se 0.2 Smooth Next Element Note That Rani Slapped On That Krishna Account Create Arthdand Ke Water The Number 4 Greater Than That Which Means It's Largest Number Swami Don't smaller number to edit Subha Pune reduce the largest number One chest notification per day Light condition hair Do n't forget to subscribe Hello viewers Intermittent account it you only swollen blood 2.1 approach very similar you only swollen blood 2.1 approach very similar you only swollen blood 2.1 approach very similar to the one month problem vote only will be discussed in the earlier Kiya Saugandh link in description follow back to check subscribe here and there solution which helps the user to subscribe to
|
Max Number of K-Sum Pairs
|
shortest-subarray-to-be-removed-to-make-array-sorted
|
You are given an integer array `nums` and an integer `k`.
In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array.
Return _the maximum number of operations you can perform on the array_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], k = 5
**Output:** 2
**Explanation:** Starting with nums = \[1,2,3,4\]:
- Remove numbers 1 and 4, then nums = \[2,3\]
- Remove numbers 2 and 3, then nums = \[\]
There are no more pairs that sum up to 5, hence a total of 2 operations.
**Example 2:**
**Input:** nums = \[3,1,3,4,3\], k = 6
**Output:** 1
**Explanation:** Starting with nums = \[3,1,3,4,3\]:
- Remove the first two 3's, then nums = \[1,4,3\]
There are no more pairs that sum up to 6, hence a total of 1 operation.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `1 <= k <= 109`
|
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
|
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
|
Medium
| null |
227 |
video we're going to look at your problem called basic calculator number two so if you haven't checked out my other video called basic calculator number one i highly recommend to check out that video before this one but basically this question uh we're basically trying to evaluate a given string expression and this string uh in this case contains digits right and it also contains plus sign minus sign multiplication sign division sign so basically we want to get the total value right so you can see here we have a string right and then what we have to do is we have to evaluate this expression and return its value in an integer value right so in a type integer so in this case what we had to do first we have to complete the multiplication right so we have two times two which is four and then what we can do is we can deal with the addition right so which is three plus four in this case is going to be seven so in this case the output is seven and then let's say we have something like this where we have a division there in this case like i said again we're going to return an integer value um so in this case it's just going to be one right and there could also be spaces right so unlike the previous question where we were or in this case the basic calculator number one where we had uh brackets right so we have to get what's we have to complete what's inside the brackets first but this question we don't but the same thing applies because in this case we want to complete what's uh the multiplication first before we do the additions and subtraction right sorry multiplication uh and division right we want to complete those two before addition and subtract subtraction so in this case you can see here um let's say we have something like this again we have to get five divided by two first which is going to be two plus three which is going to be five right so we cannot do the other way around so in this case what we had to do is that we have to given this expression we have to do something similar right so you can see here we still have the same similar constraints right strain will always not be empty each expression is valid and we're all the integers in the uh in the expression are non-negative uh in the expression are non-negative uh in the expression are non-negative integers so in the range from 0 to this number right so we're going to contain those signs or those operations or those operators in our strength so in this case how can we be able to solve this problem well to solve this problem what we have to do is very similar what we did in basic calculator number one right for a basic calculator number one what we have to do is we have to complete what's inside our brackets right once we complete what's inside our brackets we can be able to complete the outer brackets or other brackets right so in this case we have to do the same thing if there is a multiplication then what we have to do is we have to complete that first trade it is like a bracket we have to complete this first and then we can complete other numbers right so if we were to do this same thing we're going to have a pointers and then what we're going to do is that we're going to continue to iterate right and this time we're not going to use a like a um in this case we're not going to use a variable like a sum or like a total or something to keep track of our current sum because what we had to do is we had to get rid of those multiplications and divisions because we have to make sure that everything that we have here is just basically just regular plus and minus right so let's say we have like um like a negative one here right um or minus one here right so what we have to do is we can be able to use like a stack right in this case what we had to do is we have out three onto the stack right and then because three is a positive value so we add it on to it and then we our pointers move one to the right okay and then what we're going to do is that we know this is a plus sign so in this case the operator is a plus so that's fine and then the next element is two right so in this case what we can do is we can just add it on to two right and then um and then what we can do is we can just uh we have our nest element which is a multiplication symbol so in this case uh what we can do is we can change our up current operator to a multiplication and then we move on to the next element because the previous operator right in this case we have our previous operator which is equal to multiplication if it's a modification what we can do is we can basically just change because this is our stack right we can be basically get the previous element that we inserted onto our stack and then we can just change that we can just overwrite that right we can just pop that element out and then the current element is two times the previous element right two times the previous num which is two so in this case it's four right so we append four onto the stack and then let's say we have like minus one um so the next symbolism is a minus symbol so we have operator minus symbol and then once we get to the next element we're gonna do is we're basically just going to have a negative one right so operator in this case is a negative symbol so we're gonna have one times the negative one simple right so in this case we're gonna have a negative one appended onto the stack okay and let's say we have uh let's say we just have like uh divided by three for example right so what we have to do then is the next symbol is the division symbol okay and then the next element in this case is a three so in this case once we visit a three what we can do is we can just take the top element out of the stack right in this case it's negative one and then what we're going to do is we're just going to append the new value right which is going to be the previous value divided by the current value right so the previous value was negative one divided by the current value which is going to be uh negative one out of uh divided by three right we can just append that onto the stack right in this case it will be actual value like maybe like as uh like a zero or something right um so basically you get an idea right so and at the end what we're going to do is we're going to get the sum out of all those l values that we have in our stack so 3 plus 4 plus 0 which is basically our sum right so in the code it's a lot simpler right you can see here what we're going to do here is that we're going to um first have our array which is s dot character array and then we're going to have our stack um we're going to have our initial operator which is a plus sign so first we're the goal is we want to get rid of the modification and the division as well as the minus symbol as well right so that once we have our or in this case we're not the minus symbol but like the multiplication and division once we get rid of that we can basic basically like iterate through the stack try to get the total sum right the total values uh that we have in our stack right like the goal is basically we're trying to get rid of the multiplication and division right we're trying to group those values together right if we have a 2 times 2 we want to get rid of that we want to turn it into a 4 right and then we add it onto our stack right and if it's a division right we can just like group them together in this case a zero we add it onto our stack right so it's the exact same thing so first what we do is if it's empty if it's a space we can just continue uh if the current digit is actually a digit right first just like we did in the basic calculator number one we build the number uh using the stream builder and then what we're going to do then is we're going to parse that so that's our current num okay so once we build our num right and then if the operator is if our current operator right if a current operator is a negative value right if it's a minus symbol we could just going to get current num is equal to a negative value right we're gonna just get the current number times negative one if it's a modification symbol we just pop the top element out of the stack and then times the kernel so current numbers basically is equal to current num times top element out of stack right and then same thing for the division as well and at the end once we update the current num right based on the current operator we can just add the step add the current number onto the stack so and then in this case you can see here if it's not a digit it would just basically get operator is equal to this right so basically you can see this is how we like this is basically a general idea right we basically just iterate the entire string and then we trying to group those multiplications uh or divisions together and then we're just going to iterate the entire stack to get our total okay and then you can see that this is basically how we solve the problem and the time complexity and space complexity is all big over n where n is number of characters that we have in our string so basically there you have it thank you for watching
|
Basic Calculator II
|
basic-calculator-ii
|
Given a string `s` which represents an expression, _evaluate this expression and return its value_.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`.
**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.
**Example 1:**
**Input:** s = "3+2\*2"
**Output:** 7
**Example 2:**
**Input:** s = " 3/2 "
**Output:** 1
**Example 3:**
**Input:** s = " 3+5 / 2 "
**Output:** 5
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces.
* `s` represents **a valid expression**.
* All the integers in the expression are non-negative integers in the range `[0, 231 - 1]`.
* The answer is **guaranteed** to fit in a **32-bit integer**.
| null |
Math,String,Stack
|
Medium
|
224,282,785
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.