id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,352 |
so hi guys today we are going to solve this question which is product of last k numbers so this is the lead code medium question and this was a pretty good question when i sold it and i would like to share it with you so the question goes like this for example you have a three two zero five three zero two four five for example you have a vector with these elements three zero two five four and the question is that um vector n which has two functions either you can add or you can get product these are the two functions and when the great product function is called you have and it is passed with a parameter cape so you have to return the sum of the last k numbers for example in this case if k was equal to 2 so the sum of l so the product of last two k numbers you have to find the product so it would have been 20. similarly if k would have been three the product of last three numbers is 40 and similarly if the k would have been four the product of last four numbers is not it is 0 and similarly for k is equal to 5 the product of last k numbers is similar to 0 so if 0 comes once then the entire numbers which are for example for then the sub the answer for all the functions which are called for get product with which are having k and if for example from here you have to start the product of these three numbers now for k is equal to three so for all the numbers from where from for which you have to start a product from this number or this number of all of them which are behind zero the answer would always be zero i think you got this point right okay so how can we do this question so the first brute force approaches we can do very simple thing we can just do for example we can add these elements that for finding the product we can start our loop from k minus 1 till n minus k and we can find the product and return but this will take off and time and if there are uh if that product is called n times only on q times then the total complexity will be of n cross q which is approximately of n square and i think this would be uh not be accepted so we start again so how can we do this so the first thing that i would like to introduce you to is we can do one more interesting thing we can do this thing for example we have the number six five four uh eight and two okay so the product of numbers still here is six here it is thirty here is it is one twenty here it is one twenty cross eight is into sixteen ninety six and here it is 1920 okay so we have been given these numbers so for example if now i want to find the product of last three numbers so what i can do is i can divide to this i can do so what do we precisely want we want 4 cross 8 cross 2 this is we want for the product of last 3 numbers but what i can also write this thing as i can write 4 plus 8 cross 2 as this thing i can write 4 plus 8 2 s 6 into 5 into 4 cross 8 cross 2 divided by 6 cross 5 so what will happen now is 6 0 will get cut with this and what i will be remaining is 4 cross 8 cross 2 so this is the logic many program so what you can do is so what you can do this what you can do is you can just simply uh keep a store of the all the numbers here and for example if you want to find the product of last two numbers what i can do is i will divide v of the last number that i have divided by v of n minus k minus 1 so this will work as follows for example if i want to find the sum of the last two numbers so v of n minus 1 is 1 9 2 0 this divided by the last two numbers so n is 5 minus 2 is 3 minus 1 is 2 so i have to divide it by 120 i am using zero based indexing so this would be 1 and the remainder would be 7 6 16. i can getting which is correct okay so this is how we do now one more thing that i would want to do one more thing that i have to introduce to is for example what do we do with which are having the cases 0 for example this case so in this case what can we do is we will have will be having a set and that set will be storing the last occurrence of that set will be showing the last occurrence of zero so we will see if n minus k the number still which have to take the product if it is greater than the last occurrence of zero last occurrence then we have to do use this formula or else the answer would be zero so this is the whole program the logic now let me uh let me tell you the code so for example let me just do this yeah see i think you will be so this is the class product of numbers so i'm taking the vector wave which will store the to me the store to me the uh the product of the numbers i am taking a set for the last arguments and i am taking to multiply so what i do is to multiply set to one so when i'm whenever i'm adding a number so the index at which that number would be added would be the way down size is that the current index so if the number is equal to zero so the two multiply would be or let me do that will tell you what is happening in this case as if the number is not zero i'll simply multiply two multiply by one and insert to multiply in the vector so if the number is zero let me tell you what happens so this is one case that you need to for example three zero two five four so this is the case right so the production here is zero the production so technically the product till here should be zero but we are not doing this for example if the case comes here you have to find the product the last two numbers now the answer is not zero but if i have taken 0 then it will always return 0 so what i can do is whenever there is a 0 i will start my again multiplication from the next number and what i will insert in the queue is 1 because when i'm doing the for example when i'm taking the uh product of the last three numbers so i have to divide it by and minus k minus one so in this case would if it has been here zero it would divided by zero which will give me a runtime error so i am inserting one instead of zero here i hope you get the logic so this is simply what i'm doing there's a get product now this is one case if there's no zero present in that matrix so if the if i want to find the sum of all the numbers then it has to be the sum of all the numbers but if i do n minus k minus 1 it will tell me the what is the product presented v of minus 1 which is not accurate so we are returning v of n minus 1 and else we have to return v of n minus 1 by v of k minus 1 and for the other case we have to find out the last index of zero if it is greater than zero this i'll zero to return zero so this got submitted on hacker rank and uh yeah sorry only code and uh yeah i think this was a pretty good question and you should also try it thank you
|
Product of the Last K Numbers
|
maximum-profit-in-job-scheduling
|
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream.
Implement the `ProductOfNumbers` class:
* `ProductOfNumbers()` Initializes the object with an empty stream.
* `void add(int num)` Appends the integer `num` to the stream.
* `int getProduct(int k)` Returns the product of the last `k` numbers in the current list. You can assume that always the current list has at least `k` numbers.
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
**Example:**
**Input**
\[ "ProductOfNumbers ", "add ", "add ", "add ", "add ", "add ", "getProduct ", "getProduct ", "getProduct ", "add ", "getProduct "\]
\[\[\],\[3\],\[0\],\[2\],\[5\],\[4\],\[2\],\[3\],\[4\],\[8\],\[2\]\]
**Output**
\[null,null,null,null,null,null,20,40,0,null,32\]
**Explanation**
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // \[3\]
productOfNumbers.add(0); // \[3,0\]
productOfNumbers.add(2); // \[3,0,2\]
productOfNumbers.add(5); // \[3,0,2,5\]
productOfNumbers.add(4); // \[3,0,2,5,4\]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 \* 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 \* 5 \* 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 \* 2 \* 5 \* 4 = 0
productOfNumbers.add(8); // \[3,0,2,5,4,8\]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 \* 8 = 32
**Constraints:**
* `0 <= num <= 100`
* `1 <= k <= 4 * 104`
* At most `4 * 104` calls will be made to `add` and `getProduct`.
* The product of the stream at any point in time will fit in a **32-bit** integer.
|
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
|
Array,Binary Search,Dynamic Programming,Sorting
|
Hard
|
2118,2164
|
137 |
humans lucky and welcome to may the gods be with you today we are going to discuss the jewel decoding challenge day 22 problem so let's get into the question first and identify what the requirements are so the question is called single number two problem and what it basically asks is that we need to identify the element in the array that is appearing only once however the remaining elements would be appearing thrice so as you can see an example one there are four elements and out of which three elements are two and only single element is three so the output is three in example number two zero and one are appearing thrice where as 99 is appearing only once so the output is 99 so before we get into the coding part of this particular question we will identify what are the requirements that we need beforehand so that we can hold it much easily as always we are going to discuss two solutions for it one is a force method and second is called the optimized method which will help us reduce the helped us reduce the time in which the board computes itself so let's get into the prerequisites of this question first okay so the first thing that we need is called hash map it basically uses key and value pairs to store data so this is the key and this is the value that is going to be stored and both of them are going to be integer so these are the data types for them so and hash map only stores a single basically does not allow duplication of keys however the values can be the same and there are several methods that we use in hash map in order to store data to fetch data etc so we will discuss them one by one dot put method so it is basically hm not put will be used to put a specific element inside the hash map dot get will be used to fetch a particular data from the hash map dot remove will be used to remove a particular data from the hash map dot clear will allocate the entire data entry that is then the hash man however the hash map will remain intact dot size is basically used to tell us the size of the hash MA he set is basically used to generated a set of keys that are there in the hash Mubarak and are being used not values returns as the values that are there inside the hash map and not contains key helps us to identify the Alpha particular key values key is present inside the hash map so there's another thing that we're going to use today we could have used a simpler thing but I wanted you guys to learn something new so that is when B equal to use I traitor for this problem so I traitor is essentially a for each loop it is optimized version of for loop so when in depth we consider for each loop it uses I traitor in itself so we are going to use I traitor for this particular problem that there are two methods inside the ia traitor that we mostly use so they are dot has next it helps us identify if there is an element that is existing next to the particular element we are currently at dot next helps us to move to the next element so as you can see dot has next is the ending check for the ending condition while dot next is used earth as to increment or to a next increment to the next value so let's call the question we mainly code first of all the unoptimized version that is the brute-force method version that is the brute-force method version that is the brute-force method that we call it so we'll use the brute force method first I will create a array called count and it will be the same as the size of nums which is storing our data now we will check if a particular number is already there in the array before you implement that particular position in the count array and outside this J loop that we started here to check if that element already exists we will check if I is equal to one which simply means that the element appeared only one so we will store the index position of that particular element and return now is answer let's run this code and check if it works so yeah the food is working the answer is equivalent to the expected answer let's submit and check how much time it took more details so you're 11 test cases passed but it took 2 46 milliseconds which is a lot of time and might be according so it takes 2 46 milliseconds which is comparatively a lot it took thirty nine point eight MB of space that is fine but this is not fine so what we need to do is we need to identify and use some things which can optimize this particular problem so what you're going to do is we are going to call it and put it again so let's reset to the default code now we will be using hash map and the I traitor that we talked previously now it checking is numbers of I is present inside the hashmap as a key or not if it is present then we fetch the value fetch the number of times it has appeared in by inside the hashmap and we will store lumps of I as a key and increment the count install it as value if this is not the case and that means the particular value has a played only once so what we do is we put inside the hash mark numbers of is the key and 1 St value so basically we are telling like this number of played only once and if it has appeared more than once then we what we do is we increment the value and store the number of I ended has appeared we are creating a set or he will be generating like he said as I had told the lengthy explanation part generates a set of keys that have been used inside the hash map and now we can you need to be a greater sect dot I click so what it will do is it will be using this set as the I traitor now we will be learning this loom till the time we have elements left and are set as next now what he is going to do is key is going to push to the next element basically increment to the next value so I if we get King equal to 1 let me stroll and answer a key answer variable let's run the code now yeah I could got finished the answer is same as the expected answer but submit and check how much time it took more details so as you can see all lemon test cases passed and it took on default 4 milliseconds of time however memory usage is almost the same as before I hope you liked our solution please share subscribe like and comment if you have any doubts we will be posting more content soon thank you for watching
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
132 |
Ajay Ko This Is First Watch Activity What Part and Partition When Indians will not be there * That Indians will not be there * That Indians will not be there * That Do Part 1-f happened After this movie Do Part 1-f happened After this movie Do Part 1-f happened After this movie Horoscope These are the people but this is what happens that we all go together All the parties Sacrifice given has happened that the problem is FD Dashrath Singh Celebrate in Problem Partitioning So Happy Rathore Meaning in Harmony with Shabd Cutter Singh Said That Everything Meaning Singh Shailendra alias Ranjit So now what will we do, let us understand by taking an example, what do you call that, then we will use this as an example Will take this ABC is ok, so what we have to do is that we have to find out that on every point that I am ok, on every point like this is on every point interesting that how many number cuts are required for us Inverter 213 number of minimum tax security To that Briggs give Vriksh Singh into different few small earth rooms neither what will we do now we will maintain a one day are in which this length is fine that is fixed that is why side is so close five that in this one day are That we will leave this ray at each point and find out how many numbers of cuts are required up to this point, such as this, how many numbers of cuts are required up to this point, how to make these heartstrings and to fit this entire lion. For into different pattern rooms this is so much request against one in the final no harvest only we had a different lion of cases we have and will take money on the point ok there was a different lion now we have this on the next point so Aggressive Singh was that how many number cut are you zero, this is itself no cut in Param, we are fine, this is next, this is B, so this also in this, I will have to cut from here because this is Param, BPL and the end would be that you are kitna hua one cut, okay. Then we will see this BBC, how many number updates are required in it, the minimum number of accounts is fine, the minimum has to be seen, I am the white disease of you, this has arisen in the feet, you have cut this once from here, this is one from here in the front row. Cut the bar, it is okay in the front row, so this is - so how many cutters, is it okay with two cuts, this is - so how many cutters, is it okay with two cuts, this is - so how many cutters, is it okay with two cuts, then this is this, Eggs Page C in BC Rishikesh, how many cuts are required, if there is cutting from here, then there is cutting from here, just eligible fruit draw. This front room is gone, it is folded, so what are you doing here also, we will make it a button and we will jokingly call it this, whose name we will take, 2 is equal to 10, all the things for this, for the time being, let's go from zero to inch lights. Let's do it, the fifth one will also come and then we need one, before starting in this room, do one today, we need one today, so first of all, here you are, you have done only one on less, it is your birthday, you are a palindrome, it is through, it is perfect. Right, this is a friend, the rest of the time will get wasted, just for the sake of writing, it is okay, now we are here and after the space station, this will be updated, it will be available in the rally, till this point we have got only zero number. But okay, at this point, we just need to turn off the number till this point and then we are here, so here we are here, we will see and compare one who is a friend and guru, then we have researched him and he will not go further. This is someone's one, any1, give everyone, you are there, you will not go further, after here, it will end, okay, you fall for the golden number, how many should we get, we should only get zero, we need only zero and many, this is ours, this is this. So already okay in the feet so I do n't want hard in this case and then we will see also Kho that means we will start from here again so this is also wear hair is not there and here what is it like a yes baby only food That see, the wife is only ₹1, this is two, That see, the wife is only ₹1, this is two, That see, the wife is only ₹1, this is two, after this we will not go ahead of her, so what will be the minimum expenditure here, the minimum will be set for our one A, the minimum cat's previous alleged cry is 200 and you machine is hers, by the way, what is the minimum? If there is one, then this will happen, one is okay, logically you will see this is also tired, minimum, logically also you will see that even AB is adorable, the one is okay, it is okay that one started living in the B.Com room in a pan, which became ours, 90 I, one, 2, F, 2, Ramesh. The power of Britain, remember the record seat and that the DP was public and you will take out the loot. Yes, I am absolutely fine that alien, by the way, DP pimple time, which heroine is the Hindi dip, MP police, play the music of the robbers, okay, then it is done. Done Payal Music Urdu A Mode On A Hindu Woman Hot Ajay That This Is A History Of Video Okay Yadav Up Hum Karenge Phone Nahi Loot 110 Shri Ram Jain A Range Wealth Meaning Of Generation 25 Human Brains See How Easily You Will Be Able To Do You are the one who means that if we come now, what would have happened in reply, we would do the film for a broad for half an hour, where should we take Pranam, where should we go to I Plus One channel, I am Abhi Singh and this I told me. That Kung Fu is pornographic, that is, these characters are matching, keep in mind that the matching lines are very important, they are the backbone of our development, a stagnant tweet has come, a video has been made on this divine night for free, where the Mac keyboard goes and spits out a little. It has happened that you need acid, you see in such a tie, then you complain about everything in written form. For further reading, Greater Friend is I - One and Friend is I - One and Friend is I - One and I had gone to your first place. Well, whatever decision you took, see love, then basically what is it? What have you done, this is also that you are seeing that this has also happened, even in the past, human, we were born to you, then you will check this, okay, I will make this difficult, what have you done, do the placement, so like here, this, then this. What I have set I will wear tubewell is ok first you want it to stay and then you update me here I had an accident I forgot to try I am a fool it will always stay in hydration it will stay ok Is its value, then we will do Tags English Meaning Main Length and Stomach Karoge Absolutely Give Me 080 Bollywood 0 Tags English Meaning [ Tags English Meaning [ Tags English Meaning AHalf The Men In The Arm A K Saath Sanjay Nagar Qawwali Girl Apk Yudh Ho Gaya Phir Last Mein We will cut it, do it like this, Hey friend, sometimes I am a lover and you are sick or injured, you are doing two tablets, but then there were the terms, cutter, I will shoot an arrow at Shahbuddin Dhawan, go away, submit at this time because then dha
|
Palindrome Partitioning II
|
palindrome-partitioning-ii
|
Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**Example 2:**
**Input:** s = "a "
**Output:** 0
**Example 3:**
**Input:** s = "ab "
**Output:** 1
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters only.
| null |
String,Dynamic Programming
|
Hard
|
131,1871
|
389 |
hey yo what's up my little coders let me show you in this tutorial how to solve the lethal question number 389 find the difference basically you're given two strings s and t string t is generated by random shuffling string s and then add one more letter at a random position return the letter that was added to t here are some examples so there's the string s after that we randomly you know to generate the string t they basically randomly shuffled these characters in this case they appeared at the same position but you know it's not always the case they have added the extra character e at the end of the string right our task is to return that like extra character which has been added to the string s after all the transformation to the string have been applied here are some other examples but they're quite similar so the constraints are the following we can always assume that the length of the string t will be equal to the length of the string s plus one there will be always only one extra character at the string t and also both strings consist of lowercase english letters this is what we have guys okay how can we solve this question before i will write the code let me remind you one thing actually i'm sure that the majority of you already know that but still if you're very new to come to programming just in case i will explain it basically every single character has its own unique integer representation let me prove it to you okay for example if i will print out the integer representations of the character a and for example the character 1 i will get something like that so the integer representation of the character a is equal to 97 the integer representation of the character 1 is equal to 49 and so on all the other characters which are which exist basically have their own unique integer representation right let me write the code now and you understand why i have told it to you okay guys basically right one of the possible solution would be the following you define the integer value after that you iterate through the string t you sum up all the integer representations of all the characters from the string t you store this sum as a variable on each iteration you update it and you know and then you will basically have the sum of all the integer representations of all the characters from the string c having this sum you can iterate after that through the string s and basically you know you can deduct from the sum of the integer representation of all the characters from the string s and which will mean that by the end after you will go through these two for loops the variable r will store the difference basically it will store the integer representation of one extra character which has been added and after that you can just take this integer representation of that like one character and convert this integer representation to the character and basically you can return it after that this is what we need to do guys that's basically that's it of course there's some other possible solutions but you know this is quite efficient okay let me run the code now okay it works let me submit cool guys 99 percent one millisecond yeah i think that's it if you enjoyed this tutorial please guys give it a like and subscribe challenge your friends to see if they can solve this question or not and i will see you next video guys good luck
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
70 |
hey guys uh welcome back to pseudocoders uh today we are going to look at lead core problem 70 which is climbing stairs uh this question was asked in amazon 2021 uh panel interview so we are going to do that today let's start by reading the question here uh it says that your climbing stack is it takes n steps to reach the top uh each time you can either climb one or two steps in how many distinct ways can you climb uh to the top so uh your n is value is the number of steps there is the number of steps that are there and then the output is two that means that there are two ways to climb to the top it's either taking one step and then take one step or take two steps directly uh and remember that you can either take one or two steps now let's let me uh explain you this question by the uh with the help of an example here so let's say we have our n as three now we can uh so let's try let's create a tree here let's say we have taken zero steps and we want to reach three in the first step i can either take one step or i can take two steps so it becomes either one three and two three now here um i can again take one step which makes it two so i have total two steps now and then i'll take two more so one plus two is 3 so 3 going back to the left hand side again here i can take one step again which makes it 3 and then this becomes uh with two steps it becomes four three coming back to the right hand side uh here i can take either one step which means three and then i can take two steps which is four and three it's basically adding to the first uh first number here it's the number of steps okay so let's see in how many ways can we reach n we can reach n in which is let's see 3 so we reached the top here 4 3 is not a real number because we only have three steps if we are reaching 4 3 that means that this is not correct 3 yes we reached the top here three again and again four three it is wrong we don't have four steps here so that's wrong so there are really three ways of doing it one two and three so our answer would be three there are three ways to reach the top of the staircase okay so that this particular example the way that we solved it is basically recursion okay so um if you look at it uh you'll see that the time complexity here would be you know uh taking this splitting it into two again splitting it okay splitting it into two again splitting it so it's basically two raised to n because you're splitting it n times right one two and three you see one two and three you're just flooding it three times and you're splitting it into two so that makes the time complexity two raised to n uh now there's uh we can optimize this using memorization and what memorization does is that when we if you notice you'll see a 2 3 here and then 2 3 here again what's wrong with this particular explanation of well for this with the recursion method is that it calculates 2 3 the first time it calculates that oh 2 3 is 3 and 4 3 and then it again calculates the whole thing here on the right hand side so basically it's getting repeated twice and that adds on to the processing and that's why it has a higher complexity and sometimes you might run into issues you know when you're giving coding exams you'll see that you run out of time uh that happens you get a timeout error that happens because of this so we can actually solve this using memorization what we are going to do is that we are going to store this state uh in an array and then when we come across it again for example here we can just use that value instead of calculating it again for this whole um part okay so let's um okay so let's go on to our screen and write some code okay so this explanation let's keep it on the left hand side i think it's gonna go away anyway okay yeah so let's say how we are gonna do it with memorization let's have an array uh let's call it memo uh have the have an array of size n plus one uh so i'm gonna do here n plus one and then i'm gonna now write our recursive function so i'm gonna do definition climb uh i'm gonna take in the first parameter as my step and then this is my top and then i'm gonna pass in my moist list cool now what should be the terminating condition here so we have really three right we want to see if i is greater than n so let's say let's go back to our little drawing oops yeah let's go back to our little drawing you see that if i which is this if it's greater than n then we want to terminate it we don't want to go any further so that will be our first condition so let's write that let's say if i is oops if i is greater than n then what do we want to return 0 because that we are not going to count that number towards our result uh the next uh condition would be if i is equal to n so right here if you see my i is equal to n that means i have reached the top so i want to count that as a valid scenario as a valid uh reaching the top so i'm gonna do if i is equal to n then i'm gonna return one now what i'm gonna do is i talked about using memorization and storing it so if i come across a condition where you know my ad is so if none of those two conditions are true i'm going to see if i already have them in my moist array and my moist list so i'm gonna check if my mo of i is greater than 0 then i would return my memo of i that means that i have calculated it before and i'm gonna just return it why i'm checking greater than 0 is because i initialized my array with 0 so that's why i'm doing that and then lastly what i'm going to do is i'm gonna store my results into my memories and a list which is memo of 0 will be equal to calling my client recursive function two times and what's that two times gonna look like it's going to be i plus 1 right here and then i plus 2 so i'm going to call my climb with i plus 1 oops with i plus 1 and passing in my memo and i'm gonna add it to my climb i plus 2 and then memo and in the end i'm gonna just return my memo of i and in the main function that we have i'm just going to call my method i'm going to do client book 0 n is n and then memo i'm going to pass in my memo so this if you're getting a little confused let me give you an example on how this is going to work okay let's take our example of n equal to 3 let me open my ipad okay so let's take our example of n oops color change okay rn is three okay now let's have a memo list here our list says that we have we are initializing it with all zeros okay let me put it a little here yep now what happens is we call it initially with i equal to 0 and equal to 3 and my memo array list is this i come in i see that is my i here on this line is my i greater than n no it's not it's zero go back to go to the next condition is my i equal to n no then check if my memo of i which means that my uh list at the zeroth position is it greater than 0 no it's not it's currently 0 so what it's going to do is it's going to call this it's going to climb of i plus 1 and climb i plus 2. so that's going to call the climb function okay so how recursion works is you know you have this box that's how i like to do it i like to do two calls though i'm gonna do i equal to 1 n equal to 3 and i equal to 2 and equal to 3 which is nothing but 0 plus 1 and 0 plus 2 which is this i plus 1 and i plus 2 let's go in and expand on this now let's go uh this sorry i plus 1 yeah let's start with this now this is the first function that is going to get called i plus 1 which is i equal to 1 it comes here is i which is 1 greater than 3 no is 1 equal to 3 no is memo of 1 greater than 0 member 1 is not 0 we have all zeros right now okay so it's a no then it's gonna call these two functions again with i plus 1 and i plus 2. so i is currently 1 it's gonna call i plus 1 which is 1 plus 1 2 and equal to 3 which is another box and then it's going to do 1 plus 2 which is 3 and then 3 here ok now let's go to this box it's going to call this one first right i plus 1 which is 1 plus 1 2. so it's going to call this one it goes back it says i greater than uh n is 2 greater than 3 no is 2 equal to 3 no is memo of 2 greater than 0 no not right now it's not 0 so it's gonna again call this two recursive functions it's going to be i is equal to 3 and then the next would be i is equal to 4 and n equal to 3 all i'm doing is adding 1 and 2 to my i okay so then this i equal to 3 n equal to 3 gets called now let's go back to the conditions again is i greater than n is 3 greater than 3 no is 3 equal to 3 yes then it returns 1 so my this little box is going to return oops sorry this little box is going to return 1 right ok so let's go to the other one let's try this box now is i greater than n yes 4 is greater than 3 then it's going to return 0 so we are going to get 0 from this what happens in recursion is that once you calculate something it goes back here and here it goes back now this particular i equal to 2 and n equal to 3 this will be 1 plus 0 which is 1. so this particular box is going to become 1. so what happens is this particular box then becomes 1 so i equal to 2 and n equal to 3 so i equal to 2 0 1 2 this box then becomes 1 right ok now we calculated this box let's go to this box now it says i equal to 3 n equal to 3 go to goes to this particular uh recursion method it says i is greater than is my 3 greater than 3 no 3 is equal to 3 yes it returns 1 so this particular box is going to return me 1. now uh now what happens is if those recursion calls go back to i equal to 1 and n equal to 3 when you go back it's going to do 1 plus 1 since we are doing climb of i plus 1 plus clamp of i plus 2 so it becomes 1 plus 1 this particular box here becomes 2. now let's update our i equal to 1 then i our i equal to 1 really becomes 2 right uh we are done with the processing on the left hand side we go back here we this is returning 2 for us now let's explore the right hand side we go here we see that i equal to 2 and n equal to 3 okay let's see 2 is greater than 3 no 2 is equal to 3 no now we can now the memorization becomes handy it checks if memo of i is greater than 0 let's see if memo of 2 is greater than 0 yes it is it's 1 so we have already done calculation for this particular box and you can see it right here we've already done the calculation and it returned us one so what it's gonna do is our moist list is gonna return one so let's say you return he one from here and like that we are going to save some processing it comes back to the main condition it says that two plus one it gets two plus one which is three it updates um the 0th position to 3 since i equal to 0 and then it's going to return memo i which is memo of 0 which is 3 and that's our answer if you look at this uh if you look at our little t tree diagram you'll see that we there are three ways of reaching the top and that's the answer that we have got so this is the optimized approach let me try and submit it i'm submitting it okay yeah so it's accepted um and the time complexity let's talk about the time and space complexity here since we are only doing processing once our time complexity here becomes o of n because you know we are going through each and every um we are going through each and every calculation just once so that makes our time complexity of o of n whereas our space complexity is basically how much space are we using we have used just one array that's the memorization array and the array size is n plus one and we usually drop plus 1 plus 2 you know during the complexity calculation so it's going to be again o of n so the time and space complexity of this particular algorithm is o of okay so this uh code is gonna be on github i am i have included the link uh below in the description uh please give it a thumbs up if you like this video and please subscribe to it happy coding
|
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
|
253 |
uh this question is meeting rooms too so you're given the array of meeting times intervals so interval I represents starting ending so return the minimum number of the conference room required so this is pretty um I mean it should be pretty easy so the intervals array does not sorted so you're going to sort it so imagine this is zero this is 30. right and in the middle is 15 so yeah so um so the first one is going to be what from 0 to 30 right and the second one is from five to ten so imagine this is five this is ten and this is 15 to 20 something at least right so the minimum number of the room required it actually meant uh how many overlap you have right so this is one this is two so once this finish um so you have another open room uh you know uh you can use right so I'm going to start over again so right now the room is supposed to be zero right now I'm using the first one so I'll increment my room now uh the time if I since I'm using the since I'm using my current Rune so a time five right I'm going to open another room so which is two so at time 10 I finish my room right so I will take from him that one and at time 15 I will use it right so I need to increment so the maximum so we are going to check the maximum for the room right so this is how the solution is right so here's a solution I'm going to talk about two solution the first solution is going to be what uh using the tree map so uh what do I need to do for the tree map so I'm going to say for the starting I will work I will increment by one full ending I will decrement by one and then when I Traverse and I basically Traverse the word the value right so if there is another like 0 15 something like this right and I need to increment the starting so this is what so the room at the beginning right I'm gonna say two right then at time five you uh you need another room right so 0 to 30 0 to 15. and then five to ten all right so you will have to increment just keep increment and then when you finish 10 at time 10 you finish right so you're different by one and then at time 15 You decrement by One but you're also opening uh also opening another room right so this is pretty much idea so I'm going to just start coding so true man and I need to pass in the integer right so for inch interval intervals so mapped up perk at interval is zero I would have to work get it and then meta get old teeth oh Zero by one right you increment by one and this is going to be exactly the same thing but you also want the equipment right and then we'll just keep on track of the value inside the map right so in result you go to zero return result right and I also need a current value the current value so when it Traverse ends now connect the values right result equal to master Max result or current plus equal the now so you just have to keep adding the vowel and then basically uh you just have to check for the maximum so this is a tire I mean this is like a tricky part for coding but it works on the submit all right for the time in space uh this is the time and also the space why because tree map is using the log I mean it's using the Sorting so it's t log t uh I mean you know a t represent the land of the intervals right and this is the time this is also a time so the worst case won't be what the Sorting so t log t and then for the space tree map the land of the interval should be the space where you have to add every single element into the map so all of t for the space t log t for the time so uh let's talk about another solution so another solution is called a sweep line so you're still going to use it as an idea you increment the value for the starting you decrement the value for the ending and then you have to sold it right you have to sort it and then when you sort it then just keep track of flow about the maximum so this is pretty much the same so I need a list of interval to count this what room right and now I'm going to say four inch interval intervals and I need a what I need to say room that I have new in intervals zero with one and this is going to be that exactly the same thing for the word and this is the ending for Nato one right so you just keep adding all right it doesn't matter if there's a duplicate or not doesn't matter because if there is like five so if there is another like five seven all right you still say five one and then five one so you have two offline right so just keep adding and then you need to sort it collection that's sort based on the room and you want to sort from the smallest operators right so a0 does not equal to b0 right and then it's going to be what a zero minus b0 and then if they are equal if layer equal right you need to what still want to be the smallest recorders for the second index A1 minus P1 and yep so let me see yes so um now you need a what you need a result and you need a current count right return result so you're still going to Traverse the room and then result at Max I mean Master Max result and then you need to current plus equal to room at what uh in this one right because this is interval this is a value and this is doable right yes so sorry so pick either one of the solution right so let's talk about time space this is a space right so space is all of t represents length of the interval right and for the time this is time all of T but this one is actually sorting so it's going to be t log t the worst case solution is all of T right the number of rooms which is the number of interval right so the worst case for this one are all of uh I mean Fuller time t log t for the space all of t so let me pause it here all right debugging so these two solutions are pretty similar be honest right so for starting your increment by one for ending your degree by one and then uh this is not sorted but you have to sort right wait let me pause it here all right so this is a sorting so we know when do we need to add right so this is what two and then you do them in one and you give them another one to you right decrement document so you know this should be super straightforward right the answer is two right all right so uh if you have any question leave a comment below subscribe if you want it and I'll see you next time bye
|
Meeting Rooms II
|
meeting-rooms-ii
|
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106`
|
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
|
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
|
Medium
|
56,252,452,1184
|
940 |
hey what's up guys this is chung here uh this time it called number 940 this thing subsequence is number two okay so today i want to talk about this one first because this is like i would say prerequisite or a very similar question uh regarding for the uh for another problem that i'm going to talk about later so let's take a look at this one first so given like a string adds return the number of distinct non-empty number of distinct non-empty number of distinct non-empty subsequences of s right since the answer may be large to the modular right so subsequences are like this right basically you can pick any of the letters right but the relative positions of the remaining characters remains the same right so for yeah so for example abcde is so ace is a subsequence but aec is not right and then you need to return the distinct ones right for example we have abc so that's why we have seven because they're all distinct right and that's why we have seven remember uh keep in mind we don't need uh there's no empty one right so for exa in example two here we have aba obviously we'll have some like this thing uh duplicate once right that's why the answer is six and for three we have um we have what we have we so for number three we have the answer equals to three right so the constraints like it's 2 000. okay so again right so this one every time when you see this kind of modular it's going to be a pretty big numbers so it's a strong hint that we need to use that name dynamic programming to solve this problem right because you know if everything is distinct let's say if all the english letters they are distinct right obviously the total number of subsequences is what is two to the power of and minus one right so that's the uh that's the full subsequences the total number of four subsequences given the length of n a minus one means that we since we don't uh include the non-empty one right non-empty one right non-empty one right because you know for let's say for a and b right for a and b the total is what the total is like a b and a b right so that's the that's a three value here right and then when we add a b c what so why it's a two to the power of n basically every time when we add right when we add like a new numbers uh like a new characters we double the total number of the subsequences right because here for a b we have four and then for abc we have four times two and for abcd we have times four uh four times two again because so how did we get this one because for a b and c right so obviously if we don't include the c so we got to keep everything we have previously right for what we have for the previously two numbers and if we include c that's when we will basically uh here actually we have empty here right so before we have four now we have c here basically everything plus c will be the new one that this by adding this for this c we're gonna have ac bc a b c and c right okay so basically if we don't care about the distinct then we can simply use this one formula right to solve this problem but so for this one we want to oh and here is going to be a dp of what dpi is going to equals to dp i minus 1 times 2 right so that's going to be the state transition function uh if we are ignoring the duplications right of course we will do a minor zone in the end but let's uh ignore this minus one for now right but the problem for this one is that you know we want to remove the duplicates because obviously since we only have like 26 letters we could have some duplications right and how can we end up with some duplications right so for example we have this kind of letters right let's see the current one is a right so we have a here right and then let's say for example we have uh we have some other a's right here okay let's see there's another a here okay and when we calculate the current a right if we just blindly take over everything that we have from i minus uh from i minus one will we'll obviously include some bait uh some duplications because uh let's say we have this one there's another a here right and whatever we have here right class a will be the same thing if we skip everything of this part right if we skip everything totally and we get another a here right so basically as you guys can see we have already like calculated the numbers that's the total numbers of d of this part b four right in which included in this dp i minus one right so if you're just blindly doing dpi minus one times two right so this part will be uh double counting because if we skip the this middle part and if we add this one so basically some part of the previously previous count will be the will be some something that's will be recalculated right if we skip this part and we add a basically it will be duplicated as if we are adding this a so right here when we added 8 here right so that's why uh what we need to remove is this part right because like i said we are we need to remove the duplicate the dup right the duplicate and then what is dop here so the dop is basically is the first uh ladder right from right side when we meet the first duplicate same lighters as the current one and let's say this is j okay this is going to be dup is going to be a dp of what of j minus 1 right because anything on the left will be the ones we need to remove as a duplication and here's j because the definition of dp is what definition of dp is that we ending with the current one what's what is the total number of distinct subsequences and that's exactly what we're looking for right because let's say we have uh let's say we have four total it's not four let's say we have eight total distinct uh subsequences for this uh four letters right and then by adding a we have like an by adding a we have a bunch of others right so basically dpi minus one we include uh these parts right uh with this one but if we and then when we see another a here right and this a includes everything right uh from this dpi minus one including the ones that here right but since we already have a here right so from here to here and from here to here these are duplicated ones right that's why we use we need to find the first same letters from the from starting from here and then we're going to remove this one as a duplication okay so i think that's the basic idea right of this one you know so actually this dp problem it's i think it's a different kind of dp problem it's not like a minimum or maximum or the uh the two pointers or a range dp this is like um a different kind a different category where it asks you to find distinct subsequences so as you guys can see so here's actually this is another problem i want to talk later because these two are belong to the same category right uh cool so let's start coding and we have this one it goes to s we have dp right okay i create a dp with length n plus one because we have a we have what we have a dp uh i minus one right so in order for us not to over to out of the boundaries of the dp that's why i start the dp with uh with length n minus one okay and then for i in range of what in range of one to a minus one right so basically when we loop through the dp here we look through the dp from one base instead of zero base right so this one yeah okay and what do we have so we have the duplications at the beginning duplication will be zero right so how do we find the okay no the dp will be uh i equals to let's write the state transition function here i minus 1 times 2 right minus the duplication okay and then in the end we return the dp of -1 right and then -1 right and then -1 right and then don't forget to do the modular okay right and now let's try to figure out what's oh sorry this one is going to be uh we need to also exclude the empty one right then let's figure out the dp right so another way is what we simply just try to loop through from i to the very beginning right so we start from i minus one right and then we end as to zero okay because this i and j are one based right and then whenever we find so if the s i minus one right equals to s j minus one again right because with the reason we're doing i minus one j minus one is because uh we the i and j they're all one based okay and but as is zero based right that's why we do this or we can pad as we said like another characters to make to change s from zero base to one base so that we don't have to do this minus one here so we have a dup equals the dp of j minus one right if j is greater than zero right else zero and then we break okay so the reason being is because the reason we want to check this one is because the dp0 oh we haven't set up the base case right because here as you guys can see so everything is like it's coming from the dp right so if everything is zero this one will also be zero that's why for the base case dv zero will be one right obviously so dp 0 means that for empty string there's nothing we have one subsequences right and that's why you know when we do this we have to check the j here because actually i think this part is redundant because we stop at one right so this j will always be greater than zero yeah so i think we can just simply stop here because uh when j is equal to one it means that you know let's say we have a b c and a right so when we add here when we look back okay we see okay so there's another a here right so then db j minus one when j is equal to one right so j is equal to one here it's going to be dp zero right so db zero exactly one that's exactly what we need because that's what we want to uh exclude as this one since there's nothing before that you know that's why the duplication for this one is just the a is itself which is one right yep so i think that's it right so if i run the code that oh this one nice small okay submit yeah cool right so that's it right it passed and uh the time compressive for this one is un square right but actually there we can do some improvements to remove this inner for loop right because as you guys can see let's blindly just uh do another in a for loop to check this ladder one by one right and since we're traversing the letters from left to right uh instead of traversing again backwards we can simply record the last position for each character right while we are traversing from left to right so in that way we can we don't have to do a photo here right then what we can do here is that we can simply create like another array so it's called last right so at the beginning everything is zero okay 26. so i put zero here because you know the value we store here will be this i here and where this is in our case is one it's one based right instead of zero base that's why we can use zero as like as a default value otherwise if the i is zero based probably we need to use something like minus one right but zero here is fine so and this since it's because we only have 26 english letters that's why we only need this 26 size uh last index where this the value for this one record what is the last value right because let's say we have a b c and a right so when we reach here when we reach a here right so every time we see a we update this value when we see another a we up this value again so at a time when we see this all we need to do is we simply need to use a to find the corresponding value for this one which will give us the index of this one right and cool so let's just do it right so this so the first let's find the index so the index is going to be order of s right as i subtract a right sorry this one okay and then the j is what j is the last of index right okay now let's come out this one now the duplicator equals to the dp of j minus one right if the j is greater than zero right else zero so here we need to check this one because uh if j is equal to zero it means that you know we haven't seen this letter before right because at the beginning everything's zero right if this one is zero then we since we haven't seen this one before that's why we shouldn't have any duplication here right it's not the same it's not it's different uh from this one okay and yeah i think that's it oh sorry and then don't forget to update this last right so the last index will be what will be i right that's exactly what we're trying to update yeah i think that's it so if i run this one again oops did i oh sorry i minus one okay yeah because every time when you do a like string uh trying to look for string a letter from string you need to do i minus one yeah maybe that's why i said probably if you pat like an any lighter at the beginning of this one s so that you can save all this minus one that'll be easier okay anyway let's submit cool see so this one is even faster because obviously this one is what it's a of end time complexity right because we removed this inner for loop here and so which means this one is even better okay uh cool i think that's it right i mean that's this is another type of dp problem where it will it asks you to find all these uh distinct unique subsequences right so we start from this one but the very basic uh db formula right where is the 2 to the power of n right so that's the how we get this dp state transition function and then the tricky part is that how can we remove the duplication right so the way we're removing duplication is that you know from here right we find the first slider which is the same as the current one and this part will be the parts that we need to remove because from here to here and from here to here the duplicate and cool i think that's it for this one and thank you for watching this video guys and stay tuned see you guys soon bye
|
Distinct Subsequences II
|
fruit-into-baskets
|
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`.
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 "
**Output:** 7
**Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ".
**Example 2:**
**Input:** s = "aba "
**Output:** 6
**Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ".
**Example 3:**
**Input:** s = "aaa "
**Output:** 3
**Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ".
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters.
| null |
Array,Hash Table,Sliding Window
|
Medium
| null |
630 |
hello everyone welcome to quartus camp so we are at the second day of mail eco challenge and we are going to cover another interesting problem today which is course schedule 3 so now we are given a 2d matrix as our input which are the courses which actually points at the duration of the course and the last day to complete the course and we have to return the maximum number of course we can finish within the given time frame and we cannot attend two course at the same time so let's understand this problem with an example so let's go through quickly the given example to understand this problem so in this example the first course given is 100 days course and we have to complete it within 200 day so as you can complete within the 200 day the first course we are attending so consider we are completing this course on 100th day starting from the zeroth day so now we are at the day 100 so if we are going to start any course we have to start that course from the 100th day to complete it so now our second course is of day 200 so if we are starting on our 100th day to complete the course 2 we will take 100 plus 200 which is 300 days so on 300th day you will be completing course one and two so moving on to our third course thousand days duration and we have to finish it off on thousand two hundred and fiftieth day so now if we are attending this course three then we are starting from the day three hundred and on thousand three hundredth day only we will be finishing this course so in that case it crosses the timeline so we can not actually take this course three so we are not including that course into our plan so moving on to our fourth course which is of duration 2000 so on 300 day we are trying to take the course four because we cannot take the course three as the timeline exceeded so again on 300th day if we are trying to take the course we will finish that on 2300th day which is actually which is within the time frame it has given because the course has to be completed before 300 and 200 day so as we can complete the course four as well so we can complete course one two and four so totally three number of courses we can complete within the time frame that is gonna be an output that we are returning so how are we going to approach this problem though it is a heart problem category in lead code once you understand it is very easy to implement so let's go to our implementation part so let's move step by step towards our solution consider this first example we have two courses the course ones duration is 400 and course 2's duration is 300 so let's start considering finishing our course one first and then going on to our course two so we have the maximum number of days here is thousand two hundred so let us have a timeline from 0th day 2200 how many course we can actually complete out of this two courses so if we are trying to finish the first course first starting from the zeroth day on 400th day you will be completing your course one and if you see the timeline given on thousand two hundredth day you should complete your course one and that is also satisfied so now once we finish the course when we are trying to move to our course two the cost to duration is 300 if you are starting on your 400th day because you have finished your course one by now so on 400 day you are starting your course 2 and 300 days going forward you will be completing the course too and once you finish the course two you'll be on 700 because first 400 days for course one and next 300 days for course two but here the timeline given is 500 that is before 500th day you have to complete your course too that is not been satisfied in that case this is not possible that is completing your course too is not possible after completing the course one so now consider the same example that is course one and goes to with the same duration we are trying to take the course two first and then moving on to our course one so in that case we will be completing our course two on three hundred day that is it has 300 duration and we are completing starting from the zeroth day the course two will be finished on 300th day so now the timeline or the last day to finish the course is 500 that is satisfied so now after finishing this we are moving on to our course one which is starting on our 300th day and for next 400 days it goes on and once you finish your course one after 400 day it will be at 700th day so here the timeline to complete the first course given is thousand two hundred which is also satisfied so within 700 days you can complete both the courses that is the maximum you can cover in the given syllabus so what is the intuition we get from this example so if we want to complete as many number of courses we wanted then we have to first consider finishing the courses with less number of end dates then moving on to more number of entities because as we have less number of end days we have to finish it as soon or as early as possible and then moving on to higher number of end days will actually help us to finish more number of courses than doing it in the other way so now we have to pick the courses which are having less number of end dates so how do we do that so we are going to sort the given courses in such a way that they are starting or in ascending order by the number of end days that is the second value of any given array so the first step here is to sort the given arrays based on the end days to understand the second step of a solution let us consider this example so here starting our first course which is of duration three and within five days you have to complete so here the first condition we have to check is whether we can finish it off in five days yes we can finish it off before five days so starting our first course we are going to attend our first course for the first three days so yes after finishing our course two first three days will be occupied so our next course is of 12 days duration and we have to finish it before 16th day so here we are going to maintain a variable time which actually pointed at which day we are right now so after finishing our first course starting from the zeroth day we will be at the third day because it is of duration three so once we finish it will be our third day so now after finishing this course if we are trying to take up the 12-day course then the 12-day course then the 12-day course then after finishing the 12-day course we after finishing the 12-day course we after finishing the 12-day course we will be at our 15th day so why are we calculating this because we need to check whether we are attending this course within the time limit given so for the second course the time limit given is 16 if we are taking up this course then we actually can finish it before its timeline so we are going to take the course 2 as well so once we took the course 2 we will be at our 15th day so now we are moving on to our course 3 which is of duration 2 and we have to finish it off on our 17th day so on 15th day we are trying to take course 3 which is of duration 2 we will be at our 17th day so which is actually the time exact time limit we have given we can complete the course on 17th day so we are trying to take the third course as well so yes we are now at our 17th day after finishing three courses now jumping onto our fourth course now we are at the 17th day and the duration of our fourth course is five if we are trying to add five to the timeline and we will be finishing this course on 20 second day but the time limit given here is 18 so in that case we cannot pick this course because we cannot complete it before the 18th day so now moving on to our next course which is five since we are not taking our course four our five is also going to start from the 17th day and if we are adding three it has to be completed on day 20. still we cannot complete this course as well because it has to be finished on 19th day so jumping onto our sixth course and we are trying to add 4 with 17 so 17 plus 4 will actually give you 21st day and we cannot complete within 20th day so we cannot take up this course as well so here we are missing three courses if suppose we are going to remove one of the attended courses out of these three courses we want to replace one course and check whether we can attend more than one courses in future so in that case we have to choose the highest duration course so that will get so much time so we are going to replace the course of duration 12 and try to take up any other course if we are taking 12 or removing 12 in that case we can finish the course 1 and course 3 within five days because the course one duration is three and course three is duration is two so far within five days you can complete two courses and after fifth day if we are trying to take all three courses four five six we can take all three because on fifth day you will be starting your course four on tenth day you will be finishing your course four and on thirteenth day you'll be finishing your course five and on eighteenth day you'll be finishing your course six so in that case by ignoring the course two of duration 12 we can actually attend five courses but just by attending the course two you can attend only three courses so what we actually did we actually removed or swapped our longest duration course with the shorter ones so that is what we are also going to do in our program we are going to keep track of all the courses duration in a heap so this heap is a max heap so we are going to hold minimum values and push out the maximum values once it is not needed so what we are going to do is we are going to maintain a heap in that heap we are going to push all courses duration that we have attended so if we are coming across any course that we cannot attend within the given duration in that case we are going to remove or swap with already attended course and attend the new course which is of lesser duration so hope you understood the concept let's go for a quick dry run before going to the implementation of code so here i'm going to maintain a max heap which is going to hold all the duration of the attended courses so once we don't need that course or if we found a lesser duration course then we are going to pull out the maximum duration and swap the courses and we are going to maintain a variable time which is going to point at the actual day which day we are actually in so starting from our course one if we finishing the course will be a third day and i am pushing the course number into a my heap so moving on to my course 2 so here the course 2 duration is 12 and if we are adding 12 to 3 then we will be on 15th day yes we can attend the course as the timeline is 16 so we are going to push 12 to our heap moving on to our course three course threes duration is two if we add two will be on seventeenth day and actually we can finish that on seventeenth day so we are again going to push that post to our heap as well moving on to our fourth course where the duration is 5 and if we add 5 to 17 it is going to give us 22. we cannot attend this course before 18. so in that case i'm gonna check if there is any longer duration course we have already attended so if we check that into our heap we have 12 inside which is the longest out of all courses we have attended so we are going to push that wall out of heap and put five to our heap because we are going to attend a lesser duration course and pull out the longer duration course so in that case what happens to our time so here once you added the course 4 to our timeline we will be at the 22nd day since we popped out 12 that is a 12 duration course which means we did not attend that so we have to subtract 12 from our 22 which actually make us to stay at the 10th day of the courses so we are right now at the 10th day so moving on to our course 5 which is 3 so from 10 we are going to add 3 so which actually change it to 13th day so we can attend it before the 19th day so we are again pushing that to our heap now 3 also enters our heap so now moving on to our last course six which is of duration four so four thirteen plus four actually gives us 17 we can finish that before 20th day so we are again going to push this as well to our heap so far also enters our heap so in that case our iteration is over now size of our heap is one two three four five which is the actual number of forces we took within the maximum time frame so five is going to be our output so hope you are understanding the solution so this is going to work in n log n time complexity as we are going to push all our values or courses into our heap which is going to take login time and we are going to sort the given array which is again going to take one more login time so overall is going to take 2 into log n time and we are iterating the given array after sorting which is going to take log n time so overall it is going to take n log n time complexity so let's go to code now so yes as i said i'm going to sort my given array based on the second values of courses so once it is sorted i am going to implement my max heap using priority queue so here i am going to sort the values based on higher to lower because we want to pull out the maximum duration course from over heap so once we are implementing it in queue we have to sort the values in descending order so that when we pull a value or pull a value from our queue then it is going to return the highest duration course so yes as i said i'm going to maintain a variable time which is going to start over our 0th day i'm going to iterate through my given array which is going to take the big o of n time so here i'm gonna take the first course time and add it to my time that is the course of zero index will be having the duration of the course and once it is done i'm gonna add the tour queue because our queue will hold the attended courses and i'm checking if my time is greater than c of 1 which is actually the end date of completing that course if that is the case we cannot complete that course so we are trying to replace it with the higher valued course so that will be at the front of the our queue as we have sorted it in the descending order so we are subtracting the time from the actual day and that's it so once the iteration is done our queue will be having the number of courses attended so we have to return q dot size as a output so yes let's run and try so yes our solution is accepted and runs in 35 milliseconds so thanks for watching the video if you like the video hit like subscribe and let me know in comments thank you
|
Course Schedule III
|
course-schedule-iii
|
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`.
You will start on the `1st` day and you cannot take two or more courses simultaneously.
Return _the maximum number of courses that you can take_.
**Example 1:**
**Input:** courses = \[\[100,200\],\[200,1300\],\[1000,1250\],\[2000,3200\]\]
**Output:** 3
Explanation:
There are totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.
**Example 2:**
**Input:** courses = \[\[1,2\]\]
**Output:** 1
**Example 3:**
**Input:** courses = \[\[3,2\],\[4,3\]\]
**Output:** 0
**Constraints:**
* `1 <= courses.length <= 104`
* `1 <= durationi, lastDayi <= 104`
|
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t.
1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exceeds deadline, I can swap current course with current courses that has biggest duration.
* No harm done and I might have just reduced the currentTotalTime, right?
* What preprocessing do I need to do on my course processing order so that this swap is always legal?
|
Array,Greedy,Heap (Priority Queue)
|
Hard
|
207,210,2176
|
1,283 |
hey guys welcome back to another video and today we're going to be solving the lead code question find the smallest divisor given a threshold all right so in this question we're going to be given an array of integers uh called nums and we're also going to be given an integer value called threshold we will choose a positive integer divisor and divide all the array by it and sum the result of the division all right so basically we're going to be choosing a number and this number is going to be our divisor so what we're going to do is let's say uh this over here is our integer number and let's say we have uh chosen a number three so three would be considered our divisor now we're going to divide each of the numbers by three and then we're going to sum it up okay and that's what we want to do and now after doing that what we're going to do is we're going to compare that with our threshold value so after that we want to find the smallest divisor such that the result mentioned above is less than or equal to the threshold so in simple words we want whatever value there is that is closest to the threshold so ideally we want something which gets us exactly equal to the threshold but if that's not the case we want something which is closest to it but it has to be smaller than our threshold okay so each result of division is rounded to the nearest integer greater than or equal to the division so for example 7 divided by 3 is going to be equal to 3 so we're basically going to round it up to the nearest integer value and 10 by 2 equals 5. okay so it is guaranteed that there will be an answer so we don't need to worry about the fact where we don't have an answer all right so let's just look at this uh question over here real quickly and the numbers we have is one two five and nine so let's talk about the smallest divisor we can have so the smallest divisor that we could possibly have is going to be the number one so why is it the number one so when you have the number one what's gonna happen you divide each number by one and when you divide something by one it stays at the same value so in this case when you divide everything by one it's still going to be same as one two five and nine so our maximum value which we would get is going to be one plus two plus five plus nine which gives us a value of 17. so 17 is actually bigger than our threshold so that means we want to look for a bigger divisor and the reason we're looking for a bigger divisor is because bigger the divisor smaller our answer so for example now let's say we go with a divisor of two so in this case we would do one divided by 2 and that goes to 0.5 but we're going to and that goes to 0.5 but we're going to and that goes to 0.5 but we're going to round it up to 1. so now we have 1. now we're going to do 2 divided by 2 which is also 1. so now we have a total sum of 2 then we have 5 divided by 2 which would give us 2.5 which would give us 2.5 which would give us 2.5 so we're going to round that up to three so in this case we're going to have three plus two so now we have a total of five and finally nine divided by two is going to be four point five so we're gonna round that up to five and now we got an answer of ten so ten is also greater than our threshold so now we're going to change our divisor to three so now we're going to get some value then we're going to do four and so on and so forth but in this case the correct answer is when we get the value five so let's just say uh we have a divisor of four so when you have a divisor of four we get a sum of seven and seven is just right above the threshold and now when we use a divisor of five the sum ends up becoming five okay and that's the answer uh that we're going to end up outputting because that is closest to the threshold while still being smaller than it so now let's kind of talk about how can we solve this question so one thing we could do is we can go through all of the divisors possible and come up with the closest or best solution from that but how exactly do we choose a solution right so what do we what are the bounds to a possible solution so the smallest value like we talked about earlier is going to be one the smallest value is always one and the biggest value of a divisor that we could possibly have is going to be whatever the maximum value is inside of nums so how does that make sense so in this case the maximum value is going to be the number nine so in this case when you divide everything by nine so when you do one by nine you're gonna get zero point something okay but in that case what's gonna happen that just rounds up back to one so two divided by nine is after rounding it gives us a value of one same for five by nine and in that case when you have the maximum number nine divided by nine is also going to be equal to one so that is going to be our upper bound the upper bound is going to be whatever the maximum number is inside of nums and when you divide everything by that number you're going to get a value of one so in this case dividing everything by nine our sum would be one plus one which is well four okay so yeah that's going to be our upper bound value okay so you can kind of see that there is a boundary right between one to nine so to make this a little bit more efficient instead of looking for each and every value so one two three four five six seven eight nine instead of doing that we can actually selectively choose which values we want to find so let's say we start off at the very middle so in this case let's say we start off with 5 and that actually ends up giving us our answer but let's just kind of generalize it so we're going to start off at the middle of our boundary now in this case we're going to get some sort of answer and if that answer is greater than our threshold then in that case we want to look for a smaller sum and when that happens what we're going to do is we're going to move our left or our lower point bound value to the right and the reason we're doing that is because when the threshold or the value that we end up outputting is bigger than the threshold that means that we have a smaller divisor and we want a bigger divisor and if the case is the other way around so let's say the value we've got is too small then in that case that means we're looking for a smaller divisor and in that case what's going to happen is we're going to move our right pointer to the left so we uh only look at the smaller values so you can kind of understand what we're really doing is a binary search because we have a sorted list of numbers and we're just going to try to search for the best possible divisor so now all we need to do is kind of implement it and see how it actually works all right so let's start off by actually defining our two pointers so we're going to have a left pointer and we're going to have a right puncher so the left pointer is going to be the lower bound value so the lower bound value over here is going to be one and the upper bound value like i said is going to be the maximum number inside of nums okay so we have our two boundaries now so now we're going to go inside of a while loop so what we're going to be doing over here is we're going to be going inside this while loop as long as left is less than or equal to our right log the second the left value becomes greater than our right value that means that we have found our answer and we can stop right so the first thing that we want to do over here is we actually want to find out what the middle value is so to find out what the middle value is what we're going to do is we're going to take our left pointer for the left boundary we're going to add that with our right boundary and we're going to divide it by 2. but one thing that we want to do over here is we're actually going to end up doing integer division because we want an integer value and we don't want a decimal okay so now we have an integer value which we are considering to be our midpoint so now whatever the midpoint stands for so the mid value that we have over here is nothing else but the divisor but we didn't get an answer yet so now we actually want to come up with an answer so how exactly do we come up with an answer so to actually come up with the answer first we divide each of the things inside of our area nums by the mid value and then we want to add them all up so let's see how we can do that so we're going to be using sum and over here we'll be using comprehension to actually get that done so what we're going to be doing is we're going to take a number and uh we'll so the num and we're going to divide our number by the mid value so now how do we get our numbers so to get our number we'll do four num and we're going to get it from our nums area okay so one thing that is wrong over here or not wrong but we need to change is when you do num divided by mid we might actually end up with the decimal value but we are only looking for uh integer values and even if it does end up becoming a decimal value we're going to round it up so since we're going to be rounding it up what we're going to be doing is we're going to be calling math.ceiling we're going to be calling math.ceiling we're going to be calling math.ceiling so that way we're just basically rounding it up so math.seal rounding it up so math.seal rounding it up so math.seal and what that does it's going to round up our value all right so now over here we found the sum so we want to check whether the mid value is actually where it's supposed to be or not so to do that all we need to do is we're going to take this number and we're going to put it inside of a condition so if whatever this value ends up equaling if it is greater than the threshold value which we have over here then in that case that means that our value is too big and since it is too big that means that we're going to be looking for larger divisors okay we want we're looking for a larger divisor and since we want a larger divisor we're going to change our lower bound to be equal to mid plus one all right so now we're only looking at the bigger values okay and we're not going to be looking at any of the smaller values so this is that case and another condition that we have is what if this over here is a less than the threshold so if it is less than our threshold then in that case what's going to end up happening that means that we want to look at the smaller divisors so we're going to move our right bound and our right value is now going to be equal to mid minus 1. all right and that should be it so by the ending of this we're going to get our answer and the answer is actually going to be at whatever our left pointer is and that's exactly what we're going to end up returning our left pointer or the lower bound so let's submit this and as you can see our submission to get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you bye
|
Find the Smallest Divisor Given a Threshold
|
reformat-date
|
Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: `7/3 = 3` and `10/2 = 5`).
The test cases are generated so that there will be an answer.
**Example 1:**
**Input:** nums = \[1,2,5,9\], threshold = 6
**Output:** 5
**Explanation:** We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
**Example 2:**
**Input:** nums = \[44,22,33,11,1\], threshold = 5
**Output:** 44
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 106`
* `nums.length <= threshold <= 106`
|
Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number.
|
String
|
Easy
| null |
895 |
Hello Everyone Welcome To Tap Student Ko Maximum Frequency Pushp Similar To What To Do Subscribe To And Sunao Hair Give Example Left assistant Jhaal Sunao Episode Khush Aur Element Pipe Burst Subscribe In All States Will Remove That 12345 Loot 2714 Discuss The Most Frequent Elements The Five Fennel Very Removed And It Happens To Be The Top Most And Middle-Sized Forms Top Most And Middle-Sized Forms Top Most And Middle-Sized Forms Perumon Which Is The Most Frequent Subscribe To Or Listen Unknown Mind Operation Its Nature Trinamun Number And Element Which Is The Element Subscribe Now On Tap Happened Tha on karo e want to see this topic and adventure of and 504 506 a pinch frequency left and the index voids Bihar to find weather its cost but and sunil on giver number 10 now from scooty yes brother property why vikas vihar to take element based on Facts They Need To Order Elements Getting Enough To Play The Festival City Center For Example A Friend Frequency Is Gone And Withdraw All World Sunao Wid U That And Frequency Sworn In It's Entering A President Lut In This Case And Priorities Are Good Stuart Arrange Pest Intense Pain in the first element at the bottom and resettlement and entry ho that this points and right compare dasharath soft and input industrial suno veer subscribe to love you all weapons of five bigg boss-5 appears pause a ki tum love you all weapons of five bigg boss-5 appears pause a ki tum most 532 the best Do n't Forget to Subscribe Skin Doctor Frequency Thumbs Up 200 G This Tube Will Help 523 First and Comes Alive with Synonyms of Wave Play List Previous A Co Input and Interior then subscribe to The Amazing First Look This point also select the first element tip Si hawa mein ghot jhal sa sukha set agua the prostitute hai ajay ko loot lo ki police cannot hold and through with three fatty acids were going to calculate frequency Frequency of development and started to keep track of frequency right angle's first puck media on hua hai ko solve inside frequency set amazed Ajay loot Ajay turn Ajay on Hello friends welcome to right to compress rallies that past first compress with the best Frequency set is fair No obscene frequencies equal to or greater than welding shot based on the third after this indicates which acid attack took root in ascending order that this notification and not equal oil were going to short pitch ball sequence 618 was the simplest compare frequency clear frequencies tarzan match on 231 front intact who pen se z f i maths is tender ko internet based on the index is not private and bases with oo and sunao inko operation reminder first record frequency to hour hai and sunao hua hai loot hua ke All record frequencies wich pic 182 and property ke us point kyun ego into r country can see a loot phone par hai na website par element and stir well ajay ko loot hua tha most in this app hua tha loot lootere index in wich steroid shop finally Bigg Boss frequency in water are subscribe to ajay ko 220 update android step note operation for cooperation with no the first element from the curious going to be the left open hotspot setting tomorrow morning for removing me how to update frequency is a terrible fix 101 number Two Decrement Corrupt Elements Points 128 Hikhoz Dictionary App Ajay Ko Ki Picture White Polling Agent Proof Why Swansea Loot Otherwise Ajay Ko Ki A Loot Ho Tum Ki White Lily Kiran Mein A AC Equal To Null Previous Protest Elements From Which You Can Entertain - This Elements From Which You Can Entertain - This Elements From Which You Can Entertain - This Note Element To Ajay It's True A Simple Result Constructed A Prostitute Slept And Frequency Of A Number Of Frequency Response Team The Best All The Intake Twitter - Elements The Intake Twitter - Elements The Intake Twitter - Elements Near And Wisdom Topper Limit For B Take Song They Will Post Elementary Updating and Frequency Table and Construct Hey Oh Who-Who Jhal Chest Obscene Dance For watching my video like and subscribe to
|
Maximum Frequency Stack
|
shortest-path-to-get-all-keys
|
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the `FreqStack` class:
* `FreqStack()` constructs an empty frequency stack.
* `void push(int val)` pushes an integer `val` onto the top of the stack.
* `int pop()` removes and returns the most frequent element in the stack.
* If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
**Example 1:**
**Input**
\[ "FreqStack ", "push ", "push ", "push ", "push ", "push ", "push ", "pop ", "pop ", "pop ", "pop "\]
\[\[\], \[5\], \[7\], \[5\], \[7\], \[4\], \[5\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, null, null, null, null, 5, 7, 5, 4\]
**Explanation**
FreqStack freqStack = new FreqStack();
freqStack.push(5); // The stack is \[5\]
freqStack.push(7); // The stack is \[5,7\]
freqStack.push(5); // The stack is \[5,7,5\]
freqStack.push(7); // The stack is \[5,7,5,7\]
freqStack.push(4); // The stack is \[5,7,5,7,4\]
freqStack.push(5); // The stack is \[5,7,5,7,4,5\]
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,5,7,4\].
freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes \[5,7,5,4\].
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,4\].
freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes \[5,7\].
**Constraints:**
* `0 <= val <= 109`
* At most `2 * 104` calls will be made to `push` and `pop`.
* It is guaranteed that there will be at least one element in the stack before calling `pop`.
| null |
Bit Manipulation,Breadth-First Search
|
Hard
| null |
791 |
hey everyone today we are going to solve lead problem number 791 custom sord string in this question we are given two string order n s the order string is having all the unique characters and these character are specific in some kind of order and the S string is something we have to manipulate and we have to change the order of the characters in the S string as per the old string it means that there are two character let's say the characters are A and B if a is coming before B in the order in the S A should always be in the um start in the front of B let's say we have two characters A and B if a is coming before B in the order in the S we have to arrange that a is coming before B let's say uh b c we are to picking two characters B is not present in the S we are not concerned about it if U if the character is not present we are not bother about that but all the characters which are already present in s should be as per this order in the order let's say uh A and C if I consider a and C in the order string C is coming before a so in the S we have to do something that c is coming before a so it should be C A D like this so c a d is the not present in the order so c a d is a valid answer so you can return any permutation of the answer but uh make sure that all the characters in s are in order as per this order string so how do we achieve that what we can do is we can use a custom sord function for that and that custom sord function will check whether that character is coming before the another character in order or not and what is the Prototype of that if we are going to use array do sort what does that function require array first of all and a custom sort function and that array should be of characters type which is a wrapper not a primitive type character so you can easily convert this s string to a rapper first and that rapper we can you we can apply our custom sort function and what should be our custom sort function I'm I have written a Lambda for that in that Lambda we are picking two character let's say those Character Are A and B so A and B will be sorted as per the order in the string so a in the string a is having a frequency first of all let's see uh A and B are coming in the string s we have to decide whether we have to sort a or b or Not A B has arrived and in the order string we will see A and B what is the order of a and b is coming before a it means we have to return positive number such that the function know that these two character should be swapped so for the positive number let's say uh what we can do is B is having index zero and a is having index 2 and if I just subtract the index indices of these two element a is having two index 2 - 0 it is a positive two index 2 - 0 it is a positive two index 2 - 0 it is a positive number so what we can do is order do index of a minus order do index of B so here um let's say if two characters are a c I will just uh sort these two character as per the order what is the uh like uh index of a in this order a is having index 2 and C is having index one so index of a minus index of C which is 1 one is a positive number it means we have to swap it means if a and C are encountered in s string so we have to make it C comma a right because C comma a is aligned with our order string so for that I have written this logic and this is the base behind this comparator function if we encounter the positive number we do the swap if there is not a positive number we do not do the SB so by applying this formula we will get all the orders all the characters in string as aligned with the order string and what is the time and space complexity for this function we are sorting s string let's say s is having n character so the time complexity would be n log of N and what is the space complexity there might be some kind of space utilized um by the sort function that can be logo fan in the Java in some other language it might be varying so this is the time complexity I hope you have understood the approach let's write the Let's uh have a look at the code so in the code first of all I have converted this s string to the character array so that I can apply the custom sord function over it and this is my custom sort function it is taking that character array as a input and another one is Lambda the first one is character one character two and those character will be sorted as per the their order in the order string so what we can do is in order do index of C1 minus order of index of C2 so if C C1 is coming before C2 it will be a negative value before C1 is having a lower index C1 will C2 will have a higher index it will be negative value so it mean it is aligned with the order if C C1 is coming after C2 we will get a positive value in that case we are going to sort or we are going to swap those character and in the end I have converted it to a string and return from the function that's all we have to do yeah this is the heart of the code and the time is n log n okay hope you understood the problem thank you guys
|
Custom Sort String
|
split-bst
|
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**.
|
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
|
Tree,Binary Search Tree,Recursion,Binary Tree
|
Medium
|
450
|
322 |
hi everyone today we are going to solve the rit called question coin change so you are given integer already coins and representing coins of different denominations and the integer amount representing total amount of money so return the fewest number of coins that you need to make up that amount so if that amount of money cannot be made up by any combination of the coins just written -1 just written -1 just written -1 and you have an infinite number of each kind of coin so let's see the example so you are given one two five uh coins and the amount of is 11 the output should be three because uh fewest number of coins should be uh 2.5 2.5 2.5 and 1.1 so total is 3. that's why we need to 1.1 so total is 3. that's why we need to 1.1 so total is 3. that's why we need to return three so this is actually a classic dynamic programming problem and it's good to understand how it works and i'll show you how to solve this question okay so let me explain the question with this example so you have coin one two five and the amount is eight and first of all i create the amount list zero to eight so we need to return values here because amount of age and for each amount number i calculate the fewest number of coins to make up for each amount so let's begin um so among zero definitely we don't need a coin so i put zero here how about one so we have a coin one so fewest number of coins should be one how about a month two so we have a point two so the fewest number of coins should be one and how about the amount three and so we have uh every time we have a three choice and uh we have to compare the uh um the fewest number of coins if i use coin 1 this time coin 2 this time or 0.5 this time or 0.5 this time or 0.5 this time and so to do that so first of all um so check the like the number we already calculate so let's say so this time i use the coin one so now amount is three and then this time i add coin one so we need to check the number at point 2 at amount 2 because uh 3 minus 1 is 2 and look at the amount two so we know that the fewest coin number of coins to make up among two is one because we have a coin two and uh so this time i add a coin one to make amounts three so that's why fewest number of coins to make up amount 3 are 2 if i use coin 1 this time and how about using the coin 2 this time so and three minus two is one so look at the amount one so fewest number of coins was one and so i add coin two this time so one plus one and the fewest coin should be two and uh i don't have to think about the coin 5 because of 3 minus 5 is like a negative 2 we don't have a negative 2. so and then compare these two numbers are actually same so fewest number of coins to make up amount three are two so that's why i put two so how about the amount four so same things so if i use point one this time and four minus one is three and check the number here so previous number of coins are well two so two plus one and three so how about using uh coin two this time so five four minus two and uh so look at amount two previous number of coins was one so one plus this time coin two so plus one so one plus one should be uh two points and again we don't have to think about the 5.5 the 5.5 the 5.5 and so compare two numbers so two is a smaller than three so that's why i put two here how about uh amount five so obviously we have a coin five so definitely so only we only need one coin so that's why i put one how about six and if i use coin 1 this time check the 6 minus 1 and the amount 5 so the number is 1 and 1 plus 1 this time so the coin should be 2 so how about 2 6 minus two um so look at the amount four so the coin we need for amount four was two and so that's why 2 plus 1 this time so going to be 3 and how about five six minus five is one so look at one so about the coins number of coins was one so this time we need two points and compare these three numbers and two is a smallest number so i put two here and how about seven so i'll speed up like seven minus one and a two and uh so three seven minus two five and a one so two and a seven minus five and two one plus one two and that's i put two here and then finally i release the amount eight and eight minus one and seven we need point two here and so plus one so three so have a 2 so 8 minus 2 6 2 plus 1 so and 3 we need three coins and how about five minus eight minus five look at coins uh two so two plus one three so actually uh all three so i put three here uh then amount after that so we should return three this time so this is a basic idea to solve this question and it's classic dynamic programming so i'll show you how to write the code okay first of all check amount equals zero just return zero and if amount is less than minimum coins and later minus one and then creates the amount twist db and initialize with amount plus one so you can put the number here right here that is a greater than amount number of amount but uh so but this time uh amount plus one is enough for this question so i'll explain later multiply amount plus one so index start from zero so that's why uh we need plus one to check the num the last number of amount so this process creates a list like if amount is uh eight so list should be like a nine like this and uh so amount zero is obvious we don't have to we don't need a coin so i put a 0 here and start looping so for amount start from amount one and uh amount plus one because we want to there we want to increase the last number of amount then every time we check the positive fewest number of coins so loop looping the coins in points and then do you remember i as i explained earlier so a amount current amount minus current coin is a greater or equal zero then compare the number the furious number of coins so current amount equal mean and the current furious number of coin versus one plus dp amount minus coin and then if after finish this loop just return dp minus 1 so i take the last number of the list if dp minus one is not equal amount plus one so then if the case return minus one so if the last number in the list is amount plus one so inside here that means we couldn't uh find the furious number of coin i mean we couldn't make up that amount with uh with the coins we are given so that's why uh minus little minus one and let me submit it yeah this solution works the time complexity of this question should be a order of amount multiplied lengths of coins and space complexity is order of amount so that's it so if you like this video so please subscribe the channel and hit the like button i'll see you in the next question
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
68 |
Hai gas welcome and welcome back to my channel so in today's video we will see the last problem from arresting top interview 150 so what is the last problem our text justification so what do we do let us understand what is the problem of through statement here Then through the example we will also understand what problem has been given to us and how we can solve it. Okay, so here you have been given one with the word Are of Visiting and one with Next. Okay, what do you have to do in these? You have to form a line by using the word, your name in the line should be equal to the maximum characters of next week and it should be fully justified. Just fully justified means what you will do, you will form this line, it should be the same as given by Maxwell. You need to include as many words as you can with a space. If it is possible then if not possible then how to do it. What do you have to do? Take as many words as you can and space between those words. What will you do? Will you distribute the space evenly? If it is possible, then how will it be distributed? What will you do? The extra space that will go back to the left, you will sign it on the left. OK, if you are last, you have only one word. So, how to keep it, what you have to do is, whatever space is left is yours, what will you do, keep it on the right side, okay, not on the left, how will we keep it, right, if it is our last line, then what we have to do is even distribution. What we will do is we will keep a single space between two words and whatever extra space is left, we will give it at the end i.e. we will give it at the end i.e. we will give it at the end i.e. we will give it on the right side. If you have not understood till now, then someone. It doesn't matter what we do, you understand through the example, we have a problem, okay, what do you do, read this statement carefully, understand, if you don't understand, then it does n't matter, we understand you through the example, okay so now Look, what is given here we have given you a ray of sting, okay, this is given to you, it means that in the line you will become, you should have 16 characters, how many 16, so let's start from here. Are 1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 Okay 16 Now what you have to do is take one word at a time and put it here, first see how many words can be made in one line here in the first line. So give t here yes give dog i give dog s give dog then take a space give this ok take n it will be done then give space here now the example is 123456789 10 11 12 13 14 15 16 what happened till now Okay, now you are seeing here that we are not taking the example here completely, so what will happen in this condition that we will not take the example here, we will get it in the next line. So what do we do, we will remove it from here, okay we removed it, now you see that here your extra space is getting too much at the end, so what you have to do in this condition is to try to distribute. If it is possible then let us see whether it is possible or not, then what is the land of all the words, it is four plus tu hai plus what is the land of all the words, it is four plus tu hai i.e. the total is of one length and if we tu hai i.e. the total is of one length and if we tu hai i.e. the total is of one length and if we look at the extra space, then how much space has gone to the back. Back gone, you have 8 back gone, both of them mixed together will be 16, then the space is your at and the word is the length of the word. Okay, now you see what comes. If you can evenly distribute the space among the words, then if we divide the at by four. Why do you say se n tu se? What is the total number of words here? How many words are you taking in the first line? You are taking 1 2 3 but you will keep space behind the two words i.e. you divide by 3 - 1 and will keep space behind the two words i.e. you divide by 3 - 1 and will keep space behind the two words i.e. you divide by 3 - 1 and see it becomes 4. Take out these modules in it and see whether this is happening completely. Yes, it is happening completely, that is, we can keep four spaces between two bodies. This means that if this happens, then what do you have to do now, which will be done here, right? You have tested this, now the line that will be formed in yours will be formed in this way. You have taken this, now you can distribute it evenly here. It is possible to do it here, so let's take the space. 1 2 3 4 We have taken it. Hey, what happened? Wait, that's done, 1 2 3 4, okay, now we take this here, then take four space 1 2 3 4, now here we take N, this is done, this is how your first line has been formed, see first. This is the line, this is after this, there is space, then there is space, and once it is done, you have to evaluate the distribution in this way. Okay, if you look here, this condition could have also happened that what would you have here, your suggestion. If the pass is 13, then it is okay, then if you divide by you, then here you get one, it means that it cannot be an even distribution, that is, one will be divided together, one will be divided into six, it means that it is okay, then you will get 7 spaces. You have to keep it on the left side, this is the statement given to you that whatever will be consumed, there will be no extra space left, you have to move it towards the left, not towards the right, okay then who will be on the left, this one will be right, neither will it be left. If you have to shift it from the side, then here it can also be the case that there are two words here. Suppose mother, you mean three, you can put a space here, there is one word, there is a word, you have to put a space here, you have to put one. There is a word and one has to be inserted here from this side, three spaces have to be inserted here, okay and your evenly distribution is happening in all four, okay and your name has gone back in the extra, two, so you must have space for four here. Now two spaces have gone back, so give one to this one, then this is how you have to do it. Okay, so this is what I have given you in the problem statement, so you have to keep this in mind too, but how come this did not happen here? So I told you, let's do now, let's make the second line, what is the second line, your example of text, okay, let's see, let's take 16 characters first 1123456789 10 11 12 13 14 15 16 Jin Lo 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Okay now we'll do the example now we'll do the text test after that o f an assumed space t a x t now here's an extra space gone back okay so now any words so you here If you ca n't enter then what will be the length of the word here? The length of the example is your space. Now see what will happen in this way that you have two words here, how many total words are your three and 3 is your word here. What is the length of the word? It has become 13, word? What is the length of the word? It has become 13, that is, three spaces have gone back to you. Now we will try to do the value distribution. If the word is three, then divide three by 3 - 1. If you do 3 / 2, then this is There - 1. If you do 3 / 2, then this is There - 1. If you do 3 / 2, then this is There will be space of one. Okay, one divide 11 space will go between two words but we will see what models will come out. Is it zero? No, it is one A, that is, it is not evenly distributed, that is, if this extra will be left for you, then what will you do? What we have to do is that you have to put one space between each word, give one to this dog, that is, the first one gives one dog, the second one gives one dog, there will be three spaces, so we have to make it in this way, so I remove it, then what should we do? What will be our space between the first two words? There will be two and there will be one between the second. Okay, now let's remove it. This is the example. We have to keep two between it. Then we will keep here pay off here. Here we have to keep one. T A X T This We have made it ok now we have to make this last line so the justification has gone back once Apna 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1234 56789 10 11 12 13 14 15 16 ok just justification alone j u S T I F I C A T I O N Now back gone here extra space three there is also a dot two back gone Okay this is two back gone now this is your single word and this is yours na n pe ke yours If you say, this is your last word, okay, this is the last word and you have only one word, so whatever extra space is left, we will put it on the right side, not on the left, okay, we will not take it here, like we will not take it here. We used to say that in this case, if even distribution was not happening, then whatever extra child was there, we would give it to the left side, but what can we say in this case, we have to leave it on the right side only, okay if the mother suggests that In your last line, what happens in the last line is that there are two words, you and ant, something like this, okay, this is five, okay five, yours is getting to him, your total is 16, you have to make a length line from these two, so how to make him What will you do? You guys have a space dog near it, A and T guys, after that, as much as we went back to space, give it a dog, here on the side, this will be an application for the last line. One, your word will be there when it remains one, then what will be your last line? What happens is that when you reach the last line, what are you doing? Give a space between all the words that are coming in the last line and whatever is extra back, shift it towards the last. Okay, so in this way you So you must have understood what the problem is, now how will we solve this problem, so as I have shown you, we are going to solve it in this way, so what will we do, first of all we will see our word in the line. How much can it go, how much length will it go, how many words will be formed, we will have to see that, so when we are making the line, look here, like here, what we were doing was put this, then put this space, then put a space, you can see it only by removing this. Yes, it will be more correct, you will be able to understand well. Yes, right now we are testing here how many words can we have? Okay, now here we have given a space like this, we have given a space and we have given this which is based on X.A.M.P. Okay here. this which is based on X.A.M.P. Okay here. this which is based on X.A.M.P. Okay here. What you basically have to say is, take a word length, a variable in which you see how much word length is happening right now, okay, so what we will do in this, we will set from here, what is its four, okay and will keep a condition 4, so you guys. Same word length plus one space, you are putting it, put one space, then look at the next word, two, then put one space, then what is the length of the next word, two is done, then put one space, then what is the length of the next word. Yours will go here, look at four one five you seven plus one, what will happen to you 10 11 and as soon as we put this, what will happen to the example? 1 Second, if you add the word seven example with an extra space, then your What is it doing? It is going to exceed 16, so it means that we do not want to take this example, so look at us like this, when we add in it, we will keep looking, in other words, we will take a loop. Okay, starting from here, we will go till here and how long will we go until we cross this 16 Let and what will we do in this word length, we will keep adding the length of this word, then it will become four, then this What will happen to you, then what will we do to this, will we add to this, what will we not add, because here we will already check that if it is going to be 16, then what will we do in the word length, we will not add to it, okay, so this In this way, what will happen to your word length here, you will know how much length is going to be in your first line, how much length character is going to be there in any line and how much space is going to be saved, then we will calculate the space with next minus one line. Isn't it because look here, your length of the word has become 4 2 6 2 8 and your maximum word has become 16. This is done, people, by doing 16 - 16. This is done, people, by doing 16 - 16. This is done, people, by doing 16 - 8, the space will be used. Now can we do equivalent distribution of the space or not? If we can, then how will we find it? So see, here we find out the word length. 8 space is how much child is your 16 - 8 back and how much is the word? your 16 - 8 back and how much is the word? your 16 - 8 back and how much is the word? How will you How much is the word? How will you know this? So here I am here. Start with 'K' know this? So here I am here. Start with 'K' know this? So here I am here. Start with 'K' and take 'K' from here, 'K' will go to ' and take 'K' from here, 'K' will go to ' and take 'K' from here, 'K' will go to ' JCP', JCP', JCP', so what has happened to you, 'It will become yours', so what has happened to you, 'It will become yours', so what has happened to you, 'It will become yours', then in this condition how will you find the word 'J- then in this condition how will you find the word 'J- then in this condition how will you find the word 'J- I', people will find it, so 0 1 2 I', people will find it, so 0 1 2 I', people will find it, so 0 1 2 3 - 0 By finding from here, people - 0 By finding from here, people - 0 By finding from here, people got three lengths from a mine, I got it, okay, now from here, the space is getting distributed or not, how much will be your space between any two words, okay, space between two words. Let's write down, will we divide it, will the email ID be distributed, will we apply modules to it, from here, if it becomes zero, then we will understand that this validity of ours is being distributed, so what will we do in this manner, which I was telling you now. We will start creating the line i.e. new string, now you will create the first word i.e. new string, now you will create the first word i.e. new string, now you will create the first word from here, people have added this is the space that you got, here you are taking this much space, then you are adding this, then people are taking this special, then you are doing more. We have to go till here, we don't have to go beyond that, okay, as far as we go, we have to add it till we reach here, we have added it here, so in this way we will make a line, you know this. It will work, look here, this will help you know the number of words, what is the minimum word length, how much space is left behind, how much distribution can we do among the words, we will divide it and the extra space, whether we have any child or not. So here, whatever value you get here, its value N will be ours, so what will we do with it, we will distribute it towards the left, one by one, okay, we will do it like this and if our K reaches N, then we will understand that This is going to be our last line, so if it is going to be the last line, then we will give the space between the words one by one and what will we do with whatever extra space is left, if we give it in the last then we will give it on the type side, okay This is how we will do it, here the word is ours, so we will take whatever word is there and whatever extra space is there, we will add it last here, so I have told you the formula to find it here, in this way we will What will we do if we solve all of them? So see, let me understand you through the code. Look at what we have done. We have taken this in which we will leave the final answer to ourselves. Make a line so that i is your < n, till then you have to your < n, till then you have to your < n, till then you have to do this in this. What are you doing? Take the word length, word dot, word i dot size, you and G, you start with i+1, size, you and G, you start with i+1, size, you and G, you start with i+1, okay, what we were doing here, while keeping K going forward. From here what we will do is this line length + word size plus k minus line length + word size plus k minus line length + word size plus k minus i.e. the extra space we were i.e. the extra space we were i.e. the extra space we were taking is ok if we give our next with then what will we do add word dot size on the line left We will do this plus and we will keep doing this plus. As soon as this condition exceeds ours then we will not add it. What I was telling you here is this condition and on the word we will add it as long as we have less place. Okay. We have done that, after that you have to find the number of words, then the mines came which I told you about time, then you have to find the number of space, then next with mines, you find that, now people, if you are making a line, then you are making a line. How do you have to keep in mind that when the number of words is one and G reaches your last i.e. N, words is one and G reaches your last i.e. N, words is one and G reaches your last i.e. N, it means that you are making the last line, then what you have to do in that condition, if there is a word in the line then you take it. Apart from that, if there are any other words, keep them with one space each. Okay, the one that will go from your I Plus One to Lee, keep them with one space each and what do you do, whatever extra space is your child. Meaning, whatever child is there in its extra space, you keep it on the right side, that is, if you add it in the last line, then here people will size it as Next with Minus and this space means the amount of line that has been made so far and the amount that has gone back on the exercise. By subtracting from max also, you will know how much space has to be added in the last one. Okay, so this is the way to add it. Otherwise, what you have to do is to find the space between the words, which is the number of spaces divided by the number of words - 1. Whatever I divided by the number of words - 1. Whatever I divided by the number of words - 1. Whatever I told you here and despite your even distribution, if there is any saving of extra space, then take out that too. We will take the line word i, let's go from i+1 to k li, give k i+1 to k li, give k i+1 to k li, give k till k + + and what we will do here is to put till k + + and what we will do here is to put till k + + and what we will do here is to put a space in the line, a space between the words, which is the word which is going to be evenly distributed, you have to do that much. If the extra space is your back, then what you have to do is to add that one in the line. Okay, you have to keep doing the extra space, that is, on the left side, the one on the left will keep getting it one by one until it is finished, okay. We don't have to distribute it evenly, what do we have to do, if it becomes three with the supposed extracts, avoid your tax is five, then you can evenly distribute the space between them, so you dog, give the extra child to him one by one, okay. This is how we will do it and in the line we will add the word OK, so I hope you have understood this, meaning finally we will insert I in the answer line and make it like a tree, so this is how we have to make it. Okay, so what I do, see what is ours in this, you see what we are doing is visiting all the strings, so whatever happens here, your time complexity will be on, okay and extra space, you are doing that. So that will also be on so I hope you would have understood this. If you liked the video then please like and subscribe. Thank you.
|
Text Justification
|
text-justification
|
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left-justified, and no extra space is inserted between words.
**Note:**
* A word is defined as a character sequence consisting of non-space characters only.
* Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`.
* The input array `words` contains at least one word.
**Example 1:**
**Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16
**Output:**
\[
"This is an ",
"example of text ",
"justification. "
\]
**Example 2:**
**Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16
**Output:**
\[
"What must be ",
"acknowledgment ",
"shall be "
\]
**Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified.
Note that the second line is also left-justified because it contains only one word.
**Example 3:**
**Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20
**Output:**
\[
"Science is what we ",
"understand well ",
"enough to explain to ",
"a computer. Art is ",
"everything else we ",
"do "
\]
**Constraints:**
* `1 <= words.length <= 300`
* `1 <= words[i].length <= 20`
* `words[i]` consists of only English letters and symbols.
* `1 <= maxWidth <= 100`
* `words[i].length <= maxWidth`
| null |
Array,String,Simulation
|
Hard
|
1714,2260
|
1,884 |
all right let's do my code uh one sec good there we go all right so this question um i did yesterday was pretty difficult to get my head around but uh so i'll try like my best to explain how it works so you're given two eggs and you want to find out with certainty what the value of f is and the value of f is the floor number such that um any egg dropped higher than floor f it will break but any egg dropped below or equals f will not break okay so for example if we have one two three fours so in this case n will equal to three we could try to drop on floor two so this one here dropping on floor two and let's say for example that breaks if it drops on if that breaks then that means i don't need to check three four three i only need to check for one with the other egg because i only have two eggs and then i drop it on 4 1 and then if that breaks then i know the answer will be i know that f will be equal to 0 because since it dropped on full one f is one less than that and the case that where it didn't break so if you dropped on four two and it didn't break um that means i only need to check three i mean actually in this case i know for 70 it has to be three because it's the last one so the number of moves in this case would be at most two in the case that it doesn't break then i have to drop one on here and one in here and so answer for int three if we pass in three to this function would be two so let's do it one two three there's something with some more examples so this is uh we kind of found that this is two if there's just one floor it's always going to be one right if there's two floors um let's actually look if there's two floors um we could try to drop on four two if it oh wait a second if it drops on floor hmm i just realized the full two might the answer might be one so i thought it was two um okay let's take a look yes if i try to drop on four two and it uh it breaks and then try dropping four one then i have to i don't know if it's if f is equal to one or zero still so it'll be at most two drops so this will be two okay so it's very confusing like to get your head around and um we can continue this so for four so one two three four um okay so let's try solve this problem using dp because um i mean actually let's take a look it's a thousand so an n squared approach would work um n goes up to a thousand so let's try solve it using dp um how would dp work though so we need to for dp to work we need to find a sub problem so for exa for this example one two three four let's say n is equal to four what's the sub problem so sub form is actually kind of hard to see if you if we just consider dropping on one floor so let's say we drop on full one and there are two cases either the egg one the egg breaks or it doesn't break if it breaks then i know that the answer is zero and so that's trivial but that's so that wouldn't be the answer i mean for this case if i drop on for one because i want to know the maximum number of uh moves so we have to consider the case where it doesn't break because that'll give you uh more moves to how it have to do determine with certainty that what the value of f is so we have to assume that it doesn't break on one because it's too trivial to assume that it does break so we assume that it doesn't break and that means we can use a sub problem on here because if it doesn't break that means i still have the egg i can still reuse the egg that means i still have two eggs to do on this sub array and that's size three so that means i can use this sub problem here to find out whether um uh to find out the maximum value i need to figure out with certainty what f is in this sub array so that's two so the answer would be 2 for here but i've also already tried this so that's plus 1 and so the answer here would be 3 right so i tried this which is one answer and then sub right here which is i get the answer from here which is two okay what about the case okay that's not the i that was for the case where i tried on this one on break dropping the first egg on one but if i need to consider all possible wait places i can drop the first egg so for example here let's try dropping on four two on floor two oh no actually this uh it's like the same so if i drop on floor say three and it doesn't and it breaks if it breaks i only have one egg so that means the only way to figure out what f is um i would have to try to drop an egg on each of the low levels because i only have one egg i need to drop on floor one if it doesn't break then i have to drop on four two and that's the worst case scenario so then total number of drops would then be three for this sub array here and i also have to consider the case of course if it doesn't break on four three which means um i need to test on this sub right here so it'll be one plus um whatever this size of this sub array is which is one so it's one plus one which is two so this uh the right sub array will give me two and the left subarray will give me three and so the i need to try to get the max of the left sub array size of the left actually yeah left versus the right where the right is equal to the one plus the dp um one plus the dp of the size of left of right subarray so let's say for example this is j this position is j and we have so that means the size would be um n might or in this case let's say the size this is position i then we have i minus j here and the left is just equal to j so actually just replace that with this dp i minus j all right so then i need to try find the min of this for all um values of j so i'm trying out all levels to see and this is for dpi because i'm just doing this is the full sub problem of size four then i need to find it find if the sub array is if the actual problem is bigger then i would have to find out what dpi plus 1 is and so on actually let's run through this problem here again using this formula here so if j is equal to let's say j is equal to one you start j equal to one then that means i'm doing the min doing the max of um j i'm doing one on one plus dp of in this case four minus one and that's equal to okay so four minus one is going to equal to um three so that's um final size three which and dp of three is two so it's two plus one which is three so it's max of one and three which is three let's say j is equal to two now so we have the max of two and one plus dp of i minus j and i is always 4 x minus 2 so that's equal to dp of 2 which is 2 plus 1 is 3 so it's max of 2 and 3 which is still three and let's do j is equal to three now so that's the max of three one plus dp of four minus three which is equal to so we're doing the max of dp one plus one which is two and three so next is three and let's do lastly four we have max of four and one plus dp of four minus four and let's say that means we have to add a zero here so it's going to be max of four and one plus zero which is just four and then taking the min of all these we get a three okay so our dp would be a vector um like this of size n plus one and let's initialize everything to max uh into max and then we have to go through for all i what's i uh so i will go through starting from one eq from one to all the way up to i less than or equal to n plus i and our j will start from one all the way up to i as um all the way up to i yes so into j is equal to one j less than or equal to i plus j i think and we need to do the base case um so the base case would be dp of zero is equal to zero let's do dp of so answer would be dp of i is equal to the min of max of j um and one plus dp of i minus j and at the end return dp of n okay so i didn't really check the brace case properly so let's do that for the zero here i is equal to one and we have j is equal to one as well so the we're doing dp of one is equal to the min of the max of one and one plus dp of one minus one which is just zero so that's max of one and one which is equal to one so that also works let's give that a go um should be the min of dp value itself and relax okay so let's test on the largest input they have one thousand okay so i've done this before i think this is clean than my previous solution okay so i get 109 milliseconds that's quite slow compared to everyone else so there are better solutions as you can see down here so this is an n squared solution but there is also a linear solution so if we keep doing this and it's a bit hard to see how you get the linear solution um but if you keep doing this you'll find that this is actually 3 and for 5 we get three again for six we get three again for seven we get four so you'll see can i see a pattern 10 we get 4 again 11 we get 5 and so on and so forth so you see what's happening we have one we have two twos we have three threes we have four fours and it will keep going like this so how do we utilize this fact okay so what we can do is we could just sum up these values as we go along so um we'll start i from let's just say that we have a i incrementing um one by one so we have i equal to one two three four and as we go along we accumulate into some value k the sum of these values so we can get the sum of these values like so it'll be 1 3 6 10 so on and so forth and as soon as say for example n is equal to seven as soon as we hit a value as soon as k gets a value that is greater than seven in this case ten then we return what i is yeah and that's basically doing what um basic utilizing the sequence here so let's try that so let's just go increment i starting from okay so i need to use i later on because what i need to return so uh let's say it's i is equal to starting from one i think yes so i need to say all i is less than or equal to n will it ever equal n though if n is equal to one then the answer is one n is equal to two answer is two and yes i need i think i need to go up to including n and okay what else do i need to do so i need to include accumulate some value k starting from zero so i need to do k plus equals to i and then say if k is greater than or equal to n then break and at the end just return i okay it seems to work let's try with uh one and two okay give that a go so that's a linear solution okay still quite slow i mean it's quite surprising that uh still it's way better than the fool though so there's actually a constant solution to this and it still it utilizes this pattern again so you know how we are summing up these as we go along we can find any sum in constant time um using a formula so you know that the sum from 1 plus 2 plus all the way up to i let's say x in this case is equal to x times x plus one divided by two okay so we know that let's say for example our x in this case our mystery x is equal to 4 and we want the sum k so if i plug in 4 here i'll get 10. you want the first value of x such that it's greater than or equal to n because this one that's essentially what i'm doing here right if n is equal to 7 the first value that's greater than um n is 10 and that comes from using four so if i find x in this equation then i can find what i is sorry so in this case it's a bit confusing x is equal to this so i need to find x so to do this i you can use quadratic this is a quadratic if you expand it out so if you so this looks like x squared uh plus x greater than or equal to two n okay but we can simplify that to be minus two n rather than zero and so do you remember your quadratic formula is a minus b plus some plus or minus um the square root of b squared minus 4 ac all over 2 a ok so and that's for the case where you have ax squared plus so a times x squared plus b times x plus c is equal to zero let me if we have this equation then x will be equal to this well this is plus or minus so there's two roots but we just need to grab the positive root okay so our x is going to be equal to minus um b our b in this case is one so that's just minus one plus the square root of one squared which is minus which is just one uh minus four times a times c a is one c is two n minus two n so minus four times minus two n is plus eight uh n all over two and a is one so that's so this should do it this will give us the positive root if this was minus of course we'll give the negative root because our square root is always positive so let's give that a go so let's see what happens if we plug in uh n is equal to seven we get minus one plus the square root of one plus eight times seven and all divided by 2 i get 3.27 and all divided by 2 i get 3.27 and all divided by 2 i get 3.27 so x is equal to 3.27 so 3.27 is so 3.27 is so 3.27 is not really what we want 4 but it makes sense that it's less than 4 because x has to be 3.27 to x has to be 3.27 to x has to be 3.27 to 4k to be around 7. so to solve this problem all we have to do is take the ceiling of whatever we found here to get four so actually you want steel of this let's do that um return that so let's try with seven okay we get that and get one thousands here we get 45 okay and this is the constant time solution and finally we get 100 this memory let's just ignore that there's no way um yeah there's no way i'm using that much memory
|
Egg Drop With 2 Eggs and N Floors
|
minimum-changes-to-make-alternating-binary-string
|
You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`.
You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**.
In each move, you may take an **unbroken** egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves.
Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is.
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** We can drop the first egg from floor 1 and the second egg from floor 2.
If the first egg breaks, we know that f = 0.
If the second egg breaks but the first egg didn't, we know that f = 1.
Otherwise, if both eggs survive, we know that f = 2.
**Example 2:**
**Input:** n = 100
**Output:** 14
**Explanation:** One optimal strategy is:
- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.
- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.
- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.
Regardless of the outcome, it takes at most 14 drops to determine f.
**Constraints:**
* `1 <= n <= 1000`
|
Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.
|
String
|
Easy
| null |
1,002 |
hi my name is david today we're going to do number one zero two find common characters this is an easy level problem on lead code and we're gonna solve it in javascript so this is kind of a long problem it took me a while to figure out but basically the input to understand it we get input is just an array of words and we have to find the common characters in it so e l and we turn the in an array like each character and how many times it occurs as the minimum amount between all of them so we're gonna the key things is that we're gonna use ascii to translate these and we're gonna have an array of 26 indices and create a count for them for each one of them so basically the notes is that we're going to use ascii to keep track and create array of 26 indices and keep count of how many times they occur so that's the basic idea and then we have to compare and get the minimum amount of it so just to get started we'll create an output equals an empty array which is what we're going to return at the end and next we're going to create an array an empty array of 26 indices and we're going to use this to keep track of the count in the first word common char equals this is creating a new array of 26 and then dot fill it starts off with zero so we can see we can console log this and we can see a 26 an index of 26 and each of this represents a letter and it's going to count for each one of them so next we have to fill that array out with the count for the first word plus we can use that to compare it to the other ones so what we need to do is that we need to loop through it so for let i equal 0 i's less than so this would be the first word so a index of 0 dot length i plus and inside this we have to create the index grid the count so count equals and how we're going to do this is we're going to get the ask key for each one of them so if we did a i zero all right so the letter of each one and we need to get the charcoal char code at and then we can get the difference because minus it from the letter a so we can get the accurate account so string of a dot char code at so just so you can see it if we get a console.log it's going to if we get a console.log it's going to if we get a console.log it's going to get the difference of it and it's going to keep the count so these will keep the count of what we need to do this is the indices that will have a value so this is b the second next to b so we know that we increment it once and then the fourth index and the limit then text we can do that twice and then the first index increment so what we need to do is we increment common char count and now we can see if the console.log and now we can see if the console.log and now we can see if the console.log common char we should get the index and then account for it seeing these that account for a ps ones b appears once e l appears race so now we have to compare it to the other ones so we need to do another loop for that i equals so we don't have to do the first one we can do the second one i is less than a dot length i plus and inside this we basically have to do the same thing for that for each one we have to create an entire new array like we did here but for these other ones so we can compare it so let me i'm typing to make more sense for it but j equals zero j is less than a dot i we don't need a dot i dot then j plus and for each one of these we have to create just another one of these so let common tap chart equals another array and now we fill it up so actually this disco will go before this so now we have this and then we're going to update this each for each word we're going to update it so we do let count equals like this the same but we change this to i and this to j and then we can just common plus common char count and as we can see if we cancel all this we should get the two other ones for the example there we go typo there now we're going to have to compare these to the ones we have original so we'll have to do another loop so now we do another loop for let and loop through the original common char that k equals zero k is less than common char dot length k plus and now we do k uh common char index of k will equal to the minimum because we have to find the minimum math.min of each one of them so it'll be either what we have in the original one or the new one and after that we can see console.log and after that we can see console.log and after that we can see console.log common chart so we can see that it got the minimum value of both of them yeah so we see e-l-l is the minimum when yeah so we see e-l-l is the minimum when yeah so we see e-l-l is the minimum when these gets counted so now we have to translate this to that so how we're gonna do that we gotta do another loop for the length of the common char that i equals zero i is less than common jar dot length i plus and now to keep track of multiple ones we have to do another while loop here and we saw that the one has if it's greater than one we have to do something well common char greater than zero we will decrement each one as well so while we do that we reverse it so first we have to push it to the output so output that push and what are we going to push the reverse of it so string dot from char code will be i plus and we have to get it back from here and then we comment our key per minute so that is going to get the characters and then we return output great yeah so the time complexities since we're doing nested loops within these will be o n squared and also was the space complexity we're creating multiple arrays within this depending on how long it is so o of n squared so that is how you solve this problem thank you
|
Find Common Characters
|
maximum-width-ramp
|
Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters.
| null |
Array,Stack,Monotonic Stack
|
Medium
| null |
1,446 |
hello viewers welcome back to my channel hope you are doing great if you haven't subscribed to my channel yet please go ahead and subscribe I have created bunch of playlists to cover various categories of problems such as linked lists trees graphs dynamic programming breadth first search depth-first search depth-first search depth-first search binary search and so on so please check them out I have uploaded the code for this problem to github repository you can get the link from the description below this video let's jump into today's problem consecutive characters given a string s the power of the string is a maximum length of a non-empty sub string maximum length of a non-empty sub string maximum length of a non-empty sub string that contains only one unique character written the power of this range so basically we are given with a string and we need to calculate the power of that string so the power will be calculated by the single character how many times it actually occurred writes a maximum length of a non empty string that contains only one unique actor right so one character should be appearing multiple times so what is that maximum length is what the answer for this particular thing as the power of the given string so let's go ahead and look at the example leet coal right so this is a given string so L occurred just one time he occurred two consecutive times so remember he occurred two consecutive here and E occurred here also so it doesn't make it as the power as three but it will only make it as power of two only because it should be power of the string is maximum length of a non-empty string is maximum length of a non-empty string is maximum length of a non-empty sub string that contains only one unique character right so it should have only one unique character so if you take the whole string there are so many unique characters but what is the one unique characters in that maximum length that is e this is two T only one C only ones o ones D ones EA here it is only once if there was something like let's take this example right there is something like right so in this case this year only two but disease are four we will we would have given the answer as four for this particular but in this case it's only two maximum and this is only one right so that's the reason why we will see the power of this ring is only two so let's go ahead and try to look at one more example and then we will try to look at the solution a only wants B 2 times C 3 times D 4 times e 5 times D there is one more see one more B one more a one more so d occurred three times 34 times C three times B 2 times a one time and the maximum occurrences are for e so e occurred five times that's why the power of this string will be fine that's the answer right so let's go ahead and try to look up the logic how we are going to proceed for this particular problem right so one thing that we are given is we are using only the lowercase English letters in the given string s right so all letters are only lowercase English letters so now what we are going to do is the thing that we are interested is only the string the consecutive string right which found with a single unique character that means we will try to compare the adjacent characters if they are same we will take them into account if they are not same that means we should not consider them as unique character right so we will have two things basically two counters I will be calling them as max length and current length right so I will be calling them max length and current length and compare adjacent characters so if the adjacent characters are same we increment the current length okay we increment the current length if they are not same then we will compare the maximum length with current length if current length is more than not sooner or greater than maximum length then we will replace the maximum length with the current length and reset the current length and proceed for the rest of the string so that's how we are going to do it right so finally whatever we have accumulated in the max length right and let's go ahead and apply that particular logic to this lead code basically the first example rates elite code example so I have initialized my index to zero and max length initialized to 1 and current length is also initialized to 1 because after 1 0 its max length is 1 current length is 1 right when I is equal to 1 so at 1 we will have to compare with the previous character are the same l and II know they are not same so we will put will compare max length with current length are they is maximum it's currently the greater than maximum no not really so we will just reset current length to 1 right so that's what we are anyway right so now moving on to I is equal to 2 the second character it I mean 0 1 2 3 that makes it has a third character actually so third character is same as second character so what we are going to do increment the current length that's what we did right so what we are doing we are incrementing the current length if they are same we incremented the current length so next move on to next character that is 3 T so is T is equal to e no so current character is different from previous character what we are going to do compare the max length with current length that's what we are doing compare the max length with current on if current length is greater than maximum yes in this particular case current length is greater than the maximum so we'll replace the maximum so put current length into max length right and reset the current length to 1 so we reset this point move on to the next character for TNC they are not same so max length will be 2 still the correct length will be still 1 because current length is not greater than max length next go on see oh right still it will be same OD still same de still same all right so at the end of it we got max length is equal to 2 and current length is equal to 1 so whatever the max length that we accumulated so far right that will be our answer so we will be returning that as the answer max length is equal to 2 which is that answer that we are looking for right so that's how this algorithm is going to work so basically the idea is to compare the adjacent strings as long they are same the current length will be incremented if they are not saying we will do some more processing basically restating the current length and also before restarting the current length check if the current length is greater than the maximum length if so replace the maximum line with current level so that's that algorithm right so let's go ahead and jump into the court we'll come back to the time and space after looking at the code okay so string s that is what the input so max length I initialized to 1 and n is equal to s dot length int current length is equal to 1 so why did I initialize the mat length to 1 because in 1 in the constraint it is given that the string length will be at least 1 so that's why initialize to 1 so you can ignore the string being null or empty because it is given that at least one will be there in the given input so that's why I initialized max length 1 and curl n to 1 otherwise we this will make wrong because if s can be z 0 length or null and right we cannot basically assume this way right since it is given in the constraint as 1 is less than a startling that less than is equal to less than or equal to 500 right that's why I have initialized max length to 1 and curl and also to 1 okay and we start from the first character that not that means not the 0 at K so 0 is this index right this is the first character basically first T index I would say not character exactly so first index so 0th index we already assumed right so that's what the maximum length anyway right so we'll start from first in X so if first index is equal to 0 at index it is I is equal to 0 right the first is equal to the first index character is equal to 0 at index character then we will increment the current length so at some point in time if two adjacent characters are not equal right what we are going to do is we are going to calculate what is the maximum of max length or car length and put it in the max length and reset the currently that's what we discussed in our large grid so basically we will increment if they are same if they are not same compare the max length the current length and if it is greater we will replace and reset the current length similarity that's it right so finally we end this far loop at the end of n so we will need to make one more check that is max length whether it is greater than current length or not so that's what we are making so why are you making this one so just to character the strings like this so a something like this if it is there right so you wouldn't consider this last B basically right so that's the reason why we will say okay we will need to do this check one more time and before returning the max length which I do this check and written the max length at the end of it so let's go ahead and look at the time complexity and space complexes for this algorithm so time complexity we are going through the entire string let's say the string length is and write the string length is M so in that case we will say the time complexity for this particular algorithm is order of M and the space complexity what space we are extra exactly using we are using this max length current length and M so apart from these three temporary variables right or local variables we are not using anything in respect to the string length we are using only those three variables right so for that case we will say this algorithm is constant space algorithm so the time complexity is order of M and space complexity is order one for this particular algorithm if you have any questions please post them in the comment section below this video I have posted the code for this particular problem - github repository in both problem - github repository in both problem - github repository in both languages c-sharp and Java you can find languages c-sharp and Java you can find languages c-sharp and Java you can find the link in description below this video if you haven't subscribed to my channel yet please go ahead and subscribe and share among your friends please click on the build icon so that you will be notified about my future videos thank you for watching I will be back with another video very soon till then stay safe and good bye
|
Consecutive Characters
|
angle-between-hands-of-a-clock
|
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string `s`, return _the **power** of_ `s`.
**Example 1:**
**Input:** s = "leetcode "
**Output:** 2
**Explanation:** The substring "ee " is of length 2 with the character 'e' only.
**Example 2:**
**Input:** s = "abbcccddddeeeeedcba "
**Output:** 5
**Explanation:** The substring "eeeee " is of length 5 with the character 'e' only.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters.
|
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
|
Math
|
Medium
| null |
671 |
hey everyone welcome back and today we will be doing another lead code problem 671 second minimum node in the binary tree this is an easy one given a known empty special binary tree consisting of nodes with the non-negative value where nodes with the non-negative value where nodes with the non-negative value where each node is that in this tree has exactly two or zero sub nodes if the node has two sub nodes then the node value is you can say the minimum of the left and right given such a binary tree you need to return the second minimum and the second minimum does not exist then we are going to return minus one so second minimum here is 5 so we'll be returning 5 in this case and in a case where second minimum does not exist like this we are going to return minus 1. so first of all you're making a result list and are running a pre-order list and are running a pre-order list and are running a pre-order traversal with the root okay so if the root is valid and if root dot well not in you can say results we do not want to add multiple root values same root value multiple time same node value multiples time so when the first time we see it we add it and append the root dot well and now running the pre-order traversal on the root at the pre-order traversal on the root at the pre-order traversal on the root at left and now pre-order traversal on the root and now pre-order traversal on the root and now pre-order traversal on the root at right so pre-order traversal on the at right so pre-order traversal on the at right so pre-order traversal on the root and right okay now we can just call the pre-order traversal passing it the root pre-order traversal passing it the root pre-order traversal passing it the root and now you want to sort our result so we can get the second minimum at one index so return result at 1 if the length is greater if the length of result is greater than 1. so the length of result if it is greater than 1 in the else case we can just return -1 and that's it pre-order yes it is free order so just pre-order yes it is free order so just pre-order yes it is free order so just type mistake and that's it
|
Second Minimum Node In a Binary Tree
|
second-minimum-node-in-a-binary-tree
|
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly `two` or `zero` sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property `root.val = min(root.left.val, root.right.val)` always holds.
Given such a binary tree, you need to output the **second minimum** value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
**Example 1:**
**Input:** root = \[2,2,5,null,null,5,7\]
**Output:** 5
**Explanation:** The smallest value is 2, the second smallest value is 5.
**Example 2:**
**Input:** root = \[2,2,2\]
**Output:** -1
**Explanation:** The smallest value is 2, but there isn't any second smallest value.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 25]`.
* `1 <= Node.val <= 231 - 1`
* `root.val == min(root.left.val, root.right.val)` for each internal node of the tree.
| null |
Tree,Depth-First Search,Binary Tree
|
Easy
|
230
|
67 |
Hello Everyone Welcome to Date 10th January Liquid Land Under the Shadow of All the Cases to Pyun in Hotspot 20 subscribe The Video then subscribe to the Page if you liked The Video then subscribe to इस वर्ग के गाने डॉ विन्द्या 2 8 Distance इस वर्ग के गाने डॉ विन्द्या 2 8 Distance इस वर्ग के गाने डॉ विन्द्या 2 8 Distance of Vindhya Uniform Software with Source of Meditation Resort with Depression Circle Liquid Liner Terminal Index Glass Manind Streams End All Subscribe subscribe like subscribe 105 Video subscribe Video को करे करे [ subscribe Video को करे करे [ subscribe Video को करे करे Your divide Your divide in meeting on to-do list Total in meeting on to-do list Total in meeting on to-do list Total Bittu Subsidy to Solve Vid U Still Remains Under 1000 Tons of What Do You Perform subscribe The Video then subscribe to subscribe and subscribe the Ki Agar Models Operation Models Ka To Do The Result Video give Withdrawal 251 Suggestion Mode Off Side 202 Now This Diet Recent Posts By Others Generated For 1000 Channel and subscribe the 0 ki job and quantity according dam explain subscribe And subscribe The Amazing do subscribe my channel subscribe The Channel and subscribe the Channel Please subscribe and subscribe This signal is too small to commemorate the delay in this signal on Thursday. Must subscribe and this is a committee to form of Wallace and were not giving his troops for storing result apart from building its soldiers complexity stones October Singh, you are definitely killing Indore's Additional District and patriotism from the ground up.
|
Add Binary
|
add-binary
|
Given two binary strings `a` and `b`, return _their sum as a binary string_.
**Example 1:**
**Input:** a = "11", b = "1"
**Output:** "100"
**Example 2:**
**Input:** a = "1010", b = "1011"
**Output:** "10101"
**Constraints:**
* `1 <= a.length, b.length <= 104`
* `a` and `b` consist only of `'0'` or `'1'` characters.
* Each string does not contain leading zeros except for the zero itself.
| null |
Math,String,Bit Manipulation,Simulation
|
Easy
|
2,43,66,1031
|
1,637 |
Hello everyone welcome to my channel Quote Surrey with Mike So today we are going to do video number 77 of our playlist Mark is medium but very easy question but the problem statement of this question is very quick meaning I did not like that is why I did not like this question very much Dislikes have been received which means probably 8900 dislikes. It is ok. This is an easy question. Actually, the problem statement is not good. I have given number 1637. What is the name of the question? Wided vertical area between two points containing no points. G asked. Look at this question. What is the question for you? n points are given ok here look at the input here n points are given point size = x i y return the point size = x i y return the point size = x i y return the widened vertical area between two points is n't it true that no points are inside that area ok let's see what you want to say And the meaning of vertical area has been explained here. A vertical area is an area of fixed width extending infinitely along the y axis that is infinite height. Height will be infinite. What does it mean? Look, what does area mean? Wide with height. So it is saying that the height is infinite, isn't it? The height can be infinite, it will go up, from the height but width, we will know how much its area is, so what is the wide vertical area, the one with the maximum width, because the height of all is considered infinite. Well, the one whose width is more will have a wider area. Well, if we look at it, even if we do n't consider the Va Axis, the work will be done. I mean, I am saying that even if I am not a consideration, it is everyone's Va Axis. If I do this then the work will be done. 79 4 Even if I remove all these, the work will be done because look here it is clear cut that the one which has more width means the width is more, it will have the wider area, right, and the rightmost vertical area, right? It will depend on the maximum width because the height is the same which is infinitely long. Okay, note that the points on the edge of the vertical area are not considered included in the area. Look at this example and understand that I have plotted these points here first. Which point is after 8? Okay, so look at 8. It is visible here. I have it, after that it is 99 9. This is it, after that it is 7 4 74. What is it after that? It is 97, right? 9 means this. The point is okay, now pay attention to one thing, see which is the biggest area I can see, you cannot take this area, such a big area because if you take this area, then see this point has come inside, it will become wrong in the question. It is said that there are no net points on the edge will work, like this area, if you take it is okay, then look at this point, it is on the edge, then it will work, but look, there is another point in the middle, it will not work. Now it cannot take such a big area, you will have to take this area, it is going up infinitely, the height is infinite and you can take this area, look at it, the points are on the edge but there is no extra point in the middle of this area. No, it has not come, okay, so I can see two areas, one is this one and one is this one, okay, so which is the largest area? You see, its width is one and its width is one, so whose area is the largest? There is only one, this one also has one, then send the answer only one, and what is ok, the height is infinite, you just send the one whose width is wider, you just have to send the same answer, so if it is seen, then what do you have to do, that's all The widest width you get will be your answer, so just notice here, this is seven, this is eight, this is nine. You see, we have plotted the points here in a sorted fashion, so what would be the best way to do this? Sort it, right? You will sort it and find out the width between every two adjacent points. Look, if it is sorted then which one will come first? 74 will come first, after that 87 will come, after that 97 will come after that 99. Look here I sort it and write it down, first of all comes 74, after that comes 87. Look, it is also plotted in the same fashion, here is 74, then 87, after that is 97, after that is 99, see 97 more. 99 is right here, so we just have to find out whose width is the highest. Just a simple s that. So first we will find the width of these two. What is the width? Brother, 8 mi sa width. Let's see the width of these two. 9 mi 8 sa width. If you want to remove only one, then you will subtract the empty So it said that the wide vertical area is not the one with the maximum width. It is asking if there is a maximum width, so this is the maximum width, we have sent it. Okay, let's see another example which is given in our lead code. 3 is 1, 9 is 0, 1 is 0, given in our lead code. 3 is 1, 9 is 0, 1 is 4, 5 is 3 and which one is 8, then if you sort it then what will happen, see first will come 1, not 4, first will come 1 0, after that will come 1 4. After that will come 31, after that will come 5, after that will come 88, after that will come 9 0. So we have sorted it based on I am taking out the width. Okay, so see what is the width of 10 and 14. 1 - 1 that so see what is the width of 10 and 14. 1 - 1 that so see what is the width of 10 and 14. 1 - 1 that is 0, let's see its width. 3 - 1 that is, let's is 0, let's see its width. 3 - 1 that is, let's see their width. 5 - 3 is 2. Let's see their width. 8 my 5 that is. 3 Let's see their width. 5 - 3 is 2. Let's see their width. 8 my 5 that is. 3 Let's see their width. 5 - 3 is 2. Let's see their width. 8 my 5 that is. 3 Let's see their video, 9 is my 8, that is, it is ok, the maximum is t, hence its answer is - So, if you tell me, brother, if you is - So, if you tell me, brother, if you is - So, if you tell me, brother, if you subtract its Why is there no answer brother, there will be many points between these two points which we cannot take because the height is infinite, so all these points will not come within them, these are between 90 and 10. We cannot take points, they should not be inside, okay, that's why we are checking the one just adjacent, to find out the width, what is its width, its weight and its weight, by subtracting it from the x coordinate. Will we find out the Yes, I will take out x2 or When we finish, let's code it. Look, there are a lot of dislikes on this question because the problem description is not given well. Okay, so first of all let's start by making n = points start by making n = points start by making n = points dot size. Okay, after that I said. It is up to him to sort it, what will happen after sorting is that we will get the adjacent points, which will be the start of points and end of points. Okay, so what will happen with this, by default it will sort on the basis of X axis. In ascending order ok now let's start int result e 0 let's take for int aa = 1 aa le aa p ok 0 let's take for int aa = 1 aa le aa p ok 0 let's take for int aa = 1 aa le aa p ok result e equal to maximum of result comma here I take out the width int width e equal to two points of X axis of aa is ok and minus points of aa my one's The test cases are indeed yes. Let's submit and see the time complexity. A log is done because we have done the sorting. I hope I was able to help, if there is any doubt in the comment section, try to help out. See you in the next video.
|
Widest Vertical Area Between Two Points Containing No Points
|
string-compression-ii
|
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._
A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width.
Note that points **on the edge** of a vertical area **are not** considered included in the area.
**Example 1:**
**Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\]
**Output:** 1
**Explanation:** Both the red and the blue area are optimal.
**Example 2:**
**Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\]
**Output:** 3
**Constraints:**
* `n == points.length`
* `2 <= n <= 105`
* `points[i].length == 2`
* `0 <= xi, yi <= 109`
|
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
|
String,Dynamic Programming
|
Hard
| null |
905 |
hello everyone so in this video let us talk about an easy problem from lead code the problem name is sort array by parity so the problem goes like this that you're given integer edit nums move all the even integers at the beginning of an array followed by all the odd integer so you are given some integer error as you can see and you have to like move all the even on the very front and then the odd number so return any error that satisfy this condition you can return it here and there are up to 5000 elements now you can pause this video Try to find out the solution of your own as well but let's take the first example only so three one two four now I have to bring out all the even elements first so it should be like one of the case can be to bring out these elements at the very first so I should bring these elements to the very first and the strap out these odd elements at the back so this give me one of the observation that I can use some sort of a two pointer technique and I can swap out the characters or the elements if they are not even if they're odd we will put it in the very back and if it is even we can just leave it down there so let's make this example little bit bigger and let us try to use this example that whether it is working or not okay so what we'll do is that let's uh increment this value so let's say the array is let's like this okay and okay let's take this one let's say we'll take two pointers we'll take one pointer at the variant and the one pointer at the very start because I want to First initialize or bring the even numbers at the very front so what I'll do is that I will check it whether this is an even number this is not so I will swap this number with the very last number okay if I just Swap this out it will become like this it will become like I just remember this will become 3D this will become two okay now what will happen is because I've swapped I eventually know that this is the number which has come from the very back it might be even odd because it is coming from the very back I have only checked this front number is having the condition that if it is an odd put this number in the very well you got the point so if this is an odd number I've inserted it at and swapped it with the last pointer value like whatever this pointer is holding out and bring this value of the wave front now it might be happening that this might be also odd so the odd number might have come again so I should not move this pointer ahead but I should only move this pointer ahead why because it eventually means that this number is odd and it has come to the very back so now let us move down this pointer at the very start so now my pointers has moved like this has driven to the same point but this has moved now whether the first point is even if it is even then we just move our first pointer to the right hand side so we will move up first one to the right hand side whether this is whether the first point is even if it is even we just keep on moving the first photo to the right hand side Okay so now whether this is even this is not even so I will swap this with this okay because I want to somehow bring an even number if it exists on the second pointer now if I swap them out both of them are three only so what will happen is that 3 will swap with three and nothing will change but I will not move this element because what you have observed is that by swiping this I want to somehow make this even to like for that odd number to an even number but because the other pointer is also holding an odd number this will not change anything but when I switch this I will not move this pointer but I will eventually move this pointer and now they have come to the same point which means that all the elements on the left hand side of this kind pointer are even all the pointers on the light like all the value on the right hand side of this particular Point are odd so we have and both have come to the same point so which means that we have done iteration all of them are even all of them or on the left and right side that is done so that's the whole thing we'll use two pointer technique to do over all this overall thing so let us move on to the actual code how it actually works out so we have two pointers one is I that is very fun and N is a very large end okay so this is 0 and the size of that now this is the value till I is less than n so that we will keep on doing this iteration if the current ith element so vary the first element okay or the first pointer that is holding the element if it is an odd number then what I'll do is I will swap the first element that is the pointer that is holding the first element and the last and the second pointer value both of them are swapped and then n is moved to one step on the left hand side which is the second pointer is move to the left hand side and similarly you can see that I am also moving my I on the right hand side but in the after this if condition is moved back why this will move there back what I'm trying to do is that I want to nullify the effect when I am swapping so that only the right pointer moves but if we are not doing going inside this if condition which means that when I am doing this while loop if the left pointer is pointing towards the element that is already even this is only going in the odd condition we are only stopping the first value with the second value with an odd so that my first value will not remain to be an odd value so if it is an even value already I will just move my right or the first point to this like the first value pointer to just the next element so I'll just move my I plus eventually they both moves these two pointers move around this whole array and when they comes to the same point this value will break and we have the whole bifurcation of even odd elements inside the array and that's the overall uh solution you will just download the new modified array numbers tutorial logic so this is an O of n operation by moving out both the pointers over this whole array and we have not used any extra space as it so this is an O of n time complexity problem so that's our logic and the code part for this particular problem if you still have any doubts you can mention in the comment box of this particular problem thank you for watching if you do to the end I will see you in the next Monday live recording and bye
|
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
|
1,094 |
Ka Affair So Adi Se Car Pooling Problem And They Are Going To Its President This Is The Daily Challenge To Them Car Pooling Problem Pashu Understand What Is Time Bill And Of Capacity MTC ISRO Disawar Capacity And Difficult Only Drive Stupid So This Restriction For Example Of Vikar Starting from edit absolutely only to all say still not written and got to WhatsApp best places capacity member for in this example and immediate research important awards strips slow entry this chapter giving that number of cases from * for example that number of cases from * for example that number of cases from * for example decision location means from and third edition of What They Have Some Passages From Pearl Aam And Passenger Asadhya Sulabh Complex Will Travel From This Location One To Three Leg Race Rigid Must Try Then Like Share And Subscribe Kilometers From This Point To Meters And Subscribe Possible To Pick Up All Desires For All The More Subscribe Now We Have Two Passengers Passenger Train From Location To 500 Entry Passenger Land From Sudhe Raju Passengers Entry Passengers Traveling From CEA 2103 Passenger Traffic Rider And Will Have To Be Capacity Four And It's Possible Passengers During One To Three Passenger Will Be Pickup By type Sona and total will be added to know from where they will drop to people will depart from which one that 2G spectrum allocation has pointed to The Amazing Change 251 Change Fiber Episode Oilers Growth Rate Cities for Sona in this condition will break and wept Those points point is point Naveen look into these examples for better understanding so example2 passenger traveling from one location to five against m ok and three passenger treated print from location tree to sit in the depth increase what from year to year only will have to passengers right Nau from do it will increase from to plus retail vikram 59 this is why not withdraw to passengers sandy plugin vikram free software tourist places point to that is possible case will return through this option will talk gabbar solution so what came with solution for this shoulder 600 Artists and accounts of all three passengers from two group condition which have to take care sofa during time 0 points for example this point to that is that and only thing which were also when you handed over to bantu on example2 passenger train from 1252 inverter direct example this Is nothing works will add to video plz subscribe Channel subscribe to thing do passenger will be a prop Raees soch and sucked into end secondary board MB get this is the third nx100 wedding plus arrow very least resistance at 6000 - suicide letter from left to right leg Passengers to maximum possible length from company force and lag from 100 days ago from 100 the like this loot in there and you again 10101 mid-2012 easy oil 3000 more than 1000 total 10 passengers good value total 6 day and subscribe the Channel - 265v MP3 Low 60 - 265v MP3 Low 60 - 265v MP3 Low 60 Well And Every Step Will Actually Check Pad To Passing Over Condition And Capacity And Not In This Way They Can Solve Problems Side It's All Easy There Are No Viewers Explain Unicode Idea Road Porn Should I Can Understand Tomato Digestive Lineage's Soft to Loud Maximum 21 System And What Do You Like To Start From Today And The Best All The Best Computer Total Subscribe To Ka Ka Ka Hak Re Kyun Ho
|
Car Pooling
|
matrix-cells-in-distance-order
|
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_.
**Example 1:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4
**Output:** false
**Example 2:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5
**Output:** true
**Constraints:**
* `1 <= trips.length <= 1000`
* `trips[i].length == 3`
* `1 <= numPassengersi <= 100`
* `0 <= fromi < toi <= 1000`
* `1 <= capacity <= 105`
| null |
Array,Math,Geometry,Sorting,Matrix
|
Easy
|
2304
|
936 |
hey everybody this is larry this is day 21 of the leeco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm stamping to sequence so we're about two hours away from the contest uh from the weekly uh we did a little bit better this morning but you know it's still a silly mistake so still some stuff to clear up to clean up but you know uh and those of you who've been watching this channel might know that i am going to turkey and the country uh for a couple of weeks so i might not so i might this is maybe my last contest in a couple weeks is my opponent it's live i'll probably do them virtually uh at night or something but yeah today's problem is 936 stamina sequence so yeah anyway my point there was hopefully y'all have good luck on the contest on both the bible and the weekly and let's do the let's do these farms together so stamping the sequence okay so there's a s there's a surprising question i want to determine every corresponding letter from stamp so abc you could do a oh huh oh this seems like an annoying one let's see so okay so basically we have a length n and then we have to kind of get them in the right way and n is equal to a thousand hmm this is very tricky but one thing to note is that you do not need the optimal solution so you don't need to do i mean or at least not inferior you don't need to do dp or anything like that because you only need to do one solution and not um you know and not the optimal solution so and you're able to use up to 10 times n number of turns okay so what does that mean for us right i think so some observations here the first one is that you always want to stamp on the border um and the reason is because if you stamp on the border you can always go in to overwrite stuff right where if you go from inside out then um you can't really overwrite or like your earlier stuff gets overwhelmed in a way that nothing preserves right where you go outside in then you preserve the then you preserve the edges all together um yeah and then the question is what do we do and i think based on that it is just a greedy solution but i'm just trying to think whether that's fast enough meaning that okay here you stamp you know the edge you stamp the edge as much as you can from left or the right and then you keep on going inside out you just chop off two at a time one at a time so basically yeah just looking at the prefix and then just keep on going right um but you have to be careful because i think for this one for example um if you do abca if you try to do this and then this then you would crop up all this stuff but you still have to you know take care of here right so that's a little bit you know you have to be careful now i have to think about how like what is the way that i can guarantee it to one without you know being or implementation-wise being or implementation-wise being or implementation-wise guaranteeing it to succeed without you know without um running into an issue right let's see so the thing that we said is that we're trying to do the you know um i think another way that we can play around with this problem is that instead of doing you know what stamp should i do first maybe i should think what stem should i do last right i don't know if this is working for this particular problem but these are the things that i'm thinking about so here for example maybe we recognize that the last step is going to be abca right and then now the step before that will try to extend out a little bit and then maybe now we see that we can go ca and then maybe now that we can do a and then kind of extend inside out but um but in a backwards kind of way right meaning that um yeah i think that makes sense to me trying to think whether there are weird situations but that makes sense to me but i think there's there is another or not another but there are weird cases as well that we have to think about because we have something like a b c a like uh abca again say and then like i don't know b right so there's no a in the prefix but you can see that you can do this in the three step because you can do um a b c a here to you know just cancel out this one um and then you do abca i guess this one's a bad example and that there's overlap but you know what i mean um in that you try to do the b first um so how would we do that though in a good way so we can't even do the extension one per se but i think this is general um these are the general ideas and edge cases that i'm considering this is a high problem that said we have to buy by uh by rule we have to check this thing right so yeah i mean i think if we do n square is fine for every iteration we just try to figure out a move that let us do one move right meaning that every iteration we try to get at least one uh stamp in um yeah i'm trying to think about how to handle the case well but because i feel like there are a lot of edge cases in the way that i'm saying because let's say you remove this and then you move this then i guess you get b left but which is fine but what if this is a d and then you know like would you really well first you would choose this first i suppose but then would you greedily do now there's no more four matches you'll do this but then you have a d so then that doesn't really work either right okay let's grind it out i mean i don't really have a great resolution here to be honest but i know that we do it this way is that true i was gonna say this is n squared um i think it is because then if every step we remove at least one character then that's over n and then every step we um look at each of the characters then it'll be o of n inside so then it'll be n square okay i think maybe i'm convinced about here so yeah so while not done maybe something like this done is a bit of force um we might fix this up a little bit later but um but yeah uh t as you go to let's go just to list the characters yeah i think as long as we can get one character we're fine so okay so let's do that um i mean i know that we a little bit slower on it but yeah um so here we go for away um i guess this is the part where uh we might have to do some optimization that's what i was thinking because we have to start at each character but then if we match that it'll be o of n so this n beginning and then o of n again so that's actually going to be n cube right so that's not quite right uh my analysis is a little bit yikes but hmm i don't know if this is going to be fast enough but all right let's just do it i mean i uh because i think we can early terminate on just anything with at least one character being correct uh or like one character matching and then they'll end the loop um so i think there's some like weird amortization thing but okay all night done is your fault let's see so yeah so then we can do something like if okay so for start and range of n target and here we want n minus um site and while this is true we go if match of uh let's just say start then we just do it right um we go found is equal to true and then we break if um something like this maybe this part is just gonna be well true if not found then we return empty array right otherwise if we are found oh then we should do something here start and then we just um we have an answer away from start and then um i don't know change start or something right um and then that's pretty much it and then we return answer at the end maybe reversed um well that's we might also have to verify it but let's do that for now and then now we have to implement our two functions match uh so okay so this is basically for i in range of s if stamp of i is equal to target of star plus i then we return true because we only need to re match one character um yeah one character that isn't a star or something and maybe i'm a little bit off on this one we'll see and then start here for i in range of s if stamp of i is equal to t sub star plus i then t sub star plus i is equal to question mark right and then now at the very end it goes um if t of count of question mark is you go to end then we return this thing otherwise we return this something like that let's give it a spin now this is about true so this is going to never end but um so are we done if this is true yeah maybe i just do this something like that maybe not quite sure about this one but and we terminate early so that's not great uh okay let's take a look to see what it's doing companies print um t okay so first it matches the first three okay and then i have hbc that's up to one elevation and then it doesn't find another elevation why is that huh so that's up to one iteration but then here the found is force i messed this up oh why did i not return force maybe we turn none and then it just something weird i don't know that's still a weird smell though so it's definitely should fix that but hmm is this i is this plus one did i have an off by one i probably have enough by one still no oh wait no that wasn't that did fix it so yeah okay so that looks good though this doesn't do you do this first and then you do this versus wrong right so why is this reversed wrong oh because we're not trying to get the maximal um we're trying just trying to get any answer um and i don't think that i got the layer right the ordering correct this is just wrong now but now for the second one we did zero um and then uh we did zero and then one and then three which is wrong huh how did i get the ordering right um because right now we're just doing it gritty but what we want is try to figure out how to um hmm i guess it doesn't matter i think the thing that we have to do first is try to get all the ones where it matches perfectly because those are the only ones that we cannot overlap right the initial beginning ones meaning like the abc this is the only one that we cannot overlap all the other ones we can print in some uh some order and it doesn't matter i think the only thing that matters in terms of order is the last ones because those are the ones that stamps on top don't step before that it peeks through anyway because that it assumes that there's no overlap by the time that you do them is that true i don't know that i know how to do this one in a vigorous way but yeah let's see maybe someone like this basically i'm just this is the same thing except for um well i guess here then we can just break otherwise okay something like that and here we want to match exactly which is the same idea here except for that it has to be the entire string so we just have to do and you could probably just actually do a string comparison maybe that's faster um okay so then now we can reverse this i think okay i think i'm gonna get this one wrong but let's give it some just because i'm yellow apparently i've i get this one wrong a lot so we'll see maybe i time out even i don't know we'll see but uh oh this one's okay i guess but why am i wrong here oh because i returned from here because we already finished the entire thing so okay let's see yeah you just do it here like this so easy to make a mistake on this one i don't even know this is right the complexity is just all very awkward okay well let's try it again apparently last time last couple of times i've gotten wrong a lot so hopefully this one's slightly better oh geez and it took six a while uh let's see so i put three zero one two three that's right and then one what's zero three two zero three one two oh no that's two okay so i did three first to get the one i get the one and then the zero oh the one and the zero is in the wrong order huh because we have to do the zero first otherwise the one over right or zero overwrites it huh how do i do it this way then i think the idea is right but kind of but it's hard to say it's right but i think there's some parts where i'm just a little bit wrong so yeah so let's just say we have this answer right plus a full answer maybe something like that but i don't know is that enough i mean fix this because the idea is that okay we replaced this with one character and then later stuff yeah i think this is maybe more right maybe i just needed to separate them out i was lazy and try to combine them still may be wrong though to be honest but at least the four makes more sense to me but maybe not clearly i say b so one two zero okay so one we do the b i see so did the b and then now it does it again huh how do i sort this in a good way huh hmm so basically this is just the opposite of what we did so even though um so we're going from left to right we get the first instance that it match and then we're good but we're not doing that in a good order hmm i think i have to change this a little bit i think that we're just matching this here but what we want is actually one that we can do in the right order and this isn't quite doing that what we want is actually yeah maybe i did this in a funky way because what we want is not necessarily um because we want to the reason why the ordering is an issue is because we just can't do anything like all these move in some order will make sense but the problem is that we're not calculating them in a good order i think in order to get to the right order we have to change the move instead of matching one it should match everything um so it's either this so it's not match any it's the opposite of before where okay if this is not true if this is true if it matches all of them if this doesn't match and t sub star plus i is not equals to question mark because if it's question mark then we can just match it someone like that maybe i'll put this in i don't want to put it in um and then this and then from the loop somehow okay so how does this even kind of infinite loop oh because um because at some point they're all question marks so it keeps on stamping the same one so what we need is if um okay so maybe done is here to set if start and done and start not in done and this and then we just do done.add start and then we just do done.add start and then we just do done.add start someone like that okay and then now we can reverse i think because now we're doing it from the last step up uh huh this is a very hard problem i don't know if this is right i already got more wrong answers than before but okay just actually end up somehow better uh okay cool 873 this is a disaster to be honest um i don't really know how to do the complexity as well but the idea here so that the way that i was consistent about and fixed was just doing the last step first and then now we can figure out the order in which we can combine because we know that the idea here is that let's say i have something like this i think this is a little bit different than i had uh explained it before but let's say we have we match abca um here now we replace these with question marks that means that we don't need to care about these things anymore because they're wildcard because we know that we'll stamp over them later so then now we can match the ca where initially i was just matching ca assuming that some order makes sense but the way that i didn't make sense um i think so i think this allows for a quicker termination just because excuse me having this uh um because like i said at most this will take and loop because each step will change at least one character but this is n square so this is a little bit awkward so like in the worst cases is n cubed but it also has a lot of early termination i think this early this amortization that makes it n square just because at the worst case no maybe yeah in the world yeah i don't know this is like n cube in the worst case or something i don't know to be honest um this is my idea but huh i mean this is my idea i don't know how to get n times n minus m instead of the way that i did it but um oh yeah i mean this is the way that i did it but maybe not the way that i implemented it though yeah i don't know all right sorry friends this is a really bad just maybe this farm is just my arch nemesis because it seems like i've not learned anything the last few times um let me know what you think let me know how you solve it uh and yeah i'm gonna do a bonus question real quick so stay tuned stay hit the subscribe button and i'll see you soon bye
|
Stamping The Sequence
|
rle-iterator
|
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`.
In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`.
* For example, if `stamp = "abc "` and `target = "abcba "`, then `s` is `"????? "` initially. In one turn you can:
* place `stamp` at index `0` of `s` to obtain `"abc?? "`,
* place `stamp` at index `1` of `s` to obtain `"?abc? "`, or
* place `stamp` at index `2` of `s` to obtain `"??abc "`.
Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`).
We want to convert `s` to `target` using **at most** `10 * target.length` turns.
Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array.
**Example 1:**
**Input:** stamp = "abc ", target = "ababc "
**Output:** \[0,2\]
**Explanation:** Initially s = "????? ".
- Place stamp at index 0 to get "abc?? ".
- Place stamp at index 2 to get "ababc ".
\[1,0,2\] would also be accepted as an answer, as well as some other answers.
**Example 2:**
**Input:** stamp = "abca ", target = "aabcaca "
**Output:** \[3,0,1\]
**Explanation:** Initially s = "??????? ".
- Place stamp at index 3 to get "???abca ".
- Place stamp at index 0 to get "abcabca ".
- Place stamp at index 1 to get "aabcaca ".
**Constraints:**
* `1 <= stamp.length <= target.length <= 1000`
* `stamp` and `target` consist of lowercase English letters.
| null |
Array,Design,Counting,Iterator
|
Medium
| null |
377 |
hi guys welcome to techie so today we are back with the daily challenge problem that's combination some phone that's basically an 8 medium 377 question uh i will request you to please have a look at this as it's easy based question and uh somewhat a quality one let's see what the question says you have been given an array of distinct integers that's number okay and you have been given a target sum that's an integer target return the number of possible combinations that add up to the target okay you have been given an example so let's look at the example is one two three and the target is 4 so by using this you have to form the table basically this is your dp question okay if we ask you how to go up with pp1 so this is your eq question how you will go up i'll explain then we look at the group okay we have one two and three we need to check for the combinations that sum up to four so first is if we write one or if we use two three cannot be used alone so three will require some one three and three one can be there then coming to two one this could be a possibility that comes up so how many possibilities did you get one two three four five six and seven so this is how you have to approach the problem you have to search now every time you won't be able to count how things are going so what we have to do is we have to check okay so what if we would do us we'll take an array let's say a dp array of size target plus one okay so that the last is actually a target now for every uh for the first one we make it one because it is not being used so that's what we have to do that's a base case that we go for now what you have to do for every i is one to p i trade for number or you can say num where it's an elementary number and check if this n is less than equals to r then for that case make dp of i plus equals to dp of i minus that is the approach which we'll be using that is we need to check that for every particular number how can we represent it that means so each value of i will iterate and the value of the cell can be reached with each number by dp of i plus sum so that's what we are referring to this time okay let's see for one for making it one what could be the possibility if we see it directly we just need one a single one so the same thing if we iterate i is one number is one two three first it's one n is equals to this yes so dp of one would be one plus zero sorry initially this is 0 plus this so we got 1 for 2 and 3 this won't work why because 2 is not less than equals to 1 and 3 is also not less than equals 1 so for these two this won't work so coming to the next iteration i is two so for two we'll require one and two both why because two can be formed by one as well as two if you see how many ways we can form two one and two so we need two possibilities if you check this way what are the possibilities you will get that is for the first that is one less than equals to 2 yes so dp of 2 would be 0 plus dp of 1 so that's 1 again 2 less than equals to 2 yes so dp of 2 is dp of 2 that's 1 plus dp of 0 it comes out to be 2 again coming to the third one that's 3 so for this 3 we need 1 2 and 3 all three will run because one is also less than three two is also less than three so for the first one this would be this plus this so it's two second one it will add up this and third it will add up the third one so giving it four coming to the fourth one again you'll iterate make it four then six and then seven now in action if you ask me what is the procedure that's going on is the number of elements present in your nums array is the number of elements we need to add so for four we added the first three for second also we added the first three so it's basically we are adding the elements that are present uh that's kind of a prefix sum and those elements are equal to the value that uh number of elements in now so this is our approach that takes order of n into d time you can directly see we added it as 0 we need this if i is greater than equals to n or we can also write this adding this at the last value will give us the sum this is another top-down approach if you this is another top-down approach if you this is another top-down approach if you can check for this we'll check if the target becomes zero we're coming in opposite return one that means instead of moving this way we'll be using this if t is not uh dp of t is not null return this initially it has been solved and if it is not solved then take it as the value and t minus n so this is also the same approach that is order of n into p this was an easy question if you know how to post the tp questions or point things for a question also you can see if there's anything that's required or any help required with this solution then do let me know i'll get help here till then keep following me thank you
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
291 |
this is logic coding um today let's look at another backtracking problem called world pattern two so we are given two strings one is a pattern another is the string and we want to return true if the string matches the pattern how do we define match so if there is some bijective mapping of single character to string such that each character in the pattern is replaced by the string maps too then the resulting string is s and the bijective mapping means that no two character maps to the same string and no character maps to two different strings so if we have a b and we have red blue and red blue obviously we can find the match with a is mapping to red and b is back into blue same thing with four a's so we divide by four a map to asd and a b so for this one we actually have two different mappings um for each character we're at a this a can either be mapped to a or it can be mapped to asd okay cool so as long as we can find this pattern we will just return true so since we are not sure how much how many characters in s we should match a specific character we should explore all the possibilities if we find a possibility that holds true then we just return true otherwise we backtrack and explore other opportunities so the algorithm we will use is to use recursion and backtrack so for each option so at a pattern i uh before that uh let's keep to global variable uh a pmap with charge a string and we also want a s map just to keep record so for each pattern at i um let's assume i have another index for string starting from j so j ideally we should try the mapping to j 2 j plus one and up to the end so for each pair we should try to see whether this makes sense or not um if it does then no problem but we just do dfs for each pair so now let's claim these two global variable s map and pmap and we want to return this dfs with pattern which is fixed and s pattern with i is zero actually and s with zero as well okay cool now let's define this dfs so naturally i should pass this maybe by reference to save time and space and s i would have j if we are rich at the end and competition if both are at the end i'll just return to otherwise if either one of them are at the end just return false and other than that we need to consider the constraints and explore first let's take our current character at index i now we want to um we want to explore to which strings that the c can be mapped to so k naturally starts from j but it's going to be smaller than this k plus and uh this string is going to be equal to s dot substring so starting index would be k the length of the starting index would be j and the length would be k minus j plus one okay cool so um if either c and are already mapped so we do if my pmap already has this character and it does not equals to my string when i return false and on the other hand if and as map string is not equal to character i also return false if you're not b so if they're not mapped i map them right i just add the conditioner into video character as well and yeah so after this i just need to do dfs okay if dfs the next stage would be the same thing pattern but then i plus one s but then the k would be actually i shouldn't return false i should just do continue because i wouldn't be considering this k and uh okay plus one i just returned true and i need to do backtrack as well so if insert equal to q i need to erase it i need to erase this c and uh string till the end just return false if it doesn't code yeah i think that's pretty much it we have two strain we need two index to indicate the dfs and we do our backtracking here let's try around the code stream cool i think that's pretty much it let's try submit great that's it for today
|
Word Pattern II
|
word-pattern-ii
|
Given a `pattern` and a string `s`, return `true` _if_ `s` _**matches** the_ `pattern`_._
A string `s` **matches** a `pattern` if there is some **bijective mapping** of single characters to strings such that if each character in `pattern` is replaced by the string it maps to, then the resulting string is `s`. A **bijective mapping** means that no two characters map to the same string, and no character maps to two different strings.
**Example 1:**
**Input:** pattern = "abab ", s = "redblueredblue "
**Output:** true
**Explanation:** One possible mapping is as follows:
'a' -> "red "
'b' -> "blue "
**Example 2:**
**Input:** pattern = "aaaa ", s = "asdasdasdasd "
**Output:** true
**Explanation:** One possible mapping is as follows:
'a' -> "asd "
**Example 3:**
**Input:** pattern = "aabb ", s = "xyzabcxzyabc "
**Output:** false
**Constraints:**
* `1 <= pattern.length, s.length <= 20`
* `pattern` and `s` consist of only lowercase English letters.
| null |
Hash Table,String,Backtracking
|
Medium
|
290
|
48 |
um hello so today we are going to do this problem called rotate image which is part of today's um lead code daily challenge so the problem says we get an n by n uh matrix that represents an image and we want to rotate it by 19 degrees and so what we want to do is rotate it in place so we want to modify the matrix itself and so let's take a look at this example here we have one two three and so that one needs to be the last cup um okay so here for example if you take a look at this array one two three we need to rotate it 19 degrees basically means it will go to the last column and then 4 5 6 goes still stays on the middle but the middle column and then the last one becomes the first column right so that's sort of how we rotate um if you take a look also here you can see this one becomes the last column um you can just visualize it if you rotate 19 degrees but essentially what's happening if you take a look at this 147 you can see it was a column it became a row 147 but the reverse direction so it's actually just if you take the first column it's one four seven right um if we reverse it then it's seven four one so we reverse it and we put it in the first row and so if you can think of it as sort of two transformations the first transformation converts each column to a row the second transverse transformation reverses each row and that will pretty much gives us this 90 degrees um rotation right so 147 becomes first one for seven in the first row but we reverse it so it's seven for one four five two five eight becomes first a middle row so each middle c each i column becomes the iro and then we reverse um that's what happens here and same thing here um so that's the idea and we just need to do it in place yeah okay so how can we solve this so what we said is we need um two things we need um a transpose operation so that's the first thing we need to transpose um and basically that means basically convert columns here to rows and then we need to the second thing we need to reverse rows and that will give us the 19 degrees now let's just do an example and make sure that this idea works um so basically transpose means converts column to rows so we need to zero one we need to swap it with one zero two and it's about two to zero this is basically for converting the first column to the first row and then of course we need to move this and save it back somewhere so we need to save it here in the first column right however if we do for our loop that does the conversion basically that does the from zero to n for i and then for j we can't do from every time from zero to end right because we will first let's say swap one four seven and then we will again swap 4 with something else so what we want to do is for j when we are swapping with this operation start from i plus 1 so that we don't swap what we already just wrapped let me just go walk through a couple of um for the transformation for this one and you will see how it works so this is the initial one so the first step for us would be to start from i equal to zero so our for loop would be from i equal to zero from 0 to n and for j from i plus 1 to n and n here is open uh interval so it's in plus 1 so it's n minus 1 sorry it's the last one is n minus 1. so we will go for i from 0 to n and we'll go for j from i plus 1 to n this is so that we don't swap or we already swapped um this is basically our loop um and now we will swap so the first iteration 1 2 3 and one four seven so we need to swap zero so j from one to n minus one because i starts out at zero this is the first operation and so what that would mean is we need to swap i j so we need to swap i j with j i so we need to swap zero one with one zero and zero two with two zero right um and so that means basically zero one which is two is swapped with four so that's what we have here and 0 2 which is 3 is swapped with 2 0 which is 7 so we swapped here so now we have 1 4 7 1 2 3 here and the second iteration where i equal to 1 and j equal to i plus 1 so 2 so i equal to 1 and j from 2 to n minus 1 and is equal to 3 by the way and so we'd have we need to swap only 1 2 with 2 1 and then we stop because we reach n minus 1. and so we swap 1 2 which is 6 with 2 1 which is 8. and so that what we do here and now we increase i so we go to the i equal to iteration j is equal to i plus 1. so 3 so that's outside of bigger than equal to n so we are done and so the last matrix we have is this you can run it on a bigger example just to get an idea but you can see here with these operations we got the transpose 147 is now in this row 2 5 8 is now in this column in this row 3 7 9 is now in the last row right and that's pretty much it um and so now we did the transpose which is converting the columns to rows now we do the reversal which is just converting each row reversing each row essentially so we'd have just seven four one eight five two three uh sorry nine six three and this is what the problem asks us to do um if you take a look at the late code description now the question becomes how do we reverse well reversing is actually easy if you could just go back to just one single array if you have one for seven how do you reverse it well you just swap each i with n minus i minus one that's pretty much what we do and that way and we do it only for i from zero to um n divided by two right so that we stop here we don't swap and then go back and swap again so if we take a bigger example let's say one two three four five and we wanna swap so we start from so the size here is zero one two three 4 so n is equal to 5 so that means basically um 5 divided by 2 is roughly 2 right so our mid here is i is going to go from 0 to 2. and so we swap every i with i minus n minus i minus one so we swap five and one and then we need to swap two and four so we'd have four and then two here and then three stays in the same place right we are done because we did we need to do just up to two and now we have five four three two one so it's reversed so that's what we'll do here is basically just swap um i j with um i n minus i minus 1 and n here is just the columns number of columns um and sorry this is n minus j right yeah so that's pretty much it for reversing and now yeah we know how to do our two steps um the transpose and then the reverse just want to emphasize again the critical part to think about and to make sure you understand so that going forward you can do transpose easily is this that you need to start from a plus one and then you need to swap i j and j i um yeah so that's pretty much it let's go this and make sure it passes test cases okay so what do we need to do first here so the first thing we need to do is to transpose our matrix and we'll do it in place and then after that we need to reverse those are the two transformation we need to do and that's pretty much it we do it in place we don't need to return anything and so now let's define our functions so transpose first we said we wanted i to go from 0 to n actually just to make this easier to read let's define rows as the number of rows and columns as the number of columns so rows would be length of the matrix and then the columns would be the length of the first row right we are guaranteed to have the first row by the way um and so for i is from zero to the number of rows j we said we need to start from i plus one so don't we don't swap or we already swapped and we go all the way to columns um and then we need to swap here um and so m j i so remember what we are doing is swapping i j with j i so the row the column becomes rows um and so this would be j i we want to swap that with i j i here and m i j now this is just nice in python because you can do the swapping in one operation but if you want to do it let's say in another language you could just do tom is equal to mji and then you could do m i j is equal to or actually i j here and then just override this with m j i and then after that you do j i is equal to tom that will be the same thing as doing this here so this is just assigning i j to j i and j i to i j so swapping um okay so that's for the transpose function now let's write our reverse function i'll get rid of this just to leave some space um and now we will do the reverse function which we said we just want to do it on every row and swapping is just like we do in an array we'll go all the way to n divided by two so that's just columns divided by two and for each position in that row uh we'll do i j um is going we are going to swap here you can do also what i said here if you don't want to do it the python way here you can do it with the thumb variable um like we did here um so that would be me and basically this we need needs to be swapped with i columns minus j minus one so columns is the number of values um and so that's exactly what we do here i and then columns minus j minus one and so we'll just i j would need to be this and this here we need to be j i j and that should be it so let's run this um here yeah we just need to clean this up call or submit and that passes test cases um now one thing for time complexity here we are doing for transpose of rows by column so let's just say it's oven m um all right so let's just do rows column and then if we go here this is also of rows columns right because yeah this is divided by 2 but in terms of time complexity is almost the same so it's overall it's just that of rows by columns um yeah so i think time and in terms of space we are not using any extra space so it's all one uh space um yeah so that's pretty much it for this problem please like and subscribe and see you on the next one bye
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
341 |
hello everyone welcome to quartus cam so we are today the 13th day of april leeco challenge and the problem we are going to cover is flattened nested list titrator so the input given here is a nested list and we have to implement the methods next and has next so here in java if you see the function of next and hash next hashnext will return true if this list iterator has more elements when traversing the list in the forward direction and next returns the next element in the list and advances the cursor position so we are going to overwrite these two methods here in order to return the numbers given in the nested list so let's understand this problem with an example so here is our given example so now starting from the first element in the list it is going to be a list again one comma one and then an integer and then again a list so if you get the integers from the list it is gonna be one two one and every time we call next function it is gonna return the numbers in order so how are we going to implement this so we are going to get the help of stack to implement this so here is a stack we are first going to put the elements in the stack in reverse order starting from the last point in the nested list to the index 0 why because we need to access the elements from the starting so as the stack stores the element in the reverse the first element will be at the top of the stack so we are going to put the elements first into the stack from the reverse order so now from reverse it is a list so we are going to put the list directly to our stack and then comes an integer and again a list so now we need to implement two methods hash next and next so for next method we are going to simply pop the element at the top of the stack and if we find the integer then we are going to return it simply so in this case if a next method is called first we are going to pop the element 1 and return it the same way as every time the next function is called we are going to return the next integer at the top of the stack so to implement hash next we are going to again i trade through the given stack and pop the element at the top and if the element at the top is an integer then return true as it is having a next integer or next element in the list if not if it is empty then return false so there can be another case that it can either not be empty or it not it is not an integer value but a list is the top element in the stack in that case we are simply gonna take that elements from the list and put that again to a stack so here when we pop the elements from stack it is gonna be one comma one so we are going to check whether it is having a next integer or not so in this case if we find it as a list then we are going to pop that from our list and add the elements in reverse order so that now our stack again have one and one separated and put into the stack in the reverse order so again i trade the loop and take the top element in the stack and if the element is an integer then return true if not written false so hope you are understanding this solution so let's see the code now so inside my nested iterator we are going to define our data structure so i'm gonna declare my stack in common so inside my nested iterator i'm gonna check if my nested list is empty then simply return nothing if not i'm gonna iterate my list and put the all elements in reverse into my stack so now our nested iterator is done getting into our next method we are simply going to return whatever the element is there in the top of the stack so now it's time to write our hash next method so here i'm gonna iterate till my stack is not empty so here simply we are just picking the top element in the stack if it is an integer which means we have a next integer then return true if not we are going to again pick the top list from the stack and from the reverse order we are going to put the elements of that list into our stack and finally if nothing if the stack is empty then in that case return false so yes coding is done let's run and try so let's submit yes the solution is accepted and runs in three milliseconds so thanks for watching the video if you like the video hit like and subscribe thank you
|
Flatten Nested List Iterator
|
flatten-nested-list-iterator
|
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the `NestedIterator` class:
* `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`.
* `int next()` Returns the next integer in the nested list.
* `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise.
Your code will be tested with the following pseudocode:
initialize iterator with nestedList
res = \[\]
while iterator.hasNext()
append iterator.next() to the end of res
return res
If `res` matches the expected flattened list, then your code will be judged as correct.
**Example 1:**
**Input:** nestedList = \[\[1,1\],2,\[1,1\]\]
**Output:** \[1,1,2,1,1\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\].
**Example 2:**
**Input:** nestedList = \[1,\[4,\[6\]\]\]
**Output:** \[1,4,6\]
**Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\].
**Constraints:**
* `1 <= nestedList.length <= 500`
* The values of the integers in the nested list is in the range `[-106, 106]`.
| null |
Stack,Tree,Depth-First Search,Design,Queue,Iterator
|
Medium
|
251,281,385,565
|
20 |
Hello everyone, welcome to me is the question of the channel and you have solved this question many times in college either story or story, this question is valid parenthesis, it is metal, Google, so by looking at the input and output, understand what the question is. To understand, you just have to check whether the string you have given is valid or not, so we will make it in two ways, one is a very basic method which we make from the stack, the second will always be We will have a tricky approach, okay that will also become a taxi but it will be a little different and it will be a good approach, okay, so first let's see the approach, first approach is quite simple, we will give it a simple one star, okay and as soon as we get the open bracket, either Either this or this, we will push it and as soon as we get the close bracket, this or this, we will check that to match this close bracket, this one should have open braces, it should be an open bracket to match this. It should be there to match it. If we get it then we will pop it. If we don't get it then there is something wrong with our parents and we will burn the return. If it is ok then it is best that we drive it and see. Take dry is very simple 2 minute approach ok we will create a stag and trade here now I am here first what is open bracket so put it here second what is this I am here now second what is closed bracket so Let's check whether this is an open base at the top of the start or not, what will be its open bracket, if this one is at the top of the start, which is good i.e. what will be its open bracket, if this one is at the top of the start, which is good i.e. everything is valid till now, then let's pop it i.e. these two We have done i.e. these two We have done i.e. these two We have done both of these, now I came here, okay, this is the open bracket, so pop it and then here is the science bracket, so I would like its corresponding open bracket, so we popped it, so this is Both are done, now I come here, it has an open bracket, so I pushed it. When I come here, it has a closed bracket, so which will be the corresponding open packet, which will be the one which is at the top of the stock, okay, so pop it. Will give OK, we have processed all the strings and all the characters and in the last we just have to check that our stock should remain empty i.e. our stock should remain empty i.e. our stock should remain empty i.e. all the balances are valid, only then there will be balance, so we just have to check this. After starting, if it is empty then it means everything was correct. We will return true. If not, then we will set the result. Okay, its code will also be very simple, so let's code it, after that we will serve you. Okay, so let's go with it. Let's code the court, then it's going to be simple, we will take a stock, okay [ okay [ okay Is it an open bracket or is my open bracket a square bracket, so we don't have to do anything, we have to push it in the start, okay and if not Will be able to correct the value of my K. It's great. Submit it and let's see. It's a very good project. Let's see that. There's just one trick in it. We know what we do. Like a mother, you are my open bracket. Okay, so remember it's open. We used to push the bracket on the stock, so we know what to do with this open bracket, like I just saw the open bracket, mine is also here, so what will I do, I will put its corresponding close bracket, then what is its corresponding close packet? This is right, I have given it a pulse, now let's see why it is doing this, let's come forward here, now I got a close bracket, okay, so if I got a close bracket, then I want to see that brother, this close bracket should be there in the top, correct, this is the close bracket in the top. It is a rocket, means everything is correct, so it has been popped, OK, who will it be, I am putting the close bracket, I am OK, so now let's move ahead, here comes its close, this is a closed bracket, so let's see, there should be a close packet at the top, yes, it means it is correct. So I have popped it, similarly here it is an open packet and as I move ahead, I have seen that close bracket, torch should be in the top of the rocket, yes, then everything is correct, we have popped it, okay, it is quite simple, whenever open. The bracket looks fine and whenever the close bracket comes, just check, there should be the same close bracket on the top of the stock. Okay, you have inserted open above which we saw the open bracket here and its corresponding close has been inserted. The approach itself is very simple, almost we have just done a little trick, the code will become a little cleaner, it is okay by doing this and if you have noticed in the previous approach, I had also checked st.met, then why is that? Must have been checked. also checked st.met, then why is that? Must have been checked. also checked st.met, then why is that? Must have been checked. Think like this, let's take the meaning of invalid parentheses in my string. This is my input. Okay, so first remember what I used to check in it, whether this should be there first or this should be there, then someone. No, this is fine, so I will go down and check the top of the start. Okay, so if the stock is empty right now, then perhaps I have nothing. No, perhaps mine is empty, so I will check its top. It is obvious that it will give an error because The stock is empty right now, that's why we had given the check of Start MP. The first approach is fine and the second approach is quite simple isn't it? As it appears open, it is fine to push the corresponding closed one and when it appears close, If it is then just check whether the same close is at the top of the top start or not. Okay, so let's do it will become more clear. Okay, so let's start according to this. This is also a very simple approach, right? And just @ are doing what and @ are doing what and So it must be this or it must be this because how does it go in all three? Otherwise it must be one of these three. If it gets the secondary then if it is not empty then stock and top if it is not equal to K. Okay, that means if I buy this from me, if the close bracket comes, then I would like to get this from the rocket top, this would be either from the stock top, if this is the case then I would like to get this from the jacket top. If I don't get it then I will return it first. Okay, if there is nothing like that then we will top up the stock. Okay, I have got the matching. Okay, so this was exactly the proof that we had explained in the last, what we just have to do. The stock should be empty, isn't it? When it pops up, let's run it and see if it is passing all the tests or not. You can try it too and check it out. Directing makes it clearer, but it is quite clear to me. Clean is tricky approach, it seems ok then great question using tu help koi bhi doubt hoti hai comment area aur try tu help si video thank you
|
Valid Parentheses
|
valid-parentheses
|
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`.
|
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
|
String,Stack
|
Easy
|
22,32,301,1045,2221
|
1,770 |
hi everyone let's solve this legal problem so it's a very typical dynamic programming pro problem but the um acceptance rate is not very high let's take a look at this problem so we are given two integer arrays norms and multiplies of size and nm and the arrays are one index is not important here so we begin with a score of zero and we want to perform exactly operations we have to use up all the numbers in multiply every time we choose an integer like from the start or end of nums and we multiply the integer by the numbers like the beginning of this multiplies after we use our user multiplier we cannot use this again so we need to use next number and for nums we can use the start of n after we use it we need to discuss this number so it asks us to get the maximum numbers for example for this example and the first multiply is three so we can use the n number three and we have nine then we have multiply four then we can use this multiply two then we can use this two and we get four at last we can use one so the final answer here is fourteen okay let's take a look at another example so uh what's the optimal solution for this problem and it's a little bit obvious that we need to use dynamic programming here so we need to have a two dimensional dp array dpij means the maximum value when picking i elements from left and j elements from right so dps00 means i don't pick any numbers so the value is 0 here dp100 means i pick one number from that and zero number from right so we only pick one number negative five multiply negative ten we get fifty and two zero one means i get one number from right so it's negative ten multiply 1 which is a negative 10. okay now we start to pick two numbers we start to apply two operations so for dp20 which means we get two numbers from this left so uh previously we get this for this cell we get one number from left then we get another number from left so we have two numbers from left which is uh we can use negative five multiply negative three so we have 15 and plus is 50 we get 65 and for this dp11 is a very important thing so dp1 can come from two directions they can come from uh c cell we pick one element from that then we can pick one element from right so the value is one multiply negative five so we get 50 minus five of france's cell c cell we get one element from right so we can get one element from left which is negative um three on negative 5 from left then we multiply negative 5 we have 25 and the value is 25 minus 10 so for each cell it may come from the left cell or it may come from the top cell so that's the transitive function okay let's take a look like uh how to implement it okay first of all we need to initialize this dpi array it's two dimensional and we know the size is at most and so we give and plus one here and we define local variable score and finally we retain this score okay we have this other for loop which we will iterate on times then we have the inner for loop at first i pick zero numbers from left then pick one number from left and i can pick one two three four until k element from left and we know for each cell it may come from that and it may come from top so there are two directions finally we pick the maximum number and update the dplk minus l okay one k is n we can update this score and finally we just written z score okay so the time complexity here is over and multiply okay and the space complexity here is om square thanks
|
Maximum Score from Performing Multiplication Operations
|
minimum-deletions-to-make-character-frequencies-unique
|
You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of the array `nums`.
* Add `multipliers[i] * x` to your score.
* Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on.
* Remove `x` from `nums`.
Return _the **maximum** score after performing_ `m` _operations._
**Example 1:**
**Input:** nums = \[1,2,3\], multipliers = \[3,2,1\]
**Output:** 14
**Explanation:** An optimal solution is as follows:
- Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score.
- Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score.
- Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
**Example 2:**
**Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\]
**Output:** 102
**Explanation:** An optimal solution is as follows:
- Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score.
- Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score.
- Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score.
- Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score.
- Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score.
The total score is 50 + 15 - 9 + 4 + 42 = 102.
**Constraints:**
* `n == nums.length`
* `m == multipliers.length`
* `1 <= m <= 300`
* `m <= n <= 105`
* `-1000 <= nums[i], multipliers[i] <= 1000`
|
As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.
|
String,Greedy,Sorting
|
Medium
|
1355,2212
|
1,707 |
let's go through code 1,77 maximal x with an element from our 1,77 maximal x with an element from our 1,77 maximal x with an element from our array uh for this question it give us a nouns and a quaries uh for every quy um for example 31 it is let has to find those kind of numbers which is smaller equal to the second number that one right we can use zero or one to XR St and get the maximal xrr which is return St um we intuitively what we thinking about is that we can one way we do that is we s uh this kind cories by the second uh variable right and then uh we insert um the numbers to a CH charge and um uh Portion by portion we only insert the kind of smaller than this limit then do the maximum or of this number right so if we insert St right St um that is um 0 one these kind of things right and it goes to some kind of pass and then we trying to see uh in the original chart trying to find out it's X pass um but uh um the thing that we have a limit right doing like this way uh doing like the thought is not an optimal solution uh because in that case if for example we already searched uh number um 5 100 right and then now we insert to 100 something and we see cor is always like a d Dynamic operation right so that means in the sometimes it's like a data stram now after that we come in like a 57 so all of the numbers from 8 to 100 we should remove from the Char Tree in that case this kind of complexity will be not that good right so what we are thinking about is that we insert we should insert all of these numbers to a TR tree uh in one time and then when we qu we add a limit paramet to the code okay so this is the uh bit manipulations so let's go through go over the bit operations um to review the kind beta operations uh first right so we say um for bet operation we have one and one equals one right and um one and Z equals z and uh zero and Z equals z right let's review this kind of bet op vers because every time um we do this kind of bet operation um you riew once that remember it better and know one or one equals one right 1 4 1 Z equal one right the Z or Z equals z and One X one equals so this question is ask x z 1 xr0 = 1 and then zero is zero equals zero right so this the first thing we want to review second that um to check for example the ice digit from the right if this one right so for we check a um where the I digit um from um this bits right so if is one right we can write something like this right Oneal to Z equal to zero or we can write for a uh right shift J right and one right if this one equals to one right so this is way we Che for the CH element in a with the Bas from the right with it is one or not and uh Union right Union That's A or B inter that is a and b right and uh check uh if for example B is a subet or not so what we do is that we are going to have a trying to see whether it's uh intersect is this B right and uh if B is a uh insect then uh we trying to uh get rid of B from a then that is uh a XR right of course you can write a minus B but that is not that efficient comparing to a xrb and another operation is uh um for a right the largest the stop set of a right uh we do not exclude a that is the A and A minus one right so um so this is actually removing the last um digits smallest one digits from right so there is a question count how many ones in a digits we can um write uh for example while uh a, = to zero right and a, = to zero right and a, = to zero right and a n = to a minus one right this one in the meanwhile we have counted Plus+ so that it can count to counted Plus+ so that it can count to counted Plus+ so that it can count to the um how many digits for one right and uh um the last thing we want to review is that if in some of the bit mask DP we want to iterate every sub state of State a right so what we're going to do that um for in ials a i uhal to z i equal um IUS one and a so doing like this way we can iterate every subset of I so this is a review of bit operations I think those remember this will be enough for 99% of bit mask 99% of bit mask 99% of bit mask problem for this question uh we know that we need a for every number right it has uh we can convert into a 31 lens bit binary bit chart sequence right so we create a like a child structure right TR structure um and insert every number into it so after insert something right um for uh this every CH not uh comparing to there is another question um 400 something find the maximum or two numbers in Array um we have a limit right so how can we handle this limit is that when we insert a number we can put this a not have a minimal value so that means and for each sub Tre the minimal value uh we have so when we insert we can um have these kind of values um so um just have one attributes to the ch note and the want quy right quy is that for every for the for a number right for example we have qu a number and U we have a limit that means if the minimal number on this child right uh is greater than our uh our um xrr root then we cannot go there so that we only have when um the of this can node smaller equal to the Limit we can go to um go to each uh xrr root right so we have two conditions um to find the maximum XR right so that is um if um the XR not exist right and also uh we'll make sure this number um going to this note the minimum value was smaller equal to the Limit only the two conditions we can go to this x root so is x o root and not exist the second condition is the minimal of this node right should small equal to limit if all of that greater than limit right that path of course we cannot go it is like a war right B out so using this uh kind of limit we can quate the data so let's begin to write code um so we also still have a class Tri node right and for this TR node we have a CH node array as CH and we know the value can only um because we can only be Z one so it can just have um a two size two array should be enough right new two and uh um we add one more attribute called the minimal in me let's set the initial value as integer. Max value so first thing we uh create child root equals new note uh we help write an our function insert a number right so we have a trial current equals root so for every number we know it's small equal to 31 so for each I = 31 I small equal to 31 so for each I = 31 I small equal to 31 so for each I = 31 I greater equal to Z iusus so I say uh current bit is this number right shift we check for the I uh digits with it is one or not right so uh doing like this right we just discussed to check the ice b i digit whether it is one or not can write like this so what say if this children uh bit equals now we create a new one right so when we inser because now then we have children bital newal node and we have current if current tring B right um we need to update the limit right so we know current um minimum equals mass. minimal number minum right when we insert this means for current node right current not all of this it's ch the those kind numbers the minimum number so um so if we check the root right so that means that is all of the uh numbers we insert what the minimal value of it h we can add this sign to its chart as well yeah so and actually we insert even to the leave right so for the last line um we insert one more but it um it has n right has not as chart but uh if we for last time we still we have this value it will not um affect our result because we are going to terminate when we search to the last note so we are going to have probably find the Max uh in n in limit right so what we are going to do is that we also have par current equal Ro so uh before we check this number through the XR pass right so we're trying to see with this root if current do mean is smaller than limit right that means there is no number um greater than our limit then we just return minus one we have result goes to zero right and 4 in 31 I great equal to Z iusus so I have in bit equals we have this number right shift I and one right this is the from the right we trying to see whether it is one or not so um what say that need to have two conditions so if current do children um f xr1 right in this case um we're going to the bit xlr1 pass and but we have another condition is that we need to make sure um this one it's minimal value right should smaller equal to our limit we can only on this kind of we can go to um go to this pass right and go to this pass we have result uh we add equal to this digit right so that is one and shift left shift I and also let's have bit XR = to one right and then we have bit XR = to one right and then we have bit XR = to one right and then we move to it chart so that is uh current children bit and the end result okay so the first thing we do is we compose a tree in L in LS insert right so after we doing like this we compose the tree and the second that we cor the result umal new in and we going to do is for i z i smaller than n i ++ and result I equals smaller than n i ++ and result I equals smaller than n i ++ and result I equals find Max the first is the number to X to always right so that is I zero and the second one is limit right I one in the end we just a return result what you so insert car me isal so H this is greater right so that means if we for the root the minimum is greater than limit so that means everything uh in our sub tree they are greater then we return minus one right okay so if there are in quaries so that so this if there are any numbers right the insert will be 31 multip by n so if there are CU ques right um for every qu it is 30 uh um lens 31 operation so it is Q MTI 31 right
|
Maximum XOR With an Element From Array
|
check-if-string-is-transformable-with-substring-sort-operations
|
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`.
Return _an integer array_ `answer` _where_ `answer.length == queries.length` _and_ `answer[i]` _is the answer to the_ `ith` _query._
**Example 1:**
**Input:** nums = \[0,1,2,3,4\], queries = \[\[3,1\],\[1,3\],\[5,6\]\]
**Output:** \[3,3,7\]
**Explanation:**
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
**Example 2:**
**Input:** nums = \[5,2,4,6,6,3\], queries = \[\[12,4\],\[8,1\],\[6,3\]\]
**Output:** \[15,-1,5\]
**Constraints:**
* `1 <= nums.length, queries.length <= 105`
* `queries[i].length == 2`
* `0 <= nums[j], xi, mi <= 109`
|
Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering.
|
String,Greedy,Sorting
|
Hard
| null |
1,619 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problems name is mean of an array after removing some elements so in this question we are given an array called Yara we have to return the mean of the remaining integers after removing the smallest five percent and the largest five percent of the elements coming to the function that they are given us the return type is double so we have to return a double value trim mean is the function name and the parameter is an integer array ARR now let's take a look at the example and see how this can be solved using a Java program so this is the input array given to us and we need to display the mean after removing the smallest five percent and the largest five percent of the element first let's take a look at the steps we need to follow and then we'll do a dry run for this example first we have to find the length of the array they have given us the input array right we have to find the length and then we have to sort the array in ascending order for this you can use the irs.sort as they have said can use the irs.sort as they have said can use the irs.sort as they have said we have to remove the smallest five percent and the largest five percent of the element so first let's calculate the five percent of the length so this five percent of the elements can be found out by the formula five percent of the length into five by hundred into the length of the array and store it in a double variable called limit so this is the limit or the range which we have to remove so instead of removing the element what if we can ignore the smallest five percent and the largest five percent and place the new two pointers that is the start and end and between those two pointers you can find out the sum and then divide it with the new length between that range and find the average for that let us find the starting index the new start index can be found out with the limit value so this is the sorted array we have you can find out the new start index by removing the smallest five percent and the new end index by removing the last five percent because the array sorted finding out the length of the array and subtracting it with the limit that will give you the end in between these two intervals find out the sum and divide it with the new length between these two intervals so that you can calculate the average now let's perform a dry run for this input array first we have to find out the length of the input array is 20 then you have to sort the array in ascending order so this array you have sorted it in ascending order now we have to find the limit that is 5 percent of length 5 by 100 is equal to 0.05 into length is by 100 is equal to 0.05 into length is by 100 is equal to 0.05 into length is equal to 20 or 0.05 into 20 is equal to 20 or 0.05 into 20 is equal to 20 or 0.05 into 20 is equal to 1 so the limit is 1 so you have to remove the smallest one element and the largest one element and that will be the new interval so the new interval will now be start is equal to limit so limit is 1 now and end is equal to length minus limit so 20 minus 1 is equal to 19 start is one right so we are here and end is 19 so you are here so you have to find the sum of elements between these two intervals so to find the sum between those two intervals you'll use a for Loop well I will start from start variable and it will iterate till end variable the sum of that so sum of all these elements is equal to 72 and the new length is equal to the length between start and end add a new variable for new line and increment it by 1 for each iteration so when you start from start and go till end each time you increment a new length variable by 1 and when you terminate that for Loop you will have the length of the new interval so that is 18 so now that you have the thumb and the new length you have to find out the average by dividing sum by new length 72 divided by 18 will give you the value for 0.00 so this will be a double value for 0.00 so this will be a double value for 0.00 so this will be a double value so you have to store average in a double value so you'll get this output now let's quickly coordinate up with Java let's follow the steps I've mentioned first we have to start off by finding the length of the input array I'm going to store it in a variable called LAN now we have to sort the input array in ascending order so arrays.sort ascending order so arrays.sort ascending order so arrays.sort array now let's find the limit and store it inside a double variable so double limit is equal to now you have to find out the five percent of the length so 5 by 100 is 0.05 by 100 is 0.05 by 100 is 0.05 into length now that we have the limit let us find the new interval start and end so let's declare the two variables and start will be limit but here limit is a double value and you are storing it inside the integer so first let's convert it into an integer Orient limit now to find the end interval and end is equal to length minus limit again limit is a double value so you have to convert it into an integer first now that we have the two intervals let us use a for Loop to iterate from start to learn I will be start it will iterate till n now we have to find the sum of each element and store it inside a double variable so first declare the variable double sum initialize it to 0 and you also need a new length variable right so initialize it to zero notice that I'm using the data type double because the return type is double so you need to divide sum by new length which have to be in double so sum is equal to sum Plus ARR of I will be now pointing at start and it will be going until end for each iteration you have to increment the new length variable so that by the end of the for Loop you'll get the new length between the two intervals now let's calculate the average store it inside a double variable I'm going to name it AVG now divide sum with the new length and finally return the variable average AVG now let's try to run the code now we have to use the variable length let's try to run the code again there you have it by getting the expected output let's submit the code there you have it our solution has been accepted which is faster than 52.24 accepted which is faster than 52.24 accepted which is faster than 52.24 percent of the Java online submissions surprisingly it's taking long time last time I executed it was faster than 99 percent maybe it varies because of various factors so you can ignore this as of now time complexity for this solution is O of n log n and the space complexity is constant of 1 because we are not using any extra space we are only using variables which is constant space that's it guys that's the end of the video thank you for watching and I'll see you in the next one
|
Mean of Array After Removing Some Elements
|
path-crossing
|
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105`
|
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
|
Hash Table,String
|
Easy
| null |
638 |
hey what's up guys this is sean here so today uh let's take a look at lead code number 638 shopping offers okay so your elite code store like there are n items to sell okay and each item has a price but we also have some like special offers and the special offer consists of one or more different kinds of items with a sale price basically with a sales offer you can use this sales price to purchase multiple items at once or altogether right and then you're given like an integer array price where the price is the price of the item okay and the integer array needs okay the needs means that your that's the total number of items we want to purchase okay and then for this special what is for the specials it's uh it's a list of lists okay where the you know special eye basically it's just like an offer right and the spec and the list inside this special offer is the uh the length is n basically tells you for this special offer uh what are the items you can buy business offer and so the reason we have unplugged one is because you know for the zero to n minus one is all the items we can buy for this offer and the last one is the price for this offer okay and then you need to return the lowest price right you need uh the lowest price to buy the exactly this needs uh this needs items you cannot buy less or more you have to buy exactly this many items and one of the constraints that you know you're not allowed to buy more items than you want right even if that you it will lower the overall price so which means that you know let's say in uh in this special offer here you know for example in this offer so which with five dollars you can buy three uh the first item and zero second item so let's say in this case we have uh we have two items left we have the two first items left now we so and then you cannot use this special offer because three is greater than two which means if you use this offer you're buying more than we need right that's why you know in this example uh one here right so we want to buy two the first item and the five of the second item and we have uh two special offers here you know and sorry so this is the price this is not the need so the price is two and five we want to buy three first items and two second items right yeah i mean maybe i should use this i should have used this one that's why you know in this example one here right uh the answer is 14 because the best strategy for us to use these special offers oh well and we can use special offers as many times as we want right so there's no constraints for that is to use a special offer too to purchase uh one of first item and two of the second item so after using the special offer number two here we have we only have two we're gonna have three two right so after using this the first special the second special offer we have two zero left right and that's why we have we then we'll use ten dollars to purchase this one and then plus uh we have two laps no for two you know see we there's no other special offer we can use that's why we have to use the price to purchase the remaining the remainings right that's why we have 2 times 2 which is 14. it could also be that you know the special offer was would end up spending more than directly using the price right because as you guys can see right so the price could be zero right so it means that you know it there could be a possibility that you know all the price are zero so which means that you know we will not even use any special offers we simply just use zero dollars to purchase all the other items we need right and here are some constraints right so we have it's not that big because you know so we have kind of an um we only have like up to six uh items we want to purchase and for each item the amount is like 10 right and the special offer is like up to 100 right so for this problem you know uh you know obviously we can use the dfs right basically we can just simply the starting state is like it's this three and two right at this state you know we have many options you know we can use try to use any of the special offers right and once we use that you know the needs will be updated or we don't want to use it right or if when if we don't want to use it means that we want to use the price to purchase our everything okay then we can at each of the state we can just simply try out the possible scenarios right but it turns out that you know we can memorize the result right so the reason being is that you know given like a state so a state is what state is the remaining items that we want to purchase right so let's say we have like this kind of items right let's say we have five items we're going to purchase you know given like an estate a number of these five items left you know let's say two one zero four five right you know the minimum amount that we need to purchase this given state of the items is fixed right so which means that no at the beginning let's say we have 9999 right we have this is the starting state right we could have multiple like uh branches that can lead us to the same state here because we have multiple uh special offers right the combination of you of use of the usage of different special offers can lead might may lead to the same state right it could be like this and then here right or this and here so which as then as you guys can see you're right if two if multiple different paths lead to the same state we shouldn't recalculate the state right so which means we can just memorize the result right hence this is like actually a top-down dp problem right actually a top-down dp problem right actually a top-down dp problem right where the state is this kind of is the current needs right yeah i think that's the only state we need to maintain here because there's no other state you know and we have to maintain all the other numbers here because you know the sequence also matters and yeah so that's why you know we cannot use the beat mask because you know not only we need to maintain the all the audio the numbers but we also want to maintain sorry we need to maintain all the different numbers on each of the state it's not like zero or one it's not a peak or not peak that's why you know we cannot use speed mass so we have to use a tuple to memorize this kind of state okay cool so then we can start coding then right i mean since we're going to use the top down dp right so we have the knees here right and it's going to be lru of cache none right and then we have n gonna be a length of price okay and then the uh we're gonna return dp right you know in python you know since you cannot use a list you cannot use the list because at least in python it's not hashable because this is immutable that's why if you want to hash it right or you want to basically want to store it by using this kind of python decorator you have to convert it into a immutable data structure which is the tuple okay so and now right i'm going to convert it back to the need list because we need to update it based on the special offer right so first special offer you know basically we have first special in specials we need to check each special offers and then here we have to return the answer right i'm trying to write the uh the main logic here right so the answer is you know at the beginning the system max size okay but there okay one thing to be careful is that you know as you guys can see we have i mean two category two set of options we can take here we can either try to use one of the special offers at the current state or we don't we or we can just use the price to purchase the current one okay to use a special offer it's kind of straightforward right if we take that special offer we just subtract everything from the special offer right then we increase the price by that special offer but for this kind of if we don't want to use the special offers which item we want to buy with a price right i mean if we try to write another for loop here you know for each of the items and then we try to decrease the items one by one you know that will basic that will definitely tle right let's say we have uh of this many of items here you know so for this kind of uh scenario where we don't where we want to use the price to purchase any of these items and if we want to use this if you want to use this one you know to purchase this one if we only decrease it by one so let's say we have five right so you if you want to use this one so let's say okay so next set will be five a four five something like this and then we also can we can also have like this five four right five if we try to enumerate the scenario in this way you know that'll be too much for us to calculate so it turns out you know actually if we don't use a special we can simply just use assuming we want to use the price to purchase everything in the knees here so the reason being is that you know because at each state we only need to calculate this thing once so this is what i'm trying to say here basically the base case will be like this so we're going to be sum of the need list of i right price times the price i for i in range of n so here i'm i don't use the use price regular price okay to purchase everything so the reason being is that so the reason we don't what we don't need to uh purchase items once at a time is because you know like i said we only have two options right so we eat at the current state we either choose a special offer or we don't choose a special offer right so which means that you know we don't have to purchase items uh one by one and try to purchase each items uh try to purchase items for each of the need right we can simply assuming we want to purchase everything with a regular price because let's say we have because let's say the final end is we want to use special offer special over two right plus special alpha one right plus special out for uh five okay and then plus the uh the regular one right as you guys can see you so let's say this is the final state basically it's the optimal final state doesn't give us the minimum uh total cost all right as you guys can see we will only have one right regular purchase regardless and all the others are the uh our special offers we will be using okay so which means that you know at each of the state actually there's no need to try to use a regular price for each of the items because we can simply assuming right and there will only be one uh case that will be using the regular price it doesn't really matter which one it is or where we'll be using that regular price since we will try using the regular price at each of the state so this means that you know sub with the given state subtracting the special offers we need the rest will be everything basically there will always be a state that you know we'll be using the regular price to purchase all the remaining items that's why you know at each of the dp state here we can simply we can safely use this assumption here because like i said there won't be any there won't be like a two regular like uh purchase here right there oh they're always going to be one okay so that's the that's a improvement here right and here try to use a special right offer okay so to try to find a special offer you know uh there's some like tricks uh small tricks we can use here because you know for the special offers you know we will be uh subtracting the numbers from the special offers but since we're try we're trying all the special offers just basically this is a little bit backtrack here right once we subtract from the special offers we need to put them back okay so for my case i just have two for loop here for the back tracking you can do it in your own way it doesn't really matter so need list of i right miners s i right so the special offers basically if the need at least i is smaller than zero right it means that you know we cannot use this special offer but i don't want to break here because i will need to put them back it can use so and if this one's smaller than zero it means that you know the remaining need is smaller than the ones in the spec than offer which means we cannot use it okay so here uh now we can do a backtracking with a dfs right so and so the price we're gonna accumulate is x minus one which is the last element for this special offer right and then the updated needs will be when we convert it to the converted back to this tuple okay and then back into a backtrack we add those them back okay right in range of n do we need list of i right and then we do this s i okay uh yeah i think that's it if i run the code accept it right all right cool so passed right so for the space uh sorry for the time complexity you know for top-down dp complexity you know for top-down dp complexity you know for top-down dp problem you know the time complexity always equals to the number of states times the time complexity inside this dp right so for this for the states here right uh we have six numbering total and on each of the numbers we have up to 10 values so the worst case scenario you know the needs will be what the state will be 10 to the power of 6 right because at each of the state we have at each of the number we have 10 and we have 6 in total and then inside here we have a for loop here right because here you know n is like only six but the first special we have what one hundred so that's why you know we have a one times 100 right and inside 100 we have this kind of n here it's going to be a times 6 i think right yeah there's a photo here four of our of six so that's going to be the worst case scenario time complexity oh this one is pretty big but i think in reality you know we won't since we have this kind of offers you know basically we won't process we won't explore all other 10 to the power of six states because you know for the offers we usually just uh will decrease multiple like uh items the numbers at once so this is the worst case scenario but i believe we won't need that many times many scenarios because at least based on the test case will not explore all the sub problems you know that's one of the feature of the top down dp is that you know we won't we only explore the necessary sub problems you know we won't be able to uh go through all the other possible sub problems right and for space is basically the number of the states here right it's going to be a 10 to the power of 6 yeah times what times the uh times 6 right because the length of the tuple is 6. so that's this is the time and this is space and yep i think that's it for this problem okay and thank you for watching this video guys then stay tuned see you guys soon bye
|
Shopping Offers
|
shopping-offers
|
In LeetCode Store, there are `n` items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array `price` where `price[i]` is the price of the `ith` item, and an integer array `needs` where `needs[i]` is the number of pieces of the `ith` item you want to buy.
You are also given an array `special` where `special[i]` is of size `n + 1` where `special[i][j]` is the number of pieces of the `jth` item in the `ith` offer and `special[i][n]` (i.e., the last integer in the array) is the price of the `ith` offer.
Return _the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers_. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
**Example 1:**
**Input:** price = \[2,5\], special = \[\[3,0,5\],\[1,2,10\]\], needs = \[3,2\]
**Output:** 14
**Explanation:** There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
**Example 2:**
**Input:** price = \[2,3,4\], special = \[\[1,1,0,4\],\[2,2,1,9\]\], needs = \[1,2,1\]
**Output:** 11
**Explanation:** The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.
**Constraints:**
* `n == price.length == needs.length`
* `1 <= n <= 6`
* `0 <= price[i], needs[i] <= 10`
* `1 <= special.length <= 100`
* `special[i].length == n + 1`
* `0 <= special[i][j] <= 50`
| null |
Array,Dynamic Programming,Backtracking,Bit Manipulation,Memoization,Bitmask
|
Medium
| null |
338 |
hello everyone welcome to day first of march record challenge and i wish all the viewers of coding decoded channel a very happy mahashivaratri the question that we have in today's counting bits here in this question we are given an integer value n we need to identify the number of ones that exist in all the numbers starting from 0 up till n we need to return the count of once in the binary representation of all such numbers in the form of an output array for example here n happens to be 2 and there will be 3 numbers 0 1 and 2 we need to count the number of 1 in the binary representation of these numbers and return it as the output i'll be walking you through two approaches to solve this question in the presentation so let's quickly hop on to it counting bits lead code 338 it's an easy level question on lead good and i totally feel the same after solving this question you will understand how important it is to analyze these test cases at times when you analyze all the test cases appropriately then the answer lies in front of you without further ado let's talk about the solution so here i have represented numbers starting from 1 till 20 unless let's assume in the question it was specified that the value of n happens to be 20 what we can do we can start the iteration starting from 0 up till 20 and we can generate the binary representation of each number we can count the number of ones that exist in the binary representation and return the final output as the answer this is naive and the basic approach that comes to everybody's mind when they read this question however can we do something better than this the answer is yes so for that let's analyze few numbers what are those numbers let's start with 2 if you look at the binary representation of two you can see that it holds only one at the second index if you go and look at the binary representation of four again you will see that it contains the same number of ones as two contains it's just that the position of one has been modified but the number of ones remains the same so let's write that here why does it remain the same because when you perform the left shift operation of 2 you get 4 left shift operation simply means you are multiplying the number by 2. as a result of which the number of ones in 2 and 4 remains the same so let's proceed ahead let's again perform the left shift operation which number do we get 4 into 2 which is 8 highlighted over here again you can see the number of 1 remains the same which is 1. let's move further ahead let's perform the left shift operation on 8 what do we get 16 so here the number of ones again remain the same pretty awesome and quite understandable so whenever we are multiplying the number by two the number of ones remains the same in the generated number or the output number let's take few other cases let's take the case of 3 or so here what do you see that the number has two ones in it so let's write two here and let's talk about the same scenario we perform the left shift operation when we perform the left shift operation what do we get six again in six the number of one remains the same let's perform the left shift operation on 6 what do we get 12 so in 12 the number of ones again remain the same which is 2 so here we are just sliding it towards the left so these two ones have been slided towards left and we get this number and since 24 is beyond our range i'm not writing it over here but again in that number the number of two remains the same let's take few more possibilities and let's shoot for five this time so what do we see the number of ones and five happens to be two and let's perform the left shift operation by a single unit what do we get 10 and number of one again remains the same which is 2 again in 20 the number of 1 remains the same you are performing just left shift operation by 6 by a single unit and the number of 1 remains the same that is 2. if you have understood this much you have understood 50 percent of the algorithm now let's talk about the rest of the part what we are going to do we are going to draw pairs here and i'll talk you how these pairs are helping us arriving at the solution so if we know the number of ones and two can we draw the number of ones and three the answer is yes it will be one higher than that of the even index so at the even index which is two what are the how many are the number of ones it happens to be one so you add one to it and you get the number of ones and three which is two similarly for generating the number of ones and four you can use the previous half position so when you divide 4 what do you get 2 so using 2 you can generate the number of ones in 4 which will be same as that of 2 which is 1 so you have you can identify the number of ones in 4 and 3 using 2. let's proceed ahead next what do we can simply check the number of 1's and 5 using 4 consider these two as pairs so number of ones in four happens to be one you add one to it you get two pretty awesome and straightforward again let's move ahead the next number that we have is six so we can identify the number of ones in six using three so we divide this number by two what do we get three number of ones in three happens to be two as a result of which the number of ones and six again happens to be two so far we have built the table up till six let's proceed ahead next we see is seven happens to be odd in nature since it's odd you look out for immediate lower value at the even index seven minus one is six the number of ones in six happens to be 2 so you add 1 to it what do you get 3 so you update it to 3 let's proceed ahead next we see is 8 since 8 is even in nature what we will do you divide that number by half you get 4 the number of ones and four is one as a result of it the number of months and eight again happens to be one let's proceed ahead next we see is nine is odd in nature since nine is odd you will look out for immediate lower value which is eight it is even you check the number of ones in that number which is one and you add one to it so you what do you get two so far we have built the list up till nine let's proceed ahead next we see is 10 so 10 is an even number whenever you see an even number what do you divide it by 2 what do you get 5 you check the number of ones in 5 which is 2 so you add 2 here pretty awesome let's proceed ahead next we see is 11 is odd in nature you will fall back to checking the number of once in 10 which is 2 and add 1 to it so the binary representation of 11 is something like this sorry for the typo and the number of one comes out to be three let's proceed ahead you see 12 so 12 being an even number what do you check the number of ones and six that you have already computed so you copy paste the same value over here so it gets two let's proceed ahead next we see is 13 is an odd number what do you check the number of 1 12 which is 2 so 2 plus 1 gives you 3 so you add 3 here let's proceed ahead next we see is 14 at 14 what you will do it's an even number you'll fall back to seven so fourteen by two is seven has three ones as a result of which fourteen will also have three ones let's proceed ahead next we see is fifteen number of 15 is an odd number so what do you check the number of ones in 14 and you add one to it so 3 plus 1 is 4 as a result of which the answer becomes 4 let's proceed ahead next we see is 16 is an even number you what do you divide it by two you simply go and check the number of ones at eight we see one as a result of its answer becomes one let's proceed ahead next we see 17 is an odd number what do you divi you check the number of ones in 16 and add 1 to it so 1 plus 1 gives you 2 and the answer becomes 2 let's proceed ahead next we see is 18 is an even number what do you divide that number by 2 you get 9 the number of once in 9 is 2 as a result of it the answer here becomes 2 next going ahead we see 19 of an odd number you fall back to 18 you check the number of ones and two you add one to the answer becomes three next you see is twenty is an even number what do you divide that number by two you get ten the number of ones in ten happens to be two as a result of it the answer here becomes two in this manner we have successfully identified the number of ones in all the numbers starting from 0 up till n and this is the way to go to conclude it further let's quickly have a look at the coding section here i've created the answer array and it will be of size nums plus 1 because we are looking for the range starting from 0 up till n and by default nums of 0 will be 0 zero you can skip this statement or you can write it to be explicit you start the iteration from i equals to one i is less than equal to n in nums and with each iteration you will increment the pointer of i if i happens to be of even value even in nature what do you divide what you divide i by 2 and you check the corresponding answer that has already been set and you copy paste that value at ans of i otherwise if i is odd you simply compute the answer from the even index i minus 1 and add 1 to it in the end you simply return a and s the time complexity of this approach is order of n and the space complexity again is order of n for building the answer 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 being it have a great day ahead and stay tuned for more appreciation coding decoded i'll see you tomorrow with another fresh question but till then good bye
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
74 |
hey what's up guys Nick white here I do tech and coding stuff on Twitch in YouTube and I haven't made a video in a while but I want to get back into it so I just ate a giant cookie and some jelly beans I got my brain working and we're gonna do some problems today this one is searched in a 2d matrix and it's so hopefully you guys know about searching so let's get an example here right so in a sorted array so actually that's first of all in a unsorted array you just kind of have to do a brute-force usually and kind of do a brute-force usually and kind of do a brute-force usually and kind of loop through the whole array and find something right if you're looking for the number seven in a number in a you know a hundred numbers that are all kind of random numbers then you're probably going to have to just loop through the whole thing and yeah that's it now if it's sorted in a simple sorted array like let's say this one let's just take this one for example this is a sorted array so what if we wanted to find the number eleven right you could go loop through the thing with a for loop and go this 11 is this oh it is okay we got it but that's gonna be like what six times or something before you find it but you could also do a binary search which is logarithmic run time compared to linear where you search through everything logarithmic you cut out half the search space each time so we would look at the middle element we'd say okay we're in seven and this is only for sorted rates so if it's sorted you can do this in it's way faster so we see oh seven is in the middle well I'm looking for 11 so I know it's got to be on the right side and then you look at the middle of you're just like okay it can be over here so you just delete it basically and then you look on this side and you're like oh look 11 right in the middle so you just check the middle each time and then you make a decision to cut out 1/2 then you make a decision to cut out 1/2 then you make a decision to cut out 1/2 of the search space that's logarithmic and it's way faster so I didn't even know this until I just did this problem but you can actually do and it makes sense I guess if I thought about it I would have figured it out but you can actually just do a logarithmic binary search in a 2d array - you just have to search in a 2d array - you just have to search in a 2d array - you just have to do a little math on the indices so you can just imagine this as a 1d array you can kind of imagine it like this and that would be it's kind of the same exact thing we just have these extra sub arrays that are just kind of there so we have to use indices to find the right spot so let's explain as we go so first of all we'll just do if matrix dot length is equal to zero we'll just return false and then in like every other 2d array problem we'll just get our number of rows so we'll do matrix domain we'll get our number of columns matrix of zero down and we will start our binary search so hopefully you guys are familiar with a binary search do you have a left you have a right is usually the very end of the array so in this case we would imagine you know in a 1d array you would just say okay it's just the length of the array minus one because we're gonna be doing it by indices in this we're gonna do the length and width of the array multiply to get to the last element so right it would be four times three that would give us 12 so that's the twelfth element and we're just gonna do minus one because the first element so is zero like in to see why it's wise so we'll do write is equal to Rho times columns minus one is just the index thing right because the first index is zero hopefully you guys you should know that if you're doing a medium Liko problem so regular binary search here right while left is less than or equal to right you calculate a midpoint so the middle element of the Ray and we're imagining it as 1d array so we have the last element of all of we have this bottom right corner we have this top left corner right left is the top left right is the bottom right and we want the middle so we're gonna grab something like 11 right so we'll do midpoint is equal to left plus okay this is the regular way that people don't understand this is how you do it okay right left + this is how you do it okay right left + this is how you do it okay right left + right - left / - it's not just right / - right - left / - it's not just right / - right - left / - it's not just right / - it's not just like something like that it's left + right - left abide by - for it's left + right - left abide by - for it's left + right - left abide by - for integer overflows we don't have to get into it this is just how you get the middle element just accept it's if you have a huge number in certain languages you have to write it like this it's not length of the array / - dude if it's not length of the array / - dude if it's not length of the array / - dude if you're if you do that it's kind of wrong so there's languages where the numbers get too big and it could mess it up seriously bad and make the numbers negative energy overflow it's what it's called and then in this case we're going to so in a regular binary search let's just say we would do something like this if array of midpoints is equal to target return true else if target is less than array of midpoint we'd return we would set left equal then no then we know it's on the left side so we'd set right equal to midpoint - one Elsa right equal to midpoint - one Elsa right equal to midpoint - one Elsa target is greater than array of midpoint we would say left equals midpoint plus one hopefully this makes sense so in a regular binary search we do we'd have a sorted array and we would check the middle element if it's equal to what we're looking for we found it so we say true otherwise if it's less than the middle element then like I said we're gonna just be like okay it's not on the right side so we'll just look on the left side and then we so we set the right pointer it would go from you know 50 to like 11 and we would just keep searching on the left side right for whatever we're looking for 3 we would see okay 11 it's less than 11 so we only search on this side this is basically garbage and the same thing for the other thing if it was 34 we'd search at 11 and we left for 30 right okay but we can't do this here right because this is a matrix and we have to specify row and column indices so what we want to do is actually just calculate the midpoint element so what is the midpoint element is equal to matrix of and when we calculate the midpoint element we can now do this if the midpoint elements equal to the target then we return we found it if it's less than MIT if targets less than the midpoint element we'll do the same thing and if targets greater than the midpoint element it's the same exact thing we just have to calculate the element and do the right calculations on the matrix indices right because you can't the midpoint right the midpoint for this array from 0 to 12 that is 0 plus 12 minus 0 divided by 2 that's like 6 right 0 1 2 3 4 5 6 it's like 16 or 11 or something like that actually we did minus 1 so it's 11 right is minus so right as in 12 it's 11 so 0 plus 11 / so right as in 12 it's 11 so 0 plus 11 / so right as in 12 it's 11 so 0 plus 11 / - right so the we're at 11 right now - right so the we're at 11 right now - right so the we're at 11 right now right but you can't just do matrix of 5 is not that would be the fifth row there's not five rows does that make sense like in this case we have to do a row and a column if we just did matrix of five which art so our midpoint is five in the midpoint value is equal to 11 like you can't just say matrix of five though to get this value you know like it has to be a row and a column so we would actually need matrix of one in one right it's one that's 11 it's not five right see it's the zero this is zero throw is the first row first column right so that's 11 that better makes sense now and to get that value this is all you have to do you just have to do it's equal to midpoint / column to do it's equal to midpoint / column to do it's equal to midpoint / column to get the row / columns to get the row in get the row / columns to get the row in get the row / columns to get the row in midpoint modulus columns to get the column and if you think about that it really shouldn't make sense to you I had to think about it for like probably of 30 seconds or something before it made sense I'll explain it - I just want to sense I'll explain it - I just want to sense I'll explain it - I just want to make sure it works okay what did we do did I spell something wrong it's mid Pont know we want midpoint so sorry about that let's do this one more time hey we got it okay perfect so that's the binary search 100% of solutions would be binary search 100% of solutions would be binary search 100% of solutions would be tit and the midpoint element why do we have to do this well let's look the midpoint would have been 5 right so 5 is 11 right so 0 1 2 3 4 5 so to get this in a 2d array we would do 5 divided by columns and what is columns is 1 2 3 4 5 divided by 4 that's gonna give us like one point something but it's gonna we're just gonna arounds down to one so we got one and then modulus columns is five modules columns 5 divided by 4 is 1 remainder 1 so we get 1 wanna here now if you just think about it you have to divide to get the row number you the midpoint divided by columns will easily give us the row number because it'll be the number of rows it's so obvious it's almost impossible to explain like the midpoint divided by the number of columns it's just like obviously that's going to give us the number of rows and modulus the number of columns gives us the position I don't really even know how to explain it any better than that like it's so obvious please just like look at it and like think about it I mean just because like if it's 5 and you divide by it's so hard to explain these things sometimes like and you divide by it's like it's a new row every time you hit 4 like there's 4 column there's 4 columns in this right so once we're past the fourth indices so we're at the fifth one for this midpoint once we're path before us past the fourth one that's one row right so if we went to eight that's two rows so if we went to 12 that's three rows right so if you do five divided by if you do the midpoint value in a 1d array divided by the column you're gonna get the perfect row like other than that and that's pretty obvious please understand that like I really hope you do and then modulus is pretty straightforward to get where it is in that column too because it's just how much it went past so if it's five and there's four columns that we know it's in the first row and then we had one remainder after that division so it's in the first column - so I mean it's in the first column - so I mean it's in the first column - so I mean it's pretty obvious I think I explained it well enough but yeah that's how you do a binary search I didn't even know you could do a logarithmic binary search in a 2d array so when it's sorted you can I guess that's pretty obvious but thanks for watching I think this is a useful thing to know and I'll see you guys next time
|
Search a 2D Matrix
|
search-a-2d-matrix
|
You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104`
| null |
Array,Binary Search,Matrix
|
Medium
|
240
|
763 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem partition labels this is a very interesting and somewhat unique problem we are given a string s and we want to partition the string into as many parts as possible so that each letter appears in at most one part and what we want to return is the list of integers representing the size of each of these parts so let's actually start with the second example this time because i think it really helps to illustrate how to solve this problem and kind of makes it simple just starting from left to right let's take a look at the first character it's an e character right we want to partition this into as many parts as possible but each character such as this e can only appear in a single partition so what we would want to do is just say okay cut it right here right this is a single partition great but we can't do that why can't we do that because there's actually multiple e's in this string there's another e all the way over here and our partitions have to be contiguous as soon as we see the first character and we see that it actually occurs way to the right in the string we will never be able to partition the string here anywhere right because at the very least we know that this has to be one partition and if we do partition it like that this i think is nine characters but we actually can't even partition it here either and we can figure that out just by looking at the second character is a c now there's a c over here there's another c over here and that's perfectly fine but the reason we can't partition here is because there's a c in the last position only by looking at the first two characters we realize that the entire string is going to be a single partition we can't partition this any further and so what we're going to return is we have a single partition and the length of that partition is 10. so this is the list that we are going to return in this case so you might be starting to get an idea of how we can solve this problem in general but if not don't worry about it because that's exactly what we're going to talk about right now so let's take a look at another example in this case we're given a string and the result is that we can split it into three partitions the first partition is going to be nine characters the next partition is gonna be seven characters and the last one is gonna be eight but let's try to figure out how we can arrive at that solution and how we can make it as efficient as possible so let's take a look at this string and let's use the similar idea that we talked about in the previous example so we look at the first character it's an a now immediately we know that we can't partition this at this point right this cannot be a partition if there are additional a characters somewhere in the string and not only that we could have multiple a characters and we do we have an a character here and that's the last one now which one of these do we care about the most we care about the last a character the most because once we stop here we know for sure that all of the a characters are in this portion of the string and that's what we're trying to do we're trying to create partitions where all a characters are going to be here not anywhere else in the string not in any other partitions so wouldn't it be convenient for us every time we see a character if we could automatically know where the last index of that character happens to be and maybe just maybe this character itself could be the last occurrence of a this index could be the last position where a exists well conveniently for us we can do exactly that and we can create a hashmap so we can create a hashmap just like this one where we take every single unique character in the input string and we map it to the last index that it occurs at so for example you can see the indexes are a little bit messy but we can see that a ends at the last occurrence of a is at index eight so we can map a to the character a to index eight the last occurrence of b is going to be at index five now i could do this for the entire string but we have a ton of characters so i don't want to waste my time too much but just assume that before we even start iterating through the array we build a hashmap just like this one and the time complexity of building this hashtrap isn't going to be bad because all we have to do is just iterate through the entire uh string so the time complexity and space com the time complexity will be o of n technically we're guaranteed that every character in here is just going to be a lowercase abc character so the memory complexity of this hash map is really going to be uh you know big o of 26 so constant memory complexity not too bad okay now before we start iterating through the array let's think about how we're going to approach this algorithm remember we are going to have an output which is going to tell us the size of each partition as you can see up above so it would be helpful for us as we're iterating through this if we maintain the size of the current partition ourselves initially we can set that to zero and as we iterate through this for example we get to the first character we see it's at index zero but the last occurrence of a is at index eight so we can keep track of another variable let's call it end you could call it whatever you want but end which is gonna tell us what's the end of our partition as far as we know so far right because we see the character a and we know it exists the last occurrence of it is over here so we assume so far we're assuming that this is going to be a partition but we don't know for sure just yet because we have some b characters here it's possible that one of the b's exists even farther than that and if that's the case then of course we have to update our ending but in this case that's not the case because the b's are actually uh within the first partition so let's see this algorithm in action okay so far our size is zero we get to the first character our end is zero so far but we know that a the last occurrence of it is at this index so we update our end to be index a we get to the second character b the last occurrence of it is five is less than eight so we don't have to update our ending just yet and by the way actually we'll be we'll have incremented our size we'll have incremented to one after we iterate the b or the a character and we'll have now uh updated it to two after we have visited the b character again we get to an a character so we know that we don't have to update our end because the a's last occurrence is still here but we can increment our size now to three we see a b character we've already seen it before okay now we see a c character we've already seen a b before so we can go ahead and update the size to four now we see a c character for the first time so where's the last occurrence of a c character it's all the way over here at index seven of course we're going to get that from our hashmap in constant time since it is a 7 we don't have to update our end again so we are good to go but we can increment our size now to 5. now we get to another b character so no major updates here we get to an a character again we get to a c character again no major updates but at this point our size will actually be eight now we get to uh the last a character so now our size is actually nine but what's special about this position well this position we're at the index where our end uh value happens to be as well so what that tells us is every character in this uh partition only occurs in this partition none of these characters are found anywhere to the right side so that basically means we have finished our first partition and we want to take the size and add it to the output good thing we're keeping track of the size the first partition is of size nine so we'll add it to the output and then after that we're going to reset the size back to zero because starting from here we're going to be looking at a new partition so our size is going to be reset back to zero our end pointer can stay the same because we know as soon as we see the next character our end pointer is going to be updated anyway because we know that this is going to be a new character that we see it's a d character where is the last index of d well it's over here which is 14. so that means we're gonna update our end pointer because 14 is of course greater than eight so end is now going to be 14 of course we are going to increment our size uh now to 1. okay next character is e whereas the last occurrence of e it's over here which is 15 so 15 is greater than our current end so again let's update our end value and of course let's update our size now to be 2. next character is f last occurrence of f is actually at this position so 11 is less than 4 uh 15 so no changes here we see another e we've already seen e's before they're at index 15 which is what we have no big deal we see a g and g is the last occurrence of g is actually at this position as well which is 13 less than 15 so no updates at this point our size will actually be like five now i think uh next let's get to d this is the last occurrence of d we get to e this is the last occurrence of e and it's exactly our end value so this is the second end of the second partition and what's the size of this partition well it's seven which is what we're going to be keeping track of but i'm kind of skipping that so the second uh partition that we're gonna be adding to our output is gonna be of size seven so that's what we're gonna do next we're gonna go to the third partition so over here the first character is h uh by the way our size will have been reset to zero and last occurrence of h is over here which i think is 19. so that's what our end is going to be at currently we're going to get to the second character which is i it's a little bit smushed in here eyes last occurrence is over here actually at 22. so uh you know update the end to 22. next character third character is going to be j uh last occurrence of j is actually at the end of the string which is 23 so at this point we pretty much know that this is going to be a partition itself right but let's assume we continue to run through the algorithm we basically visit all these characters we don't really update our end because it's already at the last index of the entire string and the size of this partition is what it's something like eight characters so by the end of it our size will be at eight and then we're going to go ahead and add that to our output so you can see we did the algorithm we got the same output as they got in the example up above and we kind of had to do two passes one pass to build our hash map and then one pass to actually build the output but still we all we had to do is scan through the input so the time complexity actually is just big o of n the memory complexity is big o of one because this hash map is going to be limited to 26 characters so with that being said i hope this makes sense now we can jump into the code remember the first thing we want to do is do a little bit of pre-processing by is do a little bit of pre-processing by is do a little bit of pre-processing by that i mean building our hash map where we are going to be going ahead and mapping every character to the last index of it in the input string s so let's go ahead and iterate through our string in python we can save like one line of code by enumerating the string which is basically going to allow us to get to iterate through the index and the character at the same time so i is the index c is the character uh we're gonna go ahead and take that character and set its last index equal to i now this is okay because even if the last uh occurrence of that character isn't this index eventually we will have visited the last occurrence of that character in the string and then we'll have updated the last index of that character to the last occurrence so this is pretty simple now getting into the actual algorithm we are going to be doing the same thing we're going to be enumerating through the index and the character of every single uh character in the string but remember we're going to be maintaining a couple things one is going to be the result of course which is going to tell us the size of each partition and if we want to you know add the size we have to maintain the size and we're also going to be maintaining the end of each partition so initially these can just be set to zero now as we go through every character as soon as we see a character we want to go ahead and increment the size of the partition we also potentially want to update the end of the partition if uh the last index of this character is greater than the current end then we can go ahead and update the current end to uh that last index you can write it out like an if statement like this but to save a line of code we can actually just use the max function which is built into python and most languages we can update end to be the max of itself and the last index of the current character that we are visiting so we can get rid of these two and just have this one line of code remember we know we can stop a partition if we actually reach the end of the partition so if i equals the end of the partition then we're done we're going to go ahead and add the size to the result and then we can go ahead and reset the size back down to zero and that's all we really need to do as we finish our partition we don't really have to reset the end because it's not really necessary in this case once this is done our result will have been built so we can go ahead and return it and then run this to make sure that the code works and as you can see on the left yes it works and it's about as efficient as we can get this problem to be so i really hope that this was helpful if it was please like and subscribe it 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
|
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
|
398 |
hi everyone welcome back for another video we are going to do analytical question the question is random pick index given an integer away nonce with possible duplicates randomly output the index of a given target number you can assume that the given target number must exist in the array implement the solution class solution in nonce initializes the object with the array nonce in peak in target picks random index i from nonce where nance i is equal to a target if there are multiple valid eyes then each index should have an equal probability of returning let's work fuller code we can use hash map to solve the question for each element in the away nonce if the element is not in a hash map we create a corresponding pair with the element as the key and at least as the value if there are duplicate elements we then add the element to the list if the element is already in a hash map we can just add the element to the list we can use the random function to pick a random index from the hashmap where the index is equal to the target thanks for watching if this video is helpful please like and subscribe to the channel thank you very much for your support
|
Random Pick Index
|
random-pick-index
|
Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array.
Implement the `Solution` class:
* `Solution(int[] nums)` Initializes the object with the array `nums`.
* `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning.
**Example 1:**
**Input**
\[ "Solution ", "pick ", "pick ", "pick "\]
\[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\]
**Output**
\[null, 4, 0, 2\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3, 3, 3\]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-231 <= nums[i] <= 231 - 1`
* `target` is an integer from `nums`.
* At most `104` calls will be made to `pick`.
| null |
Hash Table,Math,Reservoir Sampling,Randomized
|
Medium
|
382,894,912
|
63 |
so on today's episode of code with senpai we'll be solving the unique pads problem asked by these companies so the problem states if we're given a grid and we can only go right or down how many unique paths are there to get from the start to the end so how would you solve this on paper well if we're given a grid of two rows and three columns from this cell we can get to the end by going right down right or down right three paths from here we can go right down or down right that's two from here we can only go down and from here we can only go right so a pattern that you might notice here is that we were able to sort of pre fill this last row and the last column with the with one because we can only go that one direction from there and then for the other cells we can get that answer by taking these some of the cells from the bottom and the right so 1 plus 1 is 2 and 1 plus 2 is 3 so the fact that we were able to compute this overall solution by solving the smaller subproblems that lead up to it lends to a dynamic programming solution where each cell is going to represent the number of unique paths from that cell to the end so we can represent this disk recurrence relation as the current cell is going to be equal to B cell from the bottom just a cell to the right and it also helps that you know this problem it uses a grid and I think you're trying to find this sub maximum which should also point you to a dynamic programming solution so we were given a bigger grid how we fill this out so a 3 by 3 grid and it should be pretty mechanical right so you know we can pre-fill these with so you know we can pre-fill these with so you know we can pre-fill these with ones from here go one cousin 1 is to 1 plus 2 is 3 2 plus 1 is 3 and 3 plus 3 is 6 where 6 is the final answer in a 3x3 grid so when we're actually coding this like it helps to add some padding to the M like this and then we can change this a little bit to a plus sign here and then we can zero these out and use this following equation to pick the whole grid so if we're going to start here and then a 1 plus 0 is 1 and 0 plus 1 is 1 plus 0 is 1 plus 1 is 2 1 plus 2 is 3 1 plus 0 is 1 2 plus 1 is 3 and 3 plus 3 is 6 so like you'll see that I liked it I like to iterate backwards here like a lot of people like to do this problem going from the start to the end but I think I doing it in reverse helps with the follow up by making the code a lot cleaner so yeah but it doesn't really matter as long as you get like do main intuition of the problem so the running time and space complexity of the solution is going to be equal to the Big O of the number of rows Anjan times the number of columns because we got a like iterate through the whole grid and store the results as we go all right so let's see some code so we take our first example they look great with 2 rows and 3 columns we're going to initialize our DP table and I'm going to import a numpy here so we can visualize this little year like that so like I said we're going to add some padding now and two handles the on the out of balance cases and we're going to pre-fill our first a and we're going to pre-fill our first a and we're going to pre-fill our first a result well we know the answer is going to be at least one from there it's very backwards where the answer to the current cell is going to be the sum of the cells from the bottom plus to write the final result our answer is in the per cell 3 yep that's what we expect so here get rid of our logs make sure that we return the answer and then it's like that there it is so the fall question asks what if there are some obstacles added to the grid so that's saying like if we took the P grid that we had before and we place the rock right here in the middle so what would change here well it would sort of block out or a zero out the paths that go through that cell right so if we were to recompute these and we were to count the obstacle that's a zero if we go 0 plus 1 is 1 plus 0 is 1 and I 1 plus 1 is 2 because look as you can see from this cell that gets the end if there is an obstacle in the center now we can only go right down or down right which is 2 all right so let's see some code well if we take exactly what we had before the difference now is that we don't know none of the rows and columns right but we can figure those out by looking at the dimensions of the outfield grid so right now the main difference is that well if there is an obstacle at that spot then we're not going to compute it right we're just going to take the zero because we can't go through it so this problem an obstacle in the obstacle grid is marked by a 1 ok so we're only gonna do our math if there is no obstacle there all right so look at that cell there's no obstacle then we can sum it up so just like that and I just make sure that we here we're looking at the same row and column here and that's it you can check out the code in the description below with more details about this problem if you found this video helpful please like subscribe comment and share with your friends and feel free to donate if there's any other problem that you'd like me to go over please let me know and thanks for watching
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot 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.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
146 |
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you did in this farm I'm gonna stop alive right about now cool 1:46 LRU cache design and design cool 1:46 LRU cache design and design cool 1:46 LRU cache design and implement a data structure for these recently used cash it should support the following operations get input get gets to value of the keys if it exists in the cache otherwise return negative one put sets or insert the value of the key is not already in the cache when the cache which is its capacity you should about eight to two least recently used item before inserting a new item the cache is in this initialized through a positive capacity oh it's capacity okay I don't know why they put a boat on a positive and not on the capacity but typing a keyword can you do both operations and no one okay cool so yeah so this is a relatively standard problem yeah I've gone in a few times actually so I'll do it for you but up the ideas used like a linked list type thing which I'm gonna do let's set up an old class yeah I guess I know just it needs to contain two Ryu right and then also set up the Nexus none and that's pretty much all I need hmm negative a little bit better I could do also this previous just for just so that we can be move stuff a little easier to write but yeah then I would add capacity I guess I have to capacity we where did you work stuff so otherwise we put in the hash tables I just put in how much and when we do it okay they don't actually tell you this don't do that okay the problem I mean they say I was just talking it up like the condition of what's considered used in this LRU hell are you case because some variation is like you it's considered used if you to a get and up or put rather and some other cases they only consider it as used of you if you only put a port or something like that so some variation that's why I'm looking it up but I guess we'll just do that yeah I wanna get we want to eventually return the hash of the key or negative one so would that's just too harsh but before that well if key is in hash or sub that hash then we want to move it to the one or the back first oh yeah so I mean I guess it doesn't matter because we're using a double pointer but you use we put it in yeah I guess we need both ends so do I just need to write a like this function to me like an English class but I'm yeah he is in hashed and we also want a anode hash no look up maybe that's a pretty name yeah don't know is because I've done known lookup of in this case where we assume data subhash and so done look up it's gonna be the same doing I guess we could have done it like I don't know you could put in the same thing in a you know in an entry type thing I let's do that's why boku why not okay now that is a little confusing because to ride you itself doesn't make sense okay cool and now we want to move it to the foot I always forget if there's a link dis class in pythons like there is in like Java maybe I should turn in Java yeah okay maybe not yeah there was a Dunkin donut how are you doing okay well let's just say beginning of fun no I guess I'm fury I should okay fine I just make a little note I linked to this class I think there's also like a cleaner way to surf Sarah knows but I don't I need to get better about that okay and you need really need two functions which is app and I guess so it's not that fun it's none then stuff done - that fun it's none then stuff done - that fun it's none then stuff done - together no stuff done and it's you're gonna - no and then just return gonna - no and then just return gonna - no and then just return otherwise then self dot and dot next is here - no dot previous is you're here - no dot previous is you're here - no dot previous is you're gonna salt on hand and so I've got an easier to know and then you have the other one which is I was at moved to end say and then in this case this assumes that it is already in there truly maybe I guess I could maybe I could just okay but uh okay they've stopped that phone is none then again we're just through the spring dogs I guess it should already be in the tree so or in the link this so maybe this doesn't come up trimmed event I was in 924 uh I made my way oh yeah I mean I'm not done with this yet sorry working progress I'm just waiting the link I jumped a little bit uh back to my legless how are you doing a friend died ooh have you interviewed tomorrow good luck Dunkin donut let me know if y'all can help yeah you know well-framed I was can help yeah you know well-framed I was can help yeah you know well-framed I was just that I wanted to finish this and then I'll fill this out afterwards sometimes I jump around my head so I was a little too far but yeah if no it's not that fund and so how do we do this if well that's the latest no so no dot no doubt previous is not none Dan hold on I guess oh wait what I want to do this is he gonna done and then don't that proof is really done and then if no time next it's not done next up we you're gonna know and I know time next is already done and now it is deleted and then now we can just a pen yeah a little odd maybe but cuz that would make waiting just really easy just trying to think for a second just to see you with disses right maybe should be okay we will test it okay back to hear if tears in Ashton oh yeah you welke is not in Hoschton just return the exam wand and just kind of mixed in daddy's ear maybe that's what you're talking about and then because I kind of have this here but Brazil baby you are way and so then linked list moved to and no I guess that's it really all right that doesn't make sense me I also need to know because I want to remove from the front okay like add a kick so for all of one movements okay and then now put okay how do I pour well if T is in to hash then V I actually want it well we can just update the hash and then also just move it to the end and that's pretty much it I think otherwise then this is a new element so we want to solve darling this kind of pen and you know just a while you I suppose no actually just a key if Y you is the key yeah okay I think I want to put this here instead the capacity so that I don't so that the cash don't worry about yeah maybe that's okay and then in this case hmm that means have to keep track okay well this won't do something like this but then just mix this a little bit weird I guess I could just do something like this which is technically true because I removed it and then now if I stop that current you know is queried and stopped at capacity or and we want to just do some tough one is negative self that fun done next and then now stop that fun that free is bigger than none it's not that new one is none and this will maybe even throw a wild at this in case shouldn't happen but ok just put return I guess it just doesn't return anything ok none okay oh but then I have to give acting mmm that is 2 because I removed it from here you know okay maybe I messed up on the capacity actually on the actual coding because maybe this should not kind of legless or at least well I guess I could beat up just a little bit of a hack but we can return you're going to I'm not a fan of this design and you want to spend time right now if I rewrite at some point of this but for now I'm just trying to get it working and technically is TDD given that we have some sample cases so that's a good place to start that's my story I'm sticking to it so we do this and then for each directed we want to remove it from both cuz we got the key okay and also didn't knock on door lock up let's give it a try yeah not a fan of it okay done it's not because No - hmm oh I never actually put the stuff - hmm oh I never actually put the stuff - hmm oh I never actually put the stuff in here Jenny mmm touching you but the same wonder but I just never put anything in the hash table okay no and I also never put anything in there idea okay I need to actually little sloppy on my end guys with that well it's close so I don't you write something correctly I think mocha you waxed - therefore - it's gone I'm just waxed - therefore - it's gone I'm just waxed - therefore - it's gone I'm just thinking about how I want to go about debugging let's print out what we get directed I suppose and it doesn't affect anything at all hmm how just doesn't set it up correctly and there's some duplication of codes so let's just put this up here okay still the wrong answer of it hopefully less well okay you Rex the wrong number moving one to the end like that's actually what I expect so why is it be moving one from the front to the first a pen and then the second of pen just be twins an empty away because the first ones here and then here it returns the correct answer I think one and then it tries to move one to the end even in something to drink oh no I mean it just removes motion just moves to one Terry and this should direct it to but it doesn't and you mix to one instead okay I mean so these we know why that or how that is there's something here well this is incomplete because we don't deal with the fun in the back hey what's up top so how you doing or do you so learning movie food to toe and constantly go yeah I mean I would say so this would be in here and you have to sort it by difficulty a little bit they're covered less on that but the easier palms are definitely easy enough for you to you know get your fingers warmed up or get it right or whatever the analogy is not good at it that part clearly yeah okay I see why because this removes - no but not from the front the removes - no but not from the front the removes - no but not from the front the fun is still this note because I don't update the pointers okay what I thought about this though but I forgot before and stuff doc boy we don't matter fun no I just take over here so - one done Knicks here so - one done Knicks here so - one done Knicks no what is he going to start on and dance so any self-touching top dance so any self-touching top dance so any self-touching top previous I guess and now some tough when the previous is none and now the news of that and that Nexus none okay yeah that's the thing that I need to try okay thank you yeah that's the finger that's the parent I need to learn like I am wax you are right I was actually talking about a little bit early on the stream but I'm I mean I just never did it that way to be honest but there's something that maybe I could be a little bit better about it's not none of course but you know because there's a lot of just checking to see if they're nuns okay oh that means there's something weird cuz the reason why I don't have a check it's because that if the fun or the end is none then this fun is also none but clearly something's a little bit of whack in the way that I've been doing it well yeah I just never learned that way but I yeah maybe it's worth doing it one day for sure yeah ux9 yobics still you Beckster one so that's not quick then we said something still messed up with here hmm oh yeah this isn't really not supposed to be a hard problem but sometimes there's not much yeah I'm almost done I just never figure what why and why is this you betting on what cuz phone is still one is none but that's wrong too oh I see because I do this stuff first that if this is self dot fun it's pointing to this known then just the stuff would already be none before okay but yeah that is copy and paste and week I mostly got this right it's just that I have time whenever no and then there's another one because try some other edge case the solution busy just copies ordered dictionary ah I guess so I mean but that's like they're the log and or whatever one wait so given this one you put in a bunch of stuff four three two what is the capacity you get two one it's not there you put in the five get the one again why is that negative wonder I know these are gets so that's still negative one for one but two how touching yeah that's that very well it was up don't drink auntie wife how you doing with my thing yeah so we move for me with to even with to the end so now it should be four three two one does make sense put five so four three two there should be two three five wait are you back that's what I'm into yeah there's still something a little bit off-course when you move to the n bit off-course when you move to the n bit off-course when you move to the n obviously the next direction shouldn't be too this one's fighter Elise better than nothing I just I need a princess I was gonna invite something like that but then I just was hoping I would need it oh I'll actually call it so that's not helpful hey what's up me how - how you doing huh hey what's up me how - how you doing huh hey what's up me how - how you doing huh once again I breeze through the heart of arms in and kind of maybe a little bit too cocky and I struggle a little bit of these ones yeah moving to the end and why doesn't the print do anything I think it's just I mean it's obvious that some part of these isn't know would we since that some well I think this may get changed if they're pointing at this now that's hot that should be all okay well there is something like for you this hey have a good night on nitrogen ion 2 & 2 good night on nitrogen ion 2 & 2 good night on nitrogen ion 2 & 2 thanks for the follow - I'm just working thanks for the follow - I'm just working thanks for the follow - I'm just working on some lead code a way basic for me I was LRU BAM apparently I am having trouble of linked lists in January you know I feel like I'm I have a good class but uh maybe not today moving forward to the N why is this holding this stuff really weird I just quaintest course house crochet yeah 1 2 3 4 moving for to the end oh and then the prints we just feel but now that's printed after the boof yeah criteria 1 2 3 4 3 and so it's still true moving to it to the end and then now just to cuz it is because that costed 3 well none of this is true three is in the middle and I know that previous is the answer so - Dewey - oh this is why do they do so - Dewey - oh this is why do they do so - Dewey - oh this is why do they do this like this now when everyone is next Morgan next we'll skip - no not just okay that's we'll skip - no not just okay that's we'll skip - no not just okay that's just a silly mistake and then now we can do something like no please cuz we want that to happen anyway all right well no we got it working again I will see let me remove two print statements real quick I could find it how'd I look spending on this one why is it still print stuff hoping Justin get matched on my search okay come on big money okay cool alright well I was gonna make some comment about oh linkless being able to visualize it i mean i'm most my issue is just that I don't have him doubly linked this well at least like it's been a while something definitely if you were me and I am me because that's how me being me works I need some more practice of like this and it's had a little bit of I don't know I just didn't ever wish I there's one of those things where like if you've done it like hundreds of times sometimes you just don't think about it but then you I don't know have a silliness pick up you know because you're a little bit bust yeah and that's kind of how I feel like I was doing because I just love silliness I would say definitely I also second one am practicing which is to look up so no pointers out by practice that next but I've seen someone using it before but I haven't done it myself cuz I don't know back in the day that's just not how people taught me but um I was taught but you know Thibault you always have to learn new things and incorporate new things into kind of how you do things and you know so I'll definitely think about it and it kind of be up on it roboy LRU cache yeah you just the basic idea is just using a linked list so that you could manage a linked list and a hash table in a way such that everything is these like a sort of one kind of and that's pretty much it because if using a linked list and if you could get to node you know one time and you could keep a sorted list you know of one time so yeah and maybe I should have used it human life yeah and maybe that's why I need to do for you sorta tick maybe I should have used or detective I mean I actually don't use already thick enough order dictionary but we have to beat up two puppies I just don't know that much about it oh yeah oh boy I mean I like thankfully but I was doing interviews I definite a bit better on the interviews but because I've definitely got this on interviews even if we don't have to implement everything I think we I did it on a whiteboard so that was a little bit ahead maybe but yeah still get familiar you cash just because it is definitely pawned I've seen nice
|
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
|
482 |
Do Hello Hi Friends Welcome Back Today We Are Going To Song Link Problem 2014 License Key For Writing This One Of The Google Interview Questions And You Can See This Year Before We Go Through Description And Details Of Want To Mention That My Channel Is Dedicated To Help People While Preparing For Coding Interview Services Aa Jaunga Telephonic Interview Sir It's Not Good Playlists And Examples With Different Format Your Problems Like Dynamic Programming Nikli Stedims Binary Search Priority Queue Optimization Problems And Manya Rate Types Of Women Big Companies Like Amazon Apple Facebook Google Microsoft And Others Soir Someone Who Is Preparing For Jawa Interview Chowk Wedding Interviews And Just Learning Jawa Which Is This Day 30 Channels And You Please subscribe The Channel So You Can Watch Funny Videos So Aam Let's Go After Description You Are You That Represented A Spring Gas Ko Which Consists Only Alpha Numeric Characters And Schedules Keys Separated Into Inch Plus One Group Buy In This A Given Number K Moods Want Two Three Formats Prince Net Group Contains Accepted K Rector Accepted For A Tufts Guru Which Good Shotgun K But Still Must Contain At Least One Character Par Dharma aur Adharm assured was insulted between two groups and all lower case latest should be converted to uppercase governor not empty string add number format screen according to the rules described about lifting as will not exceed 1200 teaser positive integer this content only alpha numeric Character in 2g and capital letters and 029 number and assist the hai honey sunti to aam s you can see hidden have given us to example so its pages examples and clear and you will discuss how they are going to solve this problem solve basically choice you can C dating s given to sndt syed faisal pani my characters only aj and their couple of days share residences 100 deaths and operates in the group of water singh suvvar suggestion i just come sodi wants to basically common group distic in super singer have to make this Cold Think Capital Is Right That You Can See These Cool Things Kept Alive And After That You Have To Take Gang Of Four Characters From The Backward Side Basically Night So As You Can See You Have To Take Gang Of Four Characters And After Guru Ko Four Characters K His Forehead With Vibrating Four Characters You Have To Insult To Date And Time Again Create Another Group Favorite Of Or Characters Or Placid End All Characters Effective Force Group Right Sorry For Example In Recent Example If You Look At This Example Any School Capital Of This String Like This Rate And You Need To Take Two Characters US visit * Characters US visit * Characters US visit * Character Group Day Again Insulting Das Aggie * Character Group Again Insulting Aggie * Character Group Again Insulting Aggie * Character Group Again Insulting Descent Ki Kundli One Character Is Left Back There Was Watching Sachin's 100th Test 100 Basically Group Can Share This Content One Character is that is the criteria Bahuguna So this is the problem and where trying to solve School Sector 21 Tak Hi Sona Now What they are going to do to solve this problem will remove all Subscribe now to receive new updates reviews and chapter-wise chapter-wise chapter-wise 325 Shyam Ki Sui Not Love You To Hai Ki Mein 900 This Is The Spelling Of But Come After Removing All The 600 And They Also Capital Of Determining Speed What Will Start From The End You Speed What Will Start From The End You Speed What Will Start From The End You Will Go Character Director From The End When They Meet Everyone E F And Characters Means Everyone's Directors Are the Best Insults Taste Their Life Will Grow Hair Oil Inserted A Senior Knows When Will Find AIDS for Guru E Can't Insult Updates Year Because You're Left with No Characters Bride and a Glass Hui Needs One Character in Its Roots Witch Can Not Interested And Share Like This Is Not Correct To Avoid Soft Basically What You Will Be Doing In These Nine Programs Is Wherever You Reach It This Time You Know Greater Than Life Is Getting Less 20 2012 0 9 In Saturday At Pankaj Subir That Contrary Direction Character Liability Both Points Up Insulting And Share The First Character Develop Don't Miss Random Group On The Left Side Effect Is The First Character 100 Deposit They Are Going To Solve This Problem Solve Your All Such Thing Will Do You Will First Convert String Into Capital After Things Which Welcomes Twenty 500 That Encounter That Pimple Beauty Android App Per Date Is Given To Us Please Give Any Process To So E Will Give Every To Character Sur Food As Every True Character Will Put To Death Share Like And Now If You Go Air Late Se Gurjar going out of the best they are doing less 2003 1280 yer do subscribe and will just you screen builder for these rates winters hujur dynamic link doing so will you stringbuilder class for this so let's go through the implementation of the in such things as you Can See Taste Second Such Thing You Can See Is We Are Going To Remove Dussehra And Spring His Noise And Tourism And Their Feelings After Works Clear Life After Death Caused Defined Spring Builders Result And What Happened During This Into The Ring Builder Should You Have Adapted To screen mirror know what they are going to your initial price of equal to total length of the screen - equal to total length of the screen - equal to total length of the screen - character total length of the street screen for example back length 8 - k basic for example back length 8 - k basic for example back length 8 - k basic element and k is for shopping - of course for element and k is for shopping - of course for element and k is for shopping - of course for basically a tight slap to Doing And Oil Is Greater Than 042 Is Will Insult Character Dash * If This Position Retired Is Character Dash * If This Position Retired Is Character Dash * If This Position Retired Is The Position Where Ru Is Insulting Saunf And Is This Position Left And Creative Is The Position Where Raghu * Canceled In To The Position Where Raghu * Canceled In To The Position Where Raghu * Canceled In To The Stringbuilder Maze On Radhe Shyam 1623 Length Fourth position minutes after To insult dance in this is greater than 1000 in this case is chief 0is don't have to insert anything you have done basically with spring rate disavar answer soft will also worked with another example from which converter software calculate the length of the British 1234 five the in The Beginning After Removing Like Share and Subscribe To Be Beatu From Idioms And So Will Go To Third Position Will In Saddest Thought For Example This Is The Spirit Soul Into Five Yes MP3 Pendujatt mp3 End And Share Hui This Is A Road In This To Second lane de only and also will go to third position now third position will inside basically which means that this and after se per third position comes with insult reference g and will reduce bittu so that welcomes one again will go to one position to is this Position Solar Eclipse Insult Key Updates Right And Again Will Decrement Bittu Uchcha Victims Minus One Drops Of Scorpio Clear This Point To You Dance Will Return This Is The Answer Rate For That Is What You Are Doing Gear System That Is Created For Doing So Will Just Rang This program on the inputs and have given ascend met solidworks now 276 posts and this is the difference between the first one letter this test that they can ctc ka form 2018 result name full modify this such a fool want every to character group Minutes each of that looks like it and tell us that you can see every two characters as a group Price 2012 Characters are grouped and separated by Roadshow It's working correct We can take this another second example also on that it is easy equal to so lets from this Myself Can See You Were Getting Away In Correct Result Declare Date Is The Result Should Submit Our Solution Is The Power Solution To Tax 2019 67 Per Cent First Another Solution Suzy Slice 100 This Is The Way Can Solve License Key Formatting Problem By Using Arduino Stringbuilder Addition of the Best Google Interview Questions on Maturity Understand and Practice But When You Are Practicing Interview Questions Try Note User ID and In Order to Complete Java Code Word Because in the White Building Date Will Help You Also Give You Have Told You Can Through My Play List For List Solution Please Find Quality Of Problems Which Are Specific Company Safai Ke Amazon App Facebook Google Microsoft And Other Companies Of Well Its Contents For Write Your Problems Dynamic Programming Priority Queue Hd Link List Related Problems Related Interview Questions Of Jewel Zoological Park Others Binary Search Related Questions Solve Gotriya Preparing For Coding Interview Definitely Painful Tube Other Is Agar Playlist Ko Doubts Aa Jaunga Interview With A Playlist Is Raavan Staff Videos For Frequent Class Ja Va Questions And How To Answer Dev Also Consider Question Send That Kal Jaunga Questions Data Frequently Asked In Java Interview Software Supaul District If You Like This Video If You Find This Helpful Please Like Share And Subscribe Mitti subscribe to the Channel Show The Video Can Reach To More People Like You Are Preparing For Coding In Java Interview State Can Also Watch This Video And a candidate can also help determine their preparation for Please subscribe this Channel and thanks for watching the video
|
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 |
823 |
Arvind Just Coding And Kuldevi Application Form Nakul Binary System Software Governor Of United Spirits In Teachers That Greater Than One And Share And Trying To Make Everything In Teachers Fuel Mode Value Difficult To The Product Of The Value Of Children Were Beaten Up By Cancer In 1971 Bittu Love You To The Answer Mode On For Ninth Class Seventh Slide A Particular Example Soft Laddu Hum A Simple Jewelery Exhibition For Numbers From One Example Number To 9 Children Channel Subscribe My Channel Angry With Me Always Swelling Us Mudde Simple Boundary With Only Your Business Must Foods And More Children So What We Do Is Vinod Minimum We Can Make One Mindtree Em With All The Valley What Will U Will Declare Map Structure And Waste Oven Initially To All Of 30 Numbers Their Career Point On This Number Switch On The Number One Rank One Minority Under Swiss Rolls Numbers Don't Feel Proud To See Which Can Make Any Other End Vs Using This Numbers Of Worship Will Start The Advantage Of Voting Festival Of Numbers In Order And So You See Using A Small S Number You Can't For Any Rate Increase No Matter What The Number You Ring Smallest Numbers That They Smallest Coordination More Than Number Selective Verses Thru This Very Old See You Can Never Form Hundred Using Numbers Women In Are You Can Ever For Introducing More Than 200 Phone Numbers Unit To Numbers To Homeless Particular Number 90 Winger Numbers Because City From Hundreds And Hundreds Of Spoilers Numbers Using A Small December You Can't For Any Country So What Looks From The Second Number Determines Key Value Will Start Hydrating And Check Again From Any Other NDTV Ko Sundar For The Smallest American Not Form In Yadav And A Side Stems From Equal To And Will Go On Till Soils Of Michael To Vandana E Cold Do It Cold Be Called For Equal To Five To Three Four 500ml Tried To Find His Youth In All The Number Seven Phase Page Using Three Layer Rashidi Rumor Can Form A Mother Values In Children Rashidi Rumor Can Form A Mother Values In Children Rashidi Rumor Can Form A Mother Values In Children Need A Very Simple And Children Turn On The Valve Of The Faucet Plants Dongri So Will See Window 10 Water Will Change Its Values Will Say Everything From Will Change Its Values Will Say Everything From Will Change Its Values Will Say Everything From Jaipur To Zero Tillage Right Swirl See The Number Smaller Particular Number Date Will Help To Five Using Any Number Beginners Particular Number You Can't For Binary Numbers Can't Only From Two To Two The Possibility That You Can Form Number Three To 99 Free Are You Can Not From Near By Indian Village Women Has One Superintendent Of Police Clean Image In Name Growth Oil Examples Will Be Able To Understand Better Listen Will Take Equal To And Give Light From Jacking To Viruddh Equal To One Because Sequel Don-2 Because Sequel Don-2 Because Sequel Don-2 Jewelers Un I Will Not Be satisfied of world equal to cox and he is equal to two so go total 209 equal to show the celebration 8 days ago520 views check number tide is 420 and 120 possibility for every thing is equal to a completely true to find the number to divide four Completely What Will You Check Divided Into To This State Problem You Are Not Indicated As President For But You Stood At Midnight Bluetooth You Can Find You Can Get 454 Extra We Strive For Every Day With Children Live With Children To Phone Number So Now Or two ways of forming mandatory for a nod to Buddha were listed neither will go to back side reaction on which will make you will find number four wheel chair for more than 500 and 1000's not just go to Two Difficulty Sumedh Vijendra Final Number 222 Multiply With Its Two And Give A Six Her Nature Defined Vs Divided Equally Second Device Equal To You Get 39 Veer Chakra This Present Name App And Not Quite Serious And Producers No Weather This Present Name Of Which This Present Number What We Do It Is The Number Of Domino's Pizza Bread Is Dynasty Gift Veer They Are Not Able To Get New Song I And Late Se 351 New Name And Forward to latest or select measure all this I Suraj can go to the next hydration tell next to two to do the thing which gives equal to zero number three to give so let's see what is the number subscribe to subscribe our two three one two three One two and tell redmi race all this and let me to back side reaction snacks hydration this vijay goyal two so let's milk porn sacrifice mode and this equal to zero 100 vinod let's mode off and this equal To Zero Officer Maze Pay Not Multi-platform With Any Number To Form 6 Witch Multi-platform With Any Number To Form 6 Witch Multi-platform With Any Number To Form 6 Witch Acid Jasol Will Just Hair Oil Hydration Suno Web Site Rating For The Valley Sixty Five The Con Is Equal To Do Extra They Just Means 16 Two Years Old When Will They Get Well Soon With 323 341 323 324 Number Two Tomorrow Morning Na Aaye Aisi Ko Into Foreign Jack 120 This Introduction That 60 Mode Two Shrink Equal To Zero Not Acidity Total Hundred Units Push Notification Number 16 Number To and give a divided into to you find number of different way of getting to number to this number subscribe to the Page if you liked The Video then subscribe to the and listen My Account Has Welcome Equal To 100 West Survey of Granting 2028 Writing for Foreign Tourists 252 New Ways Of Writing 800 Let's Go To The Next Hydration Solid Let's Go To The Extra Hai 209 Views Check Ujjwal To Zero No Veer Gurjar One To One Which Is Equal To Foreign Jack 12108 Mode Shree Does Not Equal To Zero And 100 Rates On Future Technicals Unknown Number Candy Multiply with 30 Number Panel Different Gemini 258 OK Let's Go to the Next Values Yagya Hai Vijay Ko * 2ND Next Values Yagya Hai Vijay Ko * 2ND Next Values Yagya Hai Vijay Ko * 2ND Year Michael Two for So Let's Check Peeth Mode Off and Is Equal to Zero This is Right So I Know You Can Find Number Even Tried To Find The Number 67 And Web Fonts For Sweet And Tried To Find Number Animal With 4084 * Tried To Find Number Animal With 4084 * Tried To Find Number Animal With 4084 * It Is Divided By 0.2 Users By 410 To You It Is Divided By 0.2 Users By 410 To You It Is Divided By 0.2 Users By 410 To You Check Tools President Namaz Se Purva Is President Name Of Adding One Way Similarly For Its President And Foreign Tourists Ko You Can Form For Youth Into Which You Can Form 2012 Swift New Ways Of Learning Digit Solid Account 12182 Complete Account Election Me Account Vikram Singh Guddu For OK And Why My First Us Emphasize This Student Medicine More Space Hua Hai How To Writing Reading Speaking A Little Bit Extra Time But To My Home Can Deal With This Let's Go To Back Side Reaction JB 23-01-2014 So Let's Divided Mode JB 23-01-2014 So Let's Divided Mode JB 23-01-2014 So Let's Divided Mode Equal To Zero NDMC Fat Monthly 120 Is Points Listen Number That Multiply Which Seeks To Give 60 Swift Possible In This Particular Case Verdict Which Can This Go To Back Side Reaction Next Time Job Opportunities For Equality Again Zip Swift For Newbies Guide Return Gift For New Is Special And Complete Already Present Value Of Its One Place For Physical 2525 Bay Similarly No Dues Previous Govardhan A Very Simple To Love Every Boy Just 120 Days Marriage Equal To File And The Values 12520 Dual Check Difficult You Will Get 125 Sorry It Called For Mujhe Shirdi Man Sai Nadi Deutsche Well Mode Chalu Is Equal To Two To The Number 2 And Which Will Give The Number 66 Subscribe Now To You Multiply 123 Like This Particular Question OK Thank You For This Website Will Go To J2 S Will Quit Motors Equal To The Self To Solve We Can Find The Number Multiply With Three And Gifts 1231 Examples And This Also Needs And Its President Number Three And Forest Wealth For President Android 2.2 From One To Three One Two 2.2 From One To Three One Two 2.2 From One To Three One Two Subscribe My Channel Thank You Can Any One How To * * * * * * Fixed Now You Can Go How To * * * * * * Fixed Now You Can Go How To * * * * * * Fixed Now You Can Go To Back Side Reaction Sonakshi Tension Van Jaarsveld 300 Subject For Six 212 Mode Equal To Zero Two Digit Proved Again With Riders Paste Form 6 Which Can Point During Shyam During It's Okay Thank You can be used in this is just a replay with me too does not equal to 300 width I already subscribed 98100 flight mode shampoo se vestige tax sunavai 800 i10 person tool for your fun loving waves of making every thing you do to the Final Answer is only OnePlus Two Subscribe Width Divide Power Plus Khud Veer Will Vote for You Int and It Will Take Long Enough Baroda Value Scan Very Large Too in Tears for the Values in the Recent Edition for the Values in the Recent Edition for the Values in the Recent Edition to be Defined But a Log In This Value Sub Number One Grade To Make A Wish To Indra Se Dhun Let Me Quality M Okay Monday Now He Go Forward And Is Water Resources For Pimples And Gift Are Not Being And Tours And Travels And Tours Video Start It Provides That Point is absolutely 208 sexual size i plus form 2013 quote 20 celebs this number 56 one day before doing this for you all the best least one son for what the can do this forum to int this issue unlike media tree superhit equal to Zero Edison Are Dot Size Will Do You Know What is the Condition of That I Mode Are Off J is This is Professor David Completed 100 Sets Can Find the Value of What We Do That Person Election Check-in Check-in Check-in Are Cashless Mediclaim and And To It's Equal to M.Com Are of I by Paresh thing Equal to M.Com Are of I by Paresh thing Equal to M.Com Are of I by Paresh thing self doing it's okay Sapoch is equal to 6 and is found James is equal to two heard you check 16 divided by two wickets in okay which is three choice awards presented neither map nor because it is not presented daily how to reduce Less You Cannot Multiply Up With The Number To Get 60 Deposit With Three To Get 63 Still Present Name Of Villagers Came Mode Switch OK Notice It Is Not Difficult To Understand It's Present In The Map Tonic Receive The Elephant And Values For Boys Will Have To And Values For Boys Will Have To And Values For Boys Will Have To Increment Mic Account 100MB Left To Declare Account Pimple Understanding Juice Add Year Account Equal To One Vikas Nigam Everything Pimples And Romes Radio Chal Ok So Let's Make It Is The Number Of Extra Ways Of Finding It Difficult 2030 Left Side Improve Digestion When Finally Extra Ways to Make It More Difficult to Find the Value of the Number of Units Multiply One by One Number Five Villages It's Only Values as It's Second End What Only Values as It's Second End What Only Values as It's Second End What is the Value Itself Value How to Tell Why Do You Not To declare another royal test salute the dollar term 8222 equal to and find they are of g so they decided to rate numbers which is multiply in the morning of old age example in this case which will be two brothers will be 300 number of wells and storing two for Example is one number of you for watching free is 15211 with one ok sir immediately point to my cited 2.2 sir immediately point to my cited 2.2 sir immediately point to my cited 2.2 and abroad decided that it will point to three to find the number of multiples of multiply it second with it studied second in themselves into account through placid on and of the I your show I'll let me declare auto it three years and 283 is equal to md5 is particular one courier tracking Icon 2182 are of I's the daily point vs love you'll like it then placid It's values for auto parts values for auto parts values for auto parts that in MS word all well equipped and finally give some sum plus and they will have to give this long will not suit their veneer system plus and developed to declare them all so long in committee equal to zero two A request for very last test cases for a specific intent to return is request from sampler you just have so I let me give like this and 284 is equal to and begin and video don't understand is difficult-2 m.no benefit understand is difficult-2 m.no benefit understand is difficult-2 m.no benefit you all The Way Listen Amaya Advisors Mix Them Equal To This Particular Person Then Second 100 Years And All The Number Office Adventures Freedman Some Molu Temple Making More Questions 123 45678910 Ayush Work Permit Check This Work On The Sweets Working Day Images For Maiden Speech Working For Blood Test Cases Selected Solution Write Significance in the Vicinity
|
Binary Trees With Factors
|
split-array-with-same-average
|
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return _the number of binary trees we can make_. The answer may be too large so return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[2,4\]
**Output:** 3
**Explanation:** We can make these trees: `[2], [4], [4, 2, 2]`
**Example 2:**
**Input:** arr = \[2,4,5,10\]
**Output:** 7
**Explanation:** We can make these trees: `[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]`.
**Constraints:**
* `1 <= arr.length <= 1000`
* `2 <= arr[i] <= 109`
* All the values of `arr` are **unique**.
| null |
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
|
2162
|
907 |
hey my name is casey and i'm going to walk you through how to do leak code 907 sum of sub-array minimums sum of sub-array minimums sum of sub-array minimums so let's look at the input that they give us they gave us an array of 3124 and all they're doing here is they're breaking it up into all the sub-arrays breaking it up into all the sub-arrays breaking it up into all the sub-arrays that they can so it's first at first it's just the original sub-array then they take the original sub-array then they take the original sub-array then they take the all the sub-arrays of blank three all the sub-arrays of blank three all the sub-arrays of blank three then two then one okay and if we look at the minimum value sub-arrays let's look at the minimum sub-arrays let's look at the minimum sub-arrays let's look at the minimum value here is one another the minimum value here is one two so that's where these numbers are coming from one two and so they're just looking at all the minimum values in each of these sub-arrays in each of these sub-arrays in each of these sub-arrays and they're adding it all up at the end to get 17 which is how which is where they got their output from okay so let's look at this example here that i typed out so another way of thinking about this problem is how many subarrays is each value the minimum in those sub-arrays so for example let's in those sub-arrays so for example let's in those sub-arrays so for example let's say i ask you say let's say i ask you this number seven here how many sub-arrays how many sub-arrays how many sub-arrays is that number seven the minimum value in and the way you check is you first look for your previous lesser element so what kind what's the first thing i find that before me that is less than seven well that's this 4 here so we don't want to we do not want to include that 4 in our boundary because if we did uh 7 would no longer be the minimum value right 4 would be the minimum value so we mark our boundary here and then we do the same thing on the right what is our next lesser element well it's not 16 it's not 12 5 we is the first element that we encounter that is less than seven so we mark our boundary here now we don't even care about what's on the left or right we just care about this guy here in the center which what how many different subarrays can i make and this is one so this is one subarray right and this would be another sub array the 16 7 10 and we could just keep mixing and matching these brackets right and this is another subarray of with just one element of seven okay so how many different ways can we mix and match these positions these brackets on the left and the right well there's two spots that we could put the bracket on the left and right here's one spot right here this is one this is two so if there's two spots on the left and there's three let's see one two three there's three spots on the right that we can put the right bracket in that just means that seven is in six subarrays where seven is the minimum value okay cool and because seven is in six subarrays uh we want to count the number seven six times because remember we're doing we want to find the minimum value in each sub-array in each sub-array in each sub-array so if seven is in six sub-arrays where it is the in six sub-arrays where it is the in six sub-arrays where it is the minimum value we need to count it six times so that means we if we were summing this up we would do six times seven equals forty-two forty-two forty-two so uh so this six just came from the sub-arrays and the seven is the value sub-arrays and the seven is the value sub-arrays and the seven is the value here and we want to do this for every element so for example we want to do this for the 4 the 10 the 7 uh the 16 the 12 5 9 okay so let's just say we were gonna do the four the first previous lesser element of four well it doesn't have one so we just go to the beginning of the array and the next lesser element of four well if you look at the array there is nothing less than four so we just go all the way to the end of the array and this would be let's just do this one really quick so there's one position on the left how many positions are there on the right one two three four five six seven okay so there's seven spots on the right we can put our right boundary which means there's seven sub arrays that means we got to count the number four seven times and that'll give us 28 and we would end up at the end we would end up adding 28 plus 42 plus whatever value that we get from the 10 the 16 the 12 and all that okay so now that we know what we're looking for there is one corner case that i need to go over and then we can start coding this out uh okay so let's look at this little guy right here in this array what is the minimum value if we there it's clearly a one well remember earlier what i just said is that we need to calculate how many subarrays each value is in where it's the minimum value the problem with that though is that this one it's going to say hey i am the minimum value in this subarray of 151 and this one is also going to say the same thing it's going to say no i'm the minimum value in this subarray of 151. so they're both going to say that they're in that they're the minimum value and the what would end up happening is we'd end up over counting so what we want is we only want one of these ones to count as the minimum value we don't want both only one and the any other one so if we had multiple ones let's see let's say we had all these uh let's say we only want this guy or this guy to count as a minimum value but we do not want the other three to count as the minimum value and it doesn't matter which one we pick we just need one to count and all the rest not to count as the minimum value in that sub array so um let me i'm going to explain how to do that with something called a monotonic stack and monotonic stacks are perfect for um finding your previous lusters and your next lesser elements um or a monotonically increasing stack is how you find your precessors in your next lessers you would use in a monotonically decreasing stack to find your previous greater elements or your next greater elements but we're just going to do increasing for now and if you want to know more about monotonic stacks i'm going to go through an example of one really fast but if you want to know more i did a video on it like yesterday so you can go watch that and it's pretty detailed um so you should probably should go watch it if you want to understand this problem it's like a prereq but i'm going to go through it anyway okay so let's walk through an example of using a monotonically increasing stack to find our previous lessers and our next lesser elements so in a monotonically increasing stack all the elements are always increasing so we're gonna push this four and whatever is below me in the stack is my previous lesser element so there is nothing below this four therefore there is no precessor element which is why this boundary earlier that we put was to the beginning of the array now if we want to push this 10 we can go ahead and do that and now 4 because it's below the 10 is the precessor element of 10. now if we want to push this 7 we actually have to pop this 10 in order to push the 7 in order to keep our elements always increasing because if we let's say we had 10 and we pushed a 7 this is no longer a monotonically increasing stack because 7 is less than 10 we need our elements always increasing so we have to first pop the 10 then we can push 7. now four is the previous lesser of seven and if we kept doing this all the way to the end of the array where we just put we pop everything that breaks our property of being an increasing stack and then we just push we would end up finding all of our previous lessons and if we started from the end of the array because right now notice that we're looping from the beginning of the array to find our previous lessons well if we just started from the end of the array to push on the stat to start pushing on the stack then that would find our next lesser elements but there's a way that we could do this where we can loop through the from the beginning and find the previous lesser elements and the next greater or equal elements or vice versa we could find the previous lesser equal elements and just the strictly next lesser elements okay so let me go through that really fast so let's do it with the one five one because that'll make the that'll make it clear why this works so again it's a monotonically interesting stack so we're going to push this one and then we're going to push the five and that's fine and all this is saying is the precessor element of one is nothing there is no proof sensor cool appears also five is one sweet yeah if we look at the array the principle zero five is one then when we wanna push this one we're going to kick this five out so we have to pop it because that would break our property now what that is now what i'm saying here is that because i popped you so this one that i'm about to push onto the stack if i pop you out i am your next lesser element so i'm going to go ahead and do that let's pop this 5. so i'm 5's next lesser element because i popped it out now here's the thing we have these two ones here right and i have a decision to make here it doesn't really matter it actually doesn't matter which one i choose but here i can either kick out this one and if i pop this one i am saying that i am your next lesser or equal element okay because if i pop the five on i said i'm your necklace or equal and i also pop the one out because you're not uh less than me then i'm saying that i am your next lesser equal element in order for this one to be down here so i pop this guy and then i push this one onto here the other decision we could have done was saying well let's just leave it here let's we're not going to pop it out well in that case what i'm saying is that this one is my previous lesser or equal element okay but because this didn't get popped i'm saying that this number one here has no next lesser or equal element or sorry has no next lesser element um so if we look if we were to look at our boundaries here the boundaries for this one here would be assuming that i left if i just left leave the one in here so this would be my left boundary this would be my right boundary because again i'm saying because i didn't get popped by and if i got popped by nothing i have no next lesser element okay and the boundaries for this one right here i'm saying that this one is my previous lesser or equal so its boundary would actually be here and that is exactly what we want because we only wanted one of the ones to count towards this subarray and that would be this one that we did earlier a second ago so that is how we're going to loop through our monitor our monotonically increasing stack um or we just mark our we're just going to store our next greater or equal elements and we'll just store our pre or strictly previous lesser elements or we could do it the other way around but it does it doesn't matter as long as uh one of them has the equal element and one of them doesn't okay so let's actually code this out uh so we can just go ahead and create our stack let me actually clean the clean up all this empty space uh so we're going to have a stack of indexes in the array and we want to loop through our array because we want to push all of these elements onto our stack to find our previous lessers and stuff so r dot length plus i and now this is where we want to so before we push onto our stack we need to pop everything that breaks the increasing stack property so we're gonna do a while loop so while stack is not empty and stack dot peak so what i'm doing is i'm just checking whatever the top element is to compare it to what i'm about to push and i said i was going to store the index so stack of editors this is going to be the indexes not the actual values the indexes in the array so i'm going to peek at the index and i know this is okay because i checked if it was empty so uh i'm going to check what the value is here in the array and i'm going to check so because it's an increasing stack whatever is below me it cannot be greater than me greater or equal yeah so if it's greater or equal to me uh that would break our increasing stack property so if this element yeah so if this element is less than whatever i'm about to push it on to we need to kick this out so let's go ahead and do that stack about pop and we're not quite done here so remember what i said earlier is if we pop it out i am that element's next lesser element so this i or this value here because i'm popping this out i am the i am that index's next uh lesser value so actually oh i actually need to create some arrays to store these previous lesser index lesser values so let's do that really fast um inch previous lesser equals new and length and we're going to do our next lesser or equal just to be explicit so that's very clear what we're doing so this is going to hold all of our next lessons and our previous lessons and this is actually well next lesson or equals right okay so let's now remember what i said if i'm pop if this element right here is popping this guy that means that this i or this l this value is going to be this index's next lesser value so let's do that next lesser or equal equals i'm just drawing the index here okay uh is this good we need to so now we need to do our previous lesson so now that we've so we assume that this just popped everything that broke our property and now we need to check what is underneath me or what is about to be underneath me when i push myself onto the stack so what whatever is on top so stacked up we want to do stack.peak but stacked up we want to do stack.peak but stacked up we want to do stack.peak but in this case um there could be nothing underneath me right because yeah if we pop everything on the stack if there's nothing underneath me that means i have no previous ulcer element so we want to first check if the stack is empty if it's empty well then we have no previous lesser element and if it's not empty well then we just take whatever's on top or yeah and that is my previous lesson and then finally we want to push our index onto the stack because we're pushing everything and that's we're pushing every element into the stack and we're just going to do this and we just do this for every element so that took care of finding our previous lessers and our next lesson are equals and now all we need to do is calculate the left times the right and multiply that by the value of the array because that would be the minimum value and that many subarrays and we just sum that up so let's just create a sum variable and there's one little quark in this problem where the sum okay so this sum could get like super big and there could be stack overflow or whatever so they want us to mod our sum by this value so the way we do that we just do double mod equals one e nine plus seven if you haven't seen this before this is just one times ten raised to the ninth plus seven okay and i'll leave that there so uh let's sum up all those left and right boundaries or whatever so left for anti equals zero i is less than r dot length plus i and we need to create those left variables so let's just say and left and right and then we're going to say this is just i'm going to type out this in a second i'm just typing out some template code so sum plus equals the left times the right so this would be the number of sub-arrays right sub-arrays right sub-arrays right this is the number of sub-arrays and we this is the number of sub-arrays and we this is the number of sub-arrays and we need to multiply it by that value so this is the number of subarrays times how many sub-arrays um how many sub-arrays um how many sub-arrays um this minimum value is in or sorry this let me just say that one more time if this was our seven up here remember this was our seven and we said earlier that this seven was in two times three uh sub arrays this would be the two times three sub arrays okay so that's all that is right there um so we summed it up and then they want us to mod it because we could get really big so mod equals or so sorry some mod equals um mod which is just this guy up here and at the end we want to return our sum and that'll give us the right answer assuming we could type out two more lines of code so we just need to figure out what the left and right boundaries are and that's super easy because we figured out what our boundaries were earlier so we just for the left we just do whatever my current index is minus the previous lesser i and oh okay i'm gonna go back i've missed one line of code up here and i know and i'm gonna go over it in a second but let's just let me keep going and i'll explain what that line of code is uh next so for the right it's our next lesser or equal um yeah next lesser equal minus i okay so it's better if i go through a really quick example to explain to make sure to confirm to you guys that this does indeed work and then you'll see what code i need to add up or what line i need to add up here let's just take our original example because we'll just stick with that i feel like that's it's already in your guys heads might explain another example um so this seven up here let's say the seven this is index two so this i is two my previous lesser in this case is four and what i'm saying here is two minus zero equals two well in this case two equals two oh my gosh i can't type two equals two minus zero okay we can see that works and because there are two's positions to the left right there's let's remove these brackets so it's not confusing there's two spots that we can put this bracket in on the left there's one there cool and for the and then let's just say that this happens to be let's say we're doing we're on i equals zero if i was actually equal to zero right now then let's get rid of this remember that so i is equal to zero uh we said up here if there is no previous lesser then we're going to set it to negative one so our previous lesson in this case would be negative one and zero minus negative one is one because minus plus okay we all know how to do math so um left would equal one and there is indeed one spot on the left of that four okay so this line of code is definitely correct now the line of code that i messed up or that i forgot to add let's just do the right and you'll see what it is so let's take this uh let's see which value do i want to do let's do let me shorten this down a bit so the math is just super simple um let's say there was a 2 here so we'll start with the basic example let's bring this down let's say we're doing the seven again right this is index two again and our next lesson would be at index four so four this would be a four here minus two is two and are there two brackets to the right one two it is so we know for the basic case it works now where i know it fails is let's take uh let's say there was no previous or next lesser elements let's remove that too let's say all this is all we have to work with right here well because i have no next lesser element right now i would be saying next lesser or equal so this would be equal to two minus zero and which is wrong uh wait sorry no zero minus this would be zero minus two so this i is this two up here and the reason this is wrong is because we get negative two right there isn't negative two spots to our right uh and that's because you know an integer array it'll just initialize all the values to zero at the beginning what i needed to add is let me just copy paste this i need to initialize all the elements in the beginning to r dot length because remember uh all if an element doesn't get popped it has no next lesser element so if it's not going to get popped what ends up happening is it'll just stay as this value the that index will just stay as r dot length and yeah and if it was going to get popped it would just get over in here by the actual next lesser value or the next lesser index that it's at okay so now what i'm saying here because i just took care of this line now what i'm actually saying is the next lesser or equal is no longer zero because i filled it with r dot length which in this case there's only four elements here that'd be four minus two because of this seven is at index two uh and there are two spots to the right and four minus two is two so now i know this is correct okay and i'm super sorry i forgot this line i should have included it but hopefully that makes sense if it doesn't get popped it has no next lesser and this value will never get overwritten because yeah i just won't okay um so yeah let's go ahead and run this make sure it's all right and i think we're done so let's see of course i made a mistake uh i forgot to cast this back and i made this along because i didn't want to deal with stack overflow or did i go wrong did i make a compiler where did i mess up let's see r i times left times right some odd this looks fine to me did i mess up the mod is that what this is about i think i did let's see long sum equals zero double mind hmm i'm gonna change this to longs because i think i just have stack overflow let's try that again oh that was what it was okay cool um so yeah i can just guess these the i minus and the next whatever subtraction addition whatever i'm doing here uh i just had some stack overflow so anyway uh yeah so that's how i would solve this problem um there is an alternative to finding the previous lesser index clusters if you don't like how i did it so like for example i did this in one loop right there's another way to find these previous lessons um which i kind of i hinted at earlier where if i look from the beginning of the array i can find my previous lesser elements and if i loop from the end of the array backwards i can find my next lesser elements but if you want to try to do that do it that way um it's totally up to you uh maybe go watch my monotonic stack video to see what i mean by like looping from the back and looking from the front to find your next lessons in than previous lessons whatever um but yeah that is it for this problem and uh oh i guess time complexity so when you for you when you use a monotonically decreasing stack or increasing stack whatever um the time complexity is just o of n to find all the previous options and next letters because each element in the array that we're pushing and popping only gets every element gets pushed once but every element only gets popped at most once so that's just like at most two operations per element in the input array so the time complexity is just o of n um and yeah so you can clearly see we just do one loop here so that's still oven and this fills of n uh so the whole time complexity this whole entire thing is just of n uh for space you would just say it's oh then because of the stack and these arrays that we create here are just so then okay so uh yeah that's it thanks for watching if you liked the video if it helped at all you could like the video uh and you can subscribe if you want to see more videos and just comment below if you want to see any other problems okay bye
|
Sum of Subarray Minimums
|
koko-eating-bananas
|
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104`
| null |
Array,Binary Search
|
Medium
|
788,1335,2188
|
122 |
hey guys this is Jay sir how are doing in previous video we've done the best time to buy some stock problem today we're gonna do into the follow-up which we're gonna do into the follow-up which we're gonna do into the follow-up which is sell stock - so we have the same is sell stock - so we have the same is sell stock - so we have the same prices but now rather than one-time prices but now rather than one-time prices but now rather than one-time transaction we could buy and one and sell one share of stock multiple times as complete as many transactions as we want we may not engage in multiple transaction at the same time mm-hmm we transaction at the same time mm-hmm we transaction at the same time mm-hmm we must sell the stock before we buy again okay so for this example we buy on for the example is the same as previous one so for this one because we can trade many times we could buy at one and sell at five and then by three sell at six right so this is gonna be the biggest profit which is seven so and for this one two three four five by one and a cell and five so yeah so we get the max pop maximum is 4 5 4 mm-hmm and 7 6 4 3 pop maximum is 4 5 4 mm-hmm and 7 6 4 3 pop maximum is 4 5 4 mm-hmm and 7 6 4 3 1 Wow it's that the price is always going down so it's zero so how can we do this well we analyze the examples as carefully as much as we can the example is here when we get when it's go down like 7 1 of course 7 it would be abandoned rise because 1 is smaller than it we won't buy a 7 SL 1 and now for one the next one is 5 we just stopped by 1 and sad 5 but can compare Li we get 1 - we didn't SL up to or sale at 5 1 - we didn't SL up to or sale at 5 1 - we didn't SL up to or sale at 5 which means this way is a continuous like ascending array right so we saw it for a sale at the last element why would do that but for the case here with a sell right away because 3 is smaller than 5 if it is a sex here was by one SLR six right why don't we spy one and sell a six here because if you do that the maximun will be five right but there is a going down from five three actually the problem is the same if we if this three is five right so we can buy one set of five you gotta be four and if we got five six we got one so we do two transaction to achieve the same result as one six right but now the five becomes three it means it goes lamp down a little bit so it's actually give us more profit rather than we buy one SSS six you could buy one set of five and then PI 3 has six so there will be some like overlapping right if you draw it like oh and a line there will be some like going down going up so totally you will earn better so that's uh and together with this example that reminds us we can actually do as follows right so we first we met a like soon to be ascending point right the I mean minimum right point one point a soon - too soon to go up which is like soon - too soon to go up which is like soon - too soon to go up which is like point at one what's the character risk of death this one and the point of this one would be the next one like a I next one is bigger soon to be killed what a previous one is smaller and the point to sell Oh like the point by huh will be soon to go down the next is smaller mmm okay Creve is not smaller next one is smell like this next one is smaller but previous one is not bigger okay it's not bigger this is not smaller right so like here we got this one seven one next one is bigger so we gonna soon go up and then we continue searching and find the this one is soon to go down and then got this three soon to go up right yeah so we can just look through the array and find this point and keep track of the previous one and then we could sum up the profit right cool let's do it so the profit of course is zero for that we need to keep track to know the next one so we use index based for the zero I stood up I say stop then I plus we made a possible one we just continuous doing continuous searching to the point to sell so we don't use in this photo they will it be an inner search and yeah doing a search so that we will not care about the previous one right uh-huh this one would be this one should uh-huh this one would be this one should uh-huh this one would be this one should be the possible the first one what it is should be it may be possible okay next one is smaller three Winston's not bigger okay so now we search for the point by right if it is point by not search for point by if it is the point by it is two point by research next to the point so right okay if the point because we're going to you know search here we actually don't care about pre and for sale yeah after we sell we actually well search to the by so we actually don't care to care about the proof also right cool if it is point by how can we determine it if it is if crisis i if i equals zero or crisis i plus 1 is bigger than process i so this is the point back this is point two by then search for the point sell it might be itself for seven right because seven itself so we skip or we say because by 7s cell 7 we cannot sell on the same day but theoretically it's zero so let's search for point cell well we start at that number itself let J was i we will search for the cell which is soon to do now next one is smaller than it so we will continue to loop while next one is bigger or equal than it right or bigger than it hmm yeah week bigger or equal it so while process J plus 1 is bigger or equal to process J we J plus 1 right so the J was stopped at a position where next one is smaller than it okay so we find it now if a J and I might be the same skip so if J is bigger than I profit Crawford loves because we're searching for bigger than that there wait a minute for the keys here this is the limit so this is a at the start the point 2 pi and then they can't be point to cell 0 means they go down so go up mmm okay so it should be prices j- prices i at last it should be prices j- prices i at last it should be prices j- prices i at last we will move I to J right J is the point to sell like here you find the point to sell here and we complete it so I will be next one will be equal to 3 right so the I plus 1 what do it for us so we said I to J and then we continue doing this and finally we could return the profit let's review our killed once more before we submit our implementation okay four seven one five three seven six four because it's zero okay we and yeah we start from zero if the x1 is bigger than it we continue but stop so I equals to J we don't update the profit we move I to J which is 0-2 is 0-2 is 0-2 we got one mix one is bigger mix one yeah it is bigger so we was search for point to sell J start from one and the next one is bigger than it we set to I to five and the next one is bigger no so we stopped at 5 because 5 is bigger than one we've updated the profit and set I to 5 next one we'll go search for JIT 3 do the same and then search for 4 mmm for 4 yeah there's a problem actually the ending right if like 3 1 2 3 4 5 whatever do the ending well and is 2.2 cell actually should account and is 2.2 cell actually should account and is 2.2 cell actually should account at the last intimate as into account like one two three four five we got is one and okay while we put here well go to two and go three equal to four and then stop at go to five and then stop at five because next one is not so J stop at 5 here oh yeah so it's okay so actually Jake I will be moved to J this is the setting point I got 4 and then go to next one is overflow so yeah I think it should be right Monaco yeah some it cool or accept it so that's all for this problem hope it helps yeah so what we learned from this problem you also we analyzed the example actually an example to give us a hint right actually for this substring some smacking problem this is the action in normal case until one white why don't so we think why don't we why should we sell five but not six hmm and now we hit your example that here okay so it's continuously a sending array who we will buy at the beginning a sell at the end and we realized that if remember that we said before so if one two three four it's actually the same okay so it's the case here one four six is actually the same two one five six because one five this is 0-1 so if it is up go five this is 0-1 so if it is up go five this is 0-1 so if it is up go upward or not go down so all the upward we will be connecting right so 1/5 or was exactly equal to 1/6 but one 1/5 or was exactly equal to 1/6 but one 1/5 or was exactly equal to 1/6 but one five three six it's not so it's actually equals to 1 5 and 3 6 it means that we actually crush this array into similar into segments right so one five six we crush it into one six so it will we just finally we collect this the profit of each segment so yeah let's analyze more on the example and find a way out so that's all for this one of helps see you next time
|
Best Time to Buy and Sell Stock II
|
best-time-to-buy-and-sell-stock-ii
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
121,123,188,309,714
|
129 |
hello everybody welcome to another video on problem solving in this video we're going to be solving a problem on lead code which is some root to leave numbers so let's just quickly go through the description and then we'll see how we'll be solving the problem so we've been given the root of a binary tree which contains digits from 0 to 9 only and we've been given that each root to leave path in the tree represents a number for example the root to leave path 1 2 3 would represent the number 123 and we need to return the total sum of all root to leaf numbers and the test cases are generated such that the answer will fit in a 32-bit integer answer will fit in a 32-bit integer answer will fit in a 32-bit integer so let's see what the problem actually is so let's take an example of this tree in this one is the root and two and three are the leaf nodes for those of you who don't know what leaf nodes are a leaf node is a node with no children it's been given over here so two and three are the leaf nodes so root to leave path in this tree are one two so this is one root to leave path and one three this is another root to leave path so the number of root-to-leaf paths so the number of root-to-leaf paths so the number of root-to-leaf paths would be actually be the number of leaves present in the tree so this is one root to leaf path this is another root to leave part and the number resulting from both of them are 12 and 13 respectively so you can see where 1 2 and 1 3 results in what 12 and 13. so what we need to do we need to find all the numbers which are represented by root to leave paths and find their sum and return it so let's see another problem over here we have three leaf nodes five one and zero so one leave root to leaf path would be four zero which represents forty another root to leave path would be four nine five four ninety five another one is four nine one four ninety one and their sum would result us with one thousand twenty six so this is what the problem is we need to find all the root to leave paths find the numbers that represent sum those numbers and return now let's just go through the constraints it says the number of nodes in the tree range from one to one thousand and their values range from zero to nine and the depth of the tree would not exceed ten so now let's see how we'll be solving this problem so obviously to we need to visit every node so we'll be needing to traverse the tree and to traverse the tree that's i'll tell you how i'll be doing it so we begin from the root we go left and as we go left we take this number along with us and what we do is we try to form a number with our previous number and our current node nodes value so we are first at 4 we go to 9 we store 4 somewhere and we multiply the number that we have got from the previous call we multiplied by 10 and we add our current nodes value in it so we get 4 we multiplied by 10 add 9 we get 49 we go left we get 49 multiplied by 10 490 plus 5 495 similarly from here from this node if we go right we get 49 multiplied by 10 490 plus 1 491 and again over here 4 we go down we say 4 into 10 40 plus 0 40 so this is how we'll be finding all our sum to root to leaf numbers and then we add them up and get our answer now to traverse this entire tree i'm going to be doing it recursively so coming to the code now i am going to define another function which is let's call it void traverse sum and now the parameters that this function is going to take is obviously one root pointer tree note star root and let's call our variable prep sum so this prep sum variable would help us keep a track of our previous sum for example over here when we were at 9 our previous numbers 4 when we were at 5 our previous sum was 49 at 1 our previous sum was also 49 so like that so we'll be keeping a track of our previous sum and then we'll be adding our current nodes value in it after multiplying it by 10 so let's see what i'm going to do now what i'll say is i'll say in sum is equal to prem sum into 10 plus root of val so that should work about right that should give us the correct sum so 4 will go down 49 and so on that's how it's going to work and now i'm going to traverse the tree for i'll check if root of left and if it has a left child i'm going to give it a recursive call i'll say root of left and i'm going to give it the previous sum as my sum at this node so let's say we're currently at 9 and we got 4 as the previous sum multiplied by 10 40 plus 9 gives us 49 and when we call we give the recursive call to the fifth to this node it gets the previous sum as 49 and it does the same thing similarly if root has a right child then we give it a recursive call we say traverse sum root of right and sum again so these calls would help us keep the track of the sum we'll have the sum and now what i'm going to do is keep a boolean and let's call it is leaf and i'm going to initialize it with true and whenever we go over into one of these if conditions let's say is leaf equal to false so now what we're going to do i'm going to add the sum of the number represented by the root to leave path only after i have reached the leaf node now to check if i am currently at a leaf node or not i need to keep this boolean which will give me an on give me the answer to that question and if even if it has one child if our current node has even one child then it is not a leaf node so now what i'm going to do i have my sum i have my boolean which would tell me if it's a leaf node or not now what i'm going to do i'm going to initi i'm going to define a global variable sum so let's call it sum to return and every time we get our leaf node we say if is leaf so if our current node is a leaf node then what we need to do is we need to say sum to return plus equal to sum so what this will do is it will increment the value in sum to return by our sum which is the current number represented by the root to leaf path now this function would give us the correct value of sum to it of our sum in this variable now all i need to do is call this function so what i'm going to do now in this sum numbers variable i'll say traverse sum root and i'll be beginning my sum my pref sum with zero so what will happen as soon as it enters the tree enters the function it says sum is equal to 0 into 10 plus root of val so we'll be beginning from 4 and thereafter it will happen it will handle itself another thing which we need to do is sum to return equal to 0. now why we're doing this is because this function over here is being called from the main function multiple times so every time we get a new test case we get a new tree we need to re-initialize sum to return we need to re-initialize sum to return we need to re-initialize sum to return variable back to zero so that we can get the correct value in it so sum to return we've initialized it to 0 and traverse some row we have called the function now we can simply say return sum to return and let's just put a corner case check if not root return 0. now this looks about fine it should work properly let's go ahead and test it with the example test cases it works fine for the examples let's go ahead and submit it all right it works fine for all the test cases with 100 better run time and 21 better memory usage so there you have it that's the solution for some root to leaf nodes and i hope you like the video and do make sure to like and subscribe if you found it helpful
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
230 |
hello everyone welcome to day 18th of april eco challenge and i hope all of you are having a great time my name is ansel today i'm working a software developer for at adobe and today i present day 661 of daily lead code challenge the question that we have in today is kth smallest element in a bst here in this question we are given a binary search tree and we need to identify the kth smallest element that exists in this tree so here they provided us with few examples and i'll be walking you through this example as well as the algorithm to go about it why the presentation so let's quickly hop onto it lead code 230 care smallest element in a binary search tree it's a medium level question on lead code and i totally feel the same also in case if you have any doubt or you want to ask anything from me in general please feel free to ping on the telegram group or the discord server of coding decoded both the links are mentioned in the description below without further ado let's walk through the test case that was specified in the question we have the binary search tree as this one and the value of k is three that means we are looking for the third smallest number let's go back to the property of binary search tree says that all the left child with respect to the current node will be smaller in nature and all the right child of the binary search tree with respect to the current node will be greater in nature and we already are aware of that the in-order already are aware of that the in-order already are aware of that the in-order traversal of the binary search tree is sorted in nature so let's perform the inaudible this binary first three what do you get you will get one two three four five six so we'll get the elements as one two three four five and six so one of the simplest ways to cast this tree into an array and then identify the third element in that array that would be the kth smallest element this is a naive approach that comes to everybody's mind that let's do an inorder traversal and let's cast this entire tree into an array and then we can pick up the third element from the target that will give us a result however is this casting actually needed it's not it is adding to extra space complexity of size n which we can avoid how can we do that we can do it in place while traversing through this binary search tree in an in order fashion what i'm trying to say let's walk through an example and you'll understand let's shoot for iterating over the inorder traversal for this binary search tree and as per the inaudible the way to go is left info right so we are given the root of the binary search tree as five let's proceed ahead and let's perform the left info right over it so let's invoke in order over five i'm writing in means in order over five the first thing that i'm going to do is this one and the value of p remains us three so let's proceed ahead next since five has uh the left child last three so recursively we will first invoke in order on three so in order on three gets invoked next we have three also have two as its left side so in order of two will be first invoked in order of two and since two also has a left child which is one so in order of one will be invoked now let's continue it further you see you can see that the left child of one is null and that means it has been visited we will obviously not go towards in order of null because it's already null now it's time to visit the info node since it's time to visit the info node what is that node is one that means you have identified the smallest element that exists in your binary search tree and since you have identified and you are visiting the info node what you are going to do you simply reduce the value of k the value of g gets updated to two the smallest element that you have identified happens to be one which is a first leaf node and then you will move towards the rightmost direction and you will invoke in order on null again since it's null you will traverse back and this node has completely been visited left node has been visited the info node has been visited and the right node has also been visited this completes the iteration for this entire node so this is gone so we are going in the reverse direction now let's shoot for this particular one in order of two and since its left child has been visited now what we are gonna do we will invoke over the info node since we are iterating over its info node we will reduce the value of k by one so one gets updated to key gets updated to one and the second smallest node that we were able to identify is this one that is two now we will shoot for iterating over its right side the right side of do is null since it's null obviously we are not going to go in its depth we will proceed ahead so this completes the in order of two as well its left node has been visited its info node has been visited its right node has also been visited now comes the case where we are iterating over in order of three as you can see we have successfully iterated over its left child that was one and two and this is the time to actually identify uh the info node for three whatever the info node for three it is three itself as a result of which we will simply reduce the value of k to zero since the value of p has been reduced at this particular position to 0 that becomes your answer this node is your answer which is 3 had it been the case the value of k would have been 4 initially then at this particular position it would have been reduced to one and we would have i traded over its right child in order to check for whether a node exists over there or not which in this case it does and then we would have performed in order on four in order to achieve our answer i hope this algorithm is clear to you are not doing anything extra apart from the inorder traversal and you are simply reducing the value of k as you are progressing in the in order traversal so i like to conclude it further let's quickly walk through the coding section and i'll conclude it there here i have created two variables one is the count which is a copy of key and the other is the one for storing the result and in the case smallest method i simply update count to k and i invoke my ks smallest util i pass in the root and in the end i simply return the result so the problem lies in writing this helper method appropriately in case my root happens to be null i simply return back otherwise i go in the inorder reversal in order traversal means left part first once i'm done with this i simply reduce the count value in if in case my count happens to be 0 i update my result to root dot val and i simply return back from there otherwise i go ahead and i treat over my right child that is root dot right so as per this logic this is iterating over its left child this is hydrating over its root and this is iterating over is its right side so left in for right and once i'm done with this as we simply return back the time complexity of this approach is equal to the time complexity of inorder traversal which is in the worst cases order of n and the space complexity is order of log n which is the height of the binary fourth street this brings me to the end of today's session i hope you really enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for being here 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
|
Kth Smallest Element in a BST
|
kth-smallest-element-in-a-bst
|
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
**Example 1:**
**Input:** root = \[3,1,4,null,2\], k = 1
**Output:** 1
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], k = 3
**Output:** 3
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 104`
* `0 <= Node.val <= 104`
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
|
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
|
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,671
|
83 |
okay so we're looking at question 83 remove duplicates from sorted list uh given the head of a sorted linked list we want to delete all duplicates such that uh every element value kind of just appears once um and our linked lists return links list should be sorted as well given an example one two we wanna basically return one two and then um you know one two three return one two three uh constraints are number of nodes is in the range 0 to 300 and then the values of the nodes ranges from minus 100 to 100 and they say that it's guaranteed to be sorted in ascending order array already so we kind of don't have to worry about solving them or whatever for the return list returned linked list yeah okay so again i feel like let's see so basically what it's about is that given two notes with the same value we kind of have to delete one and by deleting it just basically means to link up the previous one with oh let me just it basically if we want to delete this note we just want basically what it means is to draw this link to here instead right that's how we do the division okay um okay so let's see i feel like for this question we can implement it in an iterative way and also a recursive way uh if we start from the back and have the terminating condition set at um basically the last note right we can kind of compare oh sorry let me just get my drawing tool out um basically this is our terminating no because it's the last one we kind of just compare previous one with this one and then if it is the same we set this node this 3 to the next value of this node which in this case is none and then continue doing this for okay and then now with this in question kind of just keep comparing and then when it comes to here it's the same and we will do the pointer like that okay so yeah let's try doing that or exit drawing mode okay so let's just do the recursive function with this delete duplicates function a terminating condition first if uh head dot next is none return head okay and then um we should start comparing stuff right um be like next though is equals to self dot delete duplicates head dot next because i kind of want to compare the current note with the next note so if no if head dot vowel value is the same as next notes value what we want to do is set head dot next to the next notes dot next yeah next no dot next after that what we want to do is return right return what return the head at the end of it all okay let us try okay oh um okay it looks like because given this an empty linked list this condition like this results in a error because there's nothing in the list so what we can do is if i mean i don't know let's just do something simple i guess it's none return hit at the very beginning okay great all right that's it for today's video thank you
|
Remove Duplicates from Sorted List
|
remove-duplicates-from-sorted-list
|
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List
|
Easy
|
82,1982
|
598 |
hey everybody this is larry this is dave dude yeah from the august the code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom and all that other good stuff uh as long as it loads okay range edition two so i usually start these live so watch it at the speed that it is comfortable for you uh okay so you give an m by n we turn down the number maximum interest in the matrix after performing all the operations okay let's see m and n could be pretty big operations can also be pretty long okay um i feel like this is just like the one that we have done recently well oh wait what this maybe i misunderstood something okay hey obtain b you got four zero yeah hmm number of maximal integers i guess the other one is an interest um it's a little bit awkward it could be an intersection and could be the other thing uh because i think the um the problem that we did a couple maybe last week or a couple of weeks ago um that one you kind of get the union of stuff right um because it's just boolean but here you almost kind of want it into i was going to say you want an intersection almost except for the cases where for example you have two squares or something like that don't intersect with each other then in that case you actually want to sum up those two but a key thing to know here is that you always start at the corner and because at the if you always start at the corner there's no way so every intersection has to be um every intersection has to be done at that corner and therefore it makes this problem a lot easier because now you're just taking the min of the x's and y's um and you can draw this i mean this is my intuition um and this is maybe just for years of experience to be honest um but i think if you draw it out you can see that every time so you start with basically everything filled and every time you draw one and because it has to be only from the corner you basically chop it off right um and you always take the min or max of the x and y's and i think as soon as you realize that then you just realize that this is just a for loop so yeah so basically you then have and you could even do you know just a pen uh m and n into the thing and then now you one min of um yeah i guess this i guess there's no really good way of writing this there and yeah because i wanted to write something like i'll write it out i suppose min xm in y uh is equal to i guess m n doesn't really matter and then now for x y and ops i you could do a one-liner but then you end up doing do a one-liner but then you end up doing do a one-liner but then you end up doing two iterations so it's a little bit weird um at least the way that i was writing about it if you're a python master let me know how you would do it but yeah mx and y is equal to i mean up mx m oops this is uh min of my y and then just return mx times n y at the end this actually started out very hard but then maybe not so much i wish they made this copy paste a bow oops so yeah so okay so then now i think i'm okay with submitting there's no overflows that's what i'm just double checking so yeah let's give it a spin okay yeah so the key observation for this one is to notice the corner thing and then kind of just thinking about each one slices it because you're forced to take it from the corner um huh that's cute yeah i don't know what to say about this i'm trying to think about what is a good way to think about it um like what is my intuition here and to be honest and my intuition is just from a lot of experience i don't know if i could explain it for this particular problem but the observation is about that you start at the corner and i think maybe the easier way to think about it is thinking about one dimensional first and for these kind of ranging things um it doesn't always generalize but in this case there is this thing uh where both dimensions are independent it's not like i said not every problem is going to have to x and the y's are being independent but if you think about it that way then uh or at least you give yourself a chance to think about it that way like are they independent and what would they look like well in that case then you look at it in a 1d kind of way and in one dimension you know if you could draw boxes from or yeah in this case yeah if you could draw boxes from like five by one and then four by one and then we buy one well how what has the most what has the maximum what do they call it maximum integers right um i mean like i said it doesn't always generalize in higher dimension but these are things that i would look for in patterns to think about it and in my case i would think about well what about two times five and how have that work out and that's how it may be extended that way um yeah and you can clearly see that this is linear time and constant space um i actually don't think i need it here but i thought i was gonna write it another way you could write it this way if you wrote something like and i was thinking about something like return min of x for x2 and ops times min of y for to do y and ops but i don't look awkward to have two um two for loops but i don't know you could um but this would make it easy this would make this possible but i guess technically i don't need it now because that is by default right anyway so yeah linear time constant space let me know what you think uh hit the like button hit the subscribe button drive me a discord hope y'all have a great week and of the month we'll start again in a couple of days or you know tomorrow whatever you like i'll see you later stay good stay healthy take a mental health bye
|
Range Addition II
|
range-addition-ii
|
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`.
Count and return _the number of maximum integers in the matrix after performing all the operations_.
**Example 1:**
**Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\]
**Output:** 4
**Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4.
**Example 2:**
**Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\]
**Output:** 4
**Example 3:**
**Input:** m = 3, n = 3, ops = \[\]
**Output:** 9
**Constraints:**
* `1 <= m, n <= 4 * 104`
* `0 <= ops.length <= 104`
* `ops[i].length == 2`
* `1 <= ai <= m`
* `1 <= bi <= n`
| null |
Array,Math
|
Easy
|
370
|
1,649 |
through instructions yeah this problem is very easy to understand and it's also easy to do if you use the right data structures so let's first try to understand the problem so we are giving a r of instructions and you asked to create a sorted array from the elements in instructions you start with an empty so for the first example we are starting with the empty array now we are going to insert the element in instructions inside our array nums yeah we are begin with a empty array now we're going to insert one inside the nums yeah so if we insert one we need to find how many elements which is smaller than one and how many elements which is bigger than one so currently after we inserting one there's no element smaller or bigger than one so it going to be the minimum of zero because we want to choose the minimum value and our final result should plus this zero and second we're going to insert five yeah because there are only two element normally you should understand if there are only two element it is not possible yeah and how many elements smaller than five it is one and how many element bigger than five no it is zero so one and zero it is a zero now we're going to insert six similarly there's no element bigger than six so it going to be the minimum of two and zero so it is a zero and then we're going to insert two so after inserting two how many element smaller than two it is one how many element bigger than two it is a two there are two elements so we're going to choose the minimum so finally we're going to sum up all those values so the final result is one yeah after analyzing of the first example I think you've already found a solution you just needed to choose a data structure to solve the problem so for me in Python I'm going to use the sorted list yeah because the sorted list after in after insertion all the elements inside the nums would be sorted in increasing order after in increasing order I'm going to use binary search to check how many elements bigger than two or smaller than two yeah and then I'm going to choose the minimum yeah but there's also duplicate I think the hard part is about the example three because there are duplicate we need to think about how can we avoid the duplicate element or if there are duplicate elements how can we count the duplicate element and make the uh result tot exactly like that yeah so I'm going tol this example three later inside my code now let's just start coding so I'm going to use a sorted list so from sorted containers uh I need to import the sorted list yeah uh sorted list so I'm going to prepare the sorted list so the sorted list will would be uh just to S the list now I'm going to check the instructions one by one yeah so for I inside the instructions this I is just a integer so for my sorted list I going to add this element inside my sorted list so sorted list should add this element I yeah so for example from the beginning it is a empty now I add element one inside yeah but for this sorted list I don't need to start from the beginning I can start from the while the length of the sorted list is more than two so for example if it is five so the result should also be zero if there are three element maybe I can have a result or maybe it is zero but I'm going to start from this three elements it means it's the sorted list the length of the sorted list is more than two yeah so for this example it is zero yeah but there's no better examples but uh for example if the third element is not six if it is a four so it means I've already get a result one yeah so this is why I'm going to T from the length of the sorted list is if it is more than two I'm going to Tex the result maybe I can get a minimum value yeah um but how can I get the um par so for example if uh yeah so for example if I put one five inside next I've got a six and I've also put the six inside my sorted list yeah so this I is just a number uh it's not index so yeah maybe I can use a number n maybe you can understand it better yeah because n is just number so I put the numbers inside of the sorted list if this sorted list is more than two it means I've already um add six inside my sorted list yeah currently I have one five and six I can use this value this is six I can use a binary search to check what is the closest Value to this six yeah because if I can use this closest Value I can find yeah uh just let me make it easily to understand yeah if I insert six inside I just need to find how many element which is smaller than six how many element bigger than six currently there are two element smaller than six and zero element bigger than six yeah I just need to calculate it like that yeah uh let me use a uh index Z should be equal to uh B yeah I'm going to use the sorted list because sorted list also can use the bisect left yeah so the SL um BCT uh left sl. BCT the left uh with a number so this number going to be my current number yeah even I added it inside but I can still use it because it's going to be easier for me to solve the problem okay uh yeah I going to directly check this number is n yeah so for example if I use this number n it is a six so the index for this J would be two so how many element smaller than six there are two elements yeah because uh according to the question all the numbers inside uh yeah let me think about it um yeah if I put a six inside uh all the element before the six should always be unique you need to understand it like that yeah because even here maybe a six but all the element before this is six one and six they are unique there's no dup no duplicate numbers at the left of this number yeah this is the properties of the bisect left so this means from the left side there are two element smaller than six yeah because bisect left is always bigger than the previous ele bigger and equal than the previous element yeah more than and equal than the previous element this is why we are sure there must be two elements smaller than six so we can get a minimum value um so the minimum would be the uh minimum of the left side and the right side so from the left side we are sure it is a um Z element yeah let me check if this is J or yeah if I check this is six yeah so from the left side there must be J element yeah because this index is two so I can use this two directly yeah and how many element at the right side of uh this six so it going to be the length of the sorted list currently yeah for this one it is the three yeah so the three so the minus z equals to 2 it is one which would still minus one so this is just a mathematical calculations you need to understand it like that yeah so what is the final result uh the final result is just you need to use your result plus equal to the minimum number finally you just needed to return the result so let me prepare the result to be Zero from the beginning now we are sure this example and the second example should always work because there's no duplicate numbers if there is duplicate numbers I will analyze it later yeah let me just run it to check uh yeah as you can see it works for the first and second example but it didn't work for the third example yeah because there are duplicate numbers we need to think about how can we solve or handle the duplicate numbers yeah as you can see here uh the expected result is four but our output is six yeah this is because of the duplicate numbers as you can see there are so many three so we're going to analyze the UND duplicate numbers yeah so for example currently before uh we have a state of like 1 two 3 three uh yeah I'm I think I'm going to use a better example um yeah I'm going to use this example maybe currently I have three numbers 1 three and next I'm going to insert three inside yeah but where is the position you should know about if I were to insert three it should be at this position I mean the second number index one it because it is a bisect left yeah I need to handle this case now let me make it here yeah you need to understand how can we get the result from this array to the second array yeah so we're going to prepare some data structure to solve the duplicate numbers so from the left it should always work so for example if we insert three from this array so the three would be here and this J should be equal to one and how many elements smaller than three it is one so it is this index J but let's just check this one it is the length of SL it is a four minus Z minus one it is a three minus one it is a two yeah but our result should be zero because there's no element there's no elements bigger than three yeah so this is why it is wrong for the result so what kind of data structures can we use to solve this kind of a problem yeah so it me for each of the itation we need to store how many Ser yeah uh how many thre inside the dictionary yeah so we can add a three inside our sorted list but we also need to record how many thre So currently we need to know there are two threes inside of the dictionary before we adding this three we just added it but we need to know how many three before we add this three so there are two we need to record this two numbers of the three of course we can use a dictionary so let me just use a counter so say would be equal to a counter but we need to add this number at the end of the line it is not before yeah because after executing all this um all those line yeah we got a 1 three and we need to count there are two three so it means after executing this line we're going to use the counter to add it to the result so it would be say n plus equal to one yeah as you can see it is a s two line and it makes our problem really easy yeah if you don't understand you just need to use try to use more examples yeah because from here we need to record there are two seres and from here after put it inside so we're going to use this formula length of the array it is a 4 minus 3 - one - one it is a two and we minus 3 - one - one it is a two and we minus 3 - one - one it is a two and we need to minus this say n this is say three it is a two so it going to be zero at the right side at the left side is it is one and the result would be zero for current uh situation for the current execution from this array to the next array yeah now let me just run it to check if it works as you can see it works yeah now let me submit it to check if it can pass all the testing cases yeah I hope it can pass yeah let's ass this hack uh yeah this is why I think this going to be a really big number maybe there's a modular I forgot about it yeah there's a modular I forgot about it we should always use this mod so the result should be uh yeah I need to be careful about reading the problems yeah so I need to prepare the mod so the mod would be 10 to the power of 9 plus 7 yeah because it's going to be a really big number now let me just run it to if it works yeah as you can see it works uh the time is just so slow I didn't expect it is not so slow so yeah it is the 73% 2 seconds is still yeah it is the 73% 2 seconds is still yeah it is the 73% 2 seconds is still okay because n is 10 to the power of five and unlog in would takes time for python 2 seconds is still okay yeah um thank you for watching see you next time and by the way this reading is just 2200 yeah normally for this kind of questions the reading should be like 18800 or 1900 yeah or maybe um yeah maybe if you use some uh difficult data structures like balance the tree or binary index the tree or segment tree that going to be a little bit harder but basically that is also the template yeah thank you for watching see you next
|
Create Sorted Array through Instructions
|
maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
|
Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The number of elements currently in `nums` that are **strictly less than** `instructions[i]`.
* The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`.
For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.
Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`
**Example 1:**
**Input:** instructions = \[1,5,6,2\]
**Output:** 1
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 5 with cost min(1, 0) = 0, now nums = \[1,5\].
Insert 6 with cost min(2, 0) = 0, now nums = \[1,5,6\].
Insert 2 with cost min(1, 2) = 1, now nums = \[1,2,5,6\].
The total cost is 0 + 0 + 0 + 1 = 1.
**Example 2:**
**Input:** instructions = \[1,2,3,6,5,4\]
**Output:** 3
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 2 with cost min(1, 0) = 0, now nums = \[1,2\].
Insert 3 with cost min(2, 0) = 0, now nums = \[1,2,3\].
Insert 6 with cost min(3, 0) = 0, now nums = \[1,2,3,6\].
Insert 5 with cost min(3, 1) = 1, now nums = \[1,2,3,5,6\].
Insert 4 with cost min(3, 2) = 2, now nums = \[1,2,3,4,5,6\].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
**Example 3:**
**Input:** instructions = \[1,3,3,3,2,4,2,1,2\]
**Output:** 4
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3,3\].
Insert 2 with cost min(1, 3) = 1, now nums = \[1,2,3,3,3\].
Insert 4 with cost min(5, 0) = 0, now nums = \[1,2,3,3,3,4\].
Insert 2 with cost min(1, 4) = 1, now nums = \[1,2,2,3,3,3,4\].
Insert 1 with cost min(0, 6) = 0, now nums = \[1,1,2,2,3,3,3,4\].
Insert 2 with cost min(2, 4) = 2, now nums = \[1,1,2,2,2,3,3,3,4\].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
**Constraints:**
* `1 <= instructions.length <= 105`
* `1 <= instructions[i] <= 105`
|
Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal.
|
Array,Hash Table,Greedy,Prefix Sum
|
Medium
| null |
1,557 |
foreign hey everybody this is Larry this is me doing oh whoops one button okay fine uh what am I doing I am doing day 18th of the May liquor day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this farm and as you can see well maybe not I don't know but yeah my intro is uh me and Georgia in Tbilisi uh so yeah I hope you know you enjoyed that drama video let me know what you think uh either way you know Skip ahead if you need but uh okay let's take a look at today's problem it's gonna be 1557 minimum number of vertices to reach all nodes so give it a directed asynchronic graph with n uh vertices numbered from zero to n minus one and then away edges where edges of I is from the two represent a directed Edge from node from I and no O2 sub I okay find the smartest set of vertices from which all notes in the graph are reachable it's guarantee that a unique solution exists notice that you can return the vertexes in any order so I think this is basically some formulation of um some formulation of topological sort my first inclination is that if you get all the notes of zero in degree it should be good enough um the reason is uh I mean and to be honest to be clear and to be honest I'm not a hundred percent confident at this point um like if I was doing a contest or something like this that would be my first instinct but I would have to like you know uh I would have to think about a little bit to prove it to myself right and also just to kind of on that point to proving to myself isn't you know it's one of those things that you get by practicing and what I mean by that is that when you practice enough then you're able to maybe you could say cheat you could say Intuition or whatever but at the end of the day is because you've done the work enough that you know certain things are true right um because I haven't done it enough because I haven't practiced enough uh I don't know that I could confidently say that um for this one so in that case I'm going to start some uh ex you know um dude the one thing I would say is that what I said is definitely uh well yeah so you can prove it very quickly because they're really only two cases right um but you should know there's zeroed in degree and noticeable with uh more than zero in degree right um notes that I with non-zero in degree it non-zero in degree it non-zero in degree it um how do you say this uh well if it that means that and an edge is pointing to it right which means that by definition instead of picking this node you just pick the node that is the parent of it if you will the right and then you can kind of uh maybe recursive isn't the right word but you could kind of like you know iteratively and kind of go through that process to kind of get the parents node right and then there's zero degree node in that case would be optimal because um because literally you cannot reach this note from any other position because literally has zero notes where it has to be in this starting set um so what I told you is kind of probably close to the proof I mean maybe it's not as mathematically oh it's not like precise but it's weekly it rigorous enough to be the proof it's just that um yeah and this is off my head just to be clear right um and these are things that uh and I don't mean that as in like whatever what I mean by that is more that um that is what I would need to convince myself to start coding or like in an interview and talk about it and stuff like this right so let's let in that thing that's uh let's get to it right so let's go zero times n from zero to n minus one right yeah okay so then for UV in not myself confused um do you doesn't even matter I don't think to be honest I mean I usually use UV for oh that's just like carbon notation right and then now we have an answer is and then for I in range of n if in degrees of I is equal to zero then enter back I hopefully this is right otherwise when I'm gonna embarrass myself uh well I mean okay oh whoops uh let's give a submit and yeah that seems pretty okay I mean this is going to be this is a tree or anything no um it's tempting to say this is linear but it's not quite linear it is V plus e to be more precise um the reason why V plus e in this case is not technically linear is because uh n is n or V is not the size of the input um so yeah so that's basically it because for example in this particular and I'm giving you an extreme thing uh but it's still going to be all of V plus e uh time uh over we space right um and the reason why this isn't linear is because of a very simple thing right where if N is a billion um an edge then there's no edges it doesn't matter right if N is a billion well this the input size of n is not a billion and n is the billion is the input but not the input size is actually the number of bits we're needing to represent a billion which is say 31 bits or 30 bits or whatever it is I think it's 30 bits um yeah dirty bits right um so and that means that for every uh increment of the input size meaning you go from 30 bit to 31 bit actually the space doubles right so in that sense it is exponential and therefore technically this is exponential but we just say V plus e is probably fine for most people to unders you know understood um but just to you know uh mostly because uh I think from so yeah and there are some optimizations that you can do but um because for because at least for the if N is a billion case you could buy uh clean this up you could use this to just use Keys um so if you do it that way then I guess technically it would be linear it's just that I guess I was lazy um for example you could rewrite this to you know use a dictionary or something like this collection.cover like this collection.cover like this collection.cover right and then this is uh what's it called length of uh well it'll be just it I forget how it goes like that keys or something right um so now here with just some minor changes this is actually linear time right because now just reduces to all of the time and all of e space right um the reason is because now counter is you only get as much we only need space uh that's bounded by edges right meaning if there's a million Edge in degree will have at most a million entries so yeah um and same thing keys right it only has the number of edges in the number of things so that now this reduces it to all of the time and all of the space um and in this case uh years the least dominant one usually it's not but in any case so yeah so now we did reduce it to linear time linear space um yeah just kind of thought I'd bring it up because some uh and this time in a little bit more detail because otherwise I think I forget what I mean anyway that's what I have for this one let me know what you think stay good stay healthy take your mental health I'll see y'all later take care bye
|
Minimum Number of Vertices to Reach All Nodes
|
check-if-a-string-contains-all-binary-codes-of-size-k
|
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct.
|
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
|
Hash Table,String,Bit Manipulation,Rolling Hash,Hash Function
|
Medium
| null |
322 |
in this video we are going to solve one interesting problem coin change so let me first explain what is the problem you have given the three coins one two five this denote the denomination of the coins and you can use each coin in any number this is infinite if you want to two points 10 or you want to Five Points 20 times you can use that so you can use any coins for any number of numbers right any these infinite numbers we have and we have to achieve the amount ever Miss thing is that you have these coins and you want to make the amount of heaven so how much minimum points you can use to make this amount right so find the fullest number of coins to make the payment so if you see that example one two five and that coins is imaginary right so suppose you have the three coins so I don't know whether we used to have the three rupees or three dollars or cent coins are there or not so take this first example right one two five and if we have the coin one two and five and you have to make the amount of however so there are the many ways to make this seven right so either you can use the one points every one times right so you will have the available piece but in this case if you see how many points you use the eleven coins right second option is that you take the two coins five times and then it is also the element right but here how many coins you use we use the six coins right same way if you want to use the five quiz coins and two rupees coins then one so it is also the album is right amount to German but here how many coins you use one two three four five and we have some other options also five plus one plus five plus one here how many coins you use we use the coins chain so you have to find out what is the minimum number of coins you can use to make this payment and the output would be the three here right because 3 is the minimum points so take another example uh suppose you have your two three four and you might make them make the amount for the 12 bit so you have another many options either you can use the six coins of two of the four coins of three or three coins of the fourth right or you can take the multiple points so here might be answered very easy the four plus four and answer is the 12 and you use the three coins right suppose you have your coins too and you have to make the amount TV so it is not possible right so even if you take the one coins it is the two if you take the two coins it is the four so it is not possible so you have to return minus one because it is not possible so this is the problem statement and let me um explain you how you're going to solve uh you might can get many solutions but what I have understood the easiest way to explain I am going to explain so whatever you do it's very easy uh the if you see the number of line of code is just four five kind of codes I will explain you but first what I will do let me explain the solution then I will come back to the coding part okay so suppose if you take this coin set two three four or let me just um so suppose you have on you have given only one coin that is the two and you have to make the amount of 12. so what you do make one array of size amount first one so in this case we have the 12 take one make one array of the size 13 right so 0 1 2 3 4 5 6 7 8 9 10 11 and the 12 right so this is the total the Thirteen size of the area and give any name suppose this I am using the TP so this is the array right and what is the size of DP size is the amount first one and these are the in the indices right index of the array but here we will consider these are the amount so this is the one amount two amount three amount for amount just you can consider it right starting time what you do you make the entry of zero as you explanation everything and make the entry any number more than the amount so suppose I want to achieve the 12 you can put the 13 in all the boxes and you can take any integer Max or anything right so now you have the coin so using the coin 2 can you make the amount of one it is not possible Right so we can only start from the two because if you use the amount to we cannot make the Eraser then that amount of coins so I will start with the two so to achieve the two so suppose you want to achieve the amount to I'm saying this is the amount so how many coins you want so of course you want the one coins so make the entry for the world how I beg it I will explain you again with the coins of two can you make the three rupees look we will drag that with the points of two can you make the 4 yes how many points you need two the same way you cannot make the five but we can you can make the six rupees or six amount with the help of the two piece coin if you have the three coins of the two rupees you can make the six the same way if you go here I need the Four Points sorry I need the five coins and I need the six coins so if you see the this area easy you can find out if you want to if you amount these four how many coins you want right Four Points so if you see in the given questions if we have to achieve the amount 12 so what is the minimum number is the six if you have given the coins too let me the same example if you have given the coins full then we can later we can Implement all together so suppose if you have given the coins 3 an amount is 12. starting this is 0 and again this is the 13 right so make all the 30. in the in this example also I forgot to inform one thing so suppose with the amount of the two points of the two for making the amount seven how many numbers I need it is showing 30 means for any amount if you getting the array value is the same initializing value then we can return the minus one because it is not possible so any amount suppose for the nine if you're getting 13 because I'm visualizing this array with a 13 so if you're getting the 13 you can return the minus 1 I need the minus one means it is not possible make the nine amount with the help of the two but if you want to do 10 you can return the 5 because with the 5 you can do that okay come back here so again with the help of the coins Theory I cannot make the one rupee amount I cannot make the two amount I can make the three amount right so for the three how many coins you need I need the one with the three rupees can you make the phone no can you make the file no can you make the six yes how many coins you need the same way 3 and same way you can four okay so if you we can make this kind of the arrangement through the code I can exhibit and here is answer is the four right with the help of the uh three coins total four I can achieve the 12 right the same way it is going that now if you see the point 4 when if I have the point four so suppose uh again let me say again if you have the full piece coin for the same amount right so I'm just using the same here so what if you do that I'm using the same array don't confuse here so starting 13 is there so with the help of the full rupees coin of course I cannot make the amount one cannot make the amount two cannot make the amount three yes I can make the amount for so it is the one I cannot make the amount five because I have the only four big coin all right a four Cent right I cannot make it if I could have the one and four I could able to make the five but in this example I have the only the four rupees coin so I cannot make the five six seven eight I can make the eight and I can make the 12th and here is the answer is the thing right now what I'm going to do that if you have the coins 2 3 4 then how you make this array right so what I will do with the first adjectives so first whatever we have done the individual I am going to combine it so take the first two rupees coin and update this array so we have already done that right with the two is one here how we can get it we know that right this is scanning for this the first is scanning with two rupees coins right now the second is scanning so what if you do the second this is very important thing what you can do of course the three piece coins I cannot make the one and the two I do start from here right so here you have to find out the two things one is that if this is the DP you check right now in this index what is the value and you have to compare this value with DP let me just give the extra answer then I will tell you what about the minimum of this put this value in DPI actually we have done the same thing for the two also but I didn't explain let me explain the three because it was not any confusion when use the first coin right so now start with that so where I will start of course from the 3 so right now I value is equal to 3. so when you check this I3 value right now is the 30 so this is the 13. and I minus coin I is the 3 and we are going to use the coin 3 so 3 minus 3 is equal to 0 that's why I have taken the to have one index 0 so this value is 0 this compute value is 0 and plus 1. so it is returning one so between 13 and 1 of course 1 is minimum so I will make it the one why they take the one because when you make the eye and the coin it is coming zero that one will add the value to represent the number of coins right again if we give you whenever you explain the when I is go to the different value so in this case I is the 3 coin is 3 that is zero here and plus 1 it is showing how many coins I need then you have to update so DP 3 is equal to 1 the minimum of these two so I make the one okay all right now I is equal to 4 now let me go for the DP full so dp4 value is right now two right now it's a 2. and 4 minus 3 is the one and dp1 is the 30 right so 13 plus 1 is the 40. so what is the minimum between 2 and the 14 of course 2 so dp4 we are not going to change anything so dv4 is the fourth dp4 is the three okay so 4 is equal to 2 now again here go I is equal to 5. so you go the 5 DB 5 dp5 is the 13 value and 5 minus 3 2 dp2 value is the one right and one plus two so what is the minimum is 2 so DP 5 is equal to 2. right so again if you do the same thing for the six right for the six what happen that I is come to six minus 3 dp3 value is the one and the one right so you can get the two so I will modify this with the three to two and of course for the six we need the two number of points of the three page each right the same way even if I can say y to here you can make the for the nine and you can make for the 12 right nine must be the 3 and 12 must be the 4 right so if we go forward that if d p is the same one so this is the four and dp4 is the two plus one is the 3 and 7 dp7 is a three so of course we are going to put the three value here right and go eight so eight minus 3 5 so what is the five value is the what is the eight value right now four and eight minus three five have is the two plus one is equal to 3 so 8 is equal to here three take the 9 so dp9 right now is value 13 here 9 minus 3 is the 6. and the sixth value is the two previous one is the three so of course history you can see because for the 9 we need only the three points again let me take for the uh 10 so here n is value is the five and here 10 minus one seven d seven is equal to 3 plus 1 is the four so what is the minimum between five and four so 10 is equal to become the 4. for the 11 take the 11 everyone is at 13 here 11 minus 3 8 dp8 is the 3 plus 1 4 so we can take the 4 and 12 right now is the six twelve minus 3 is the 9 value must be three plus one four so it is the four so this is the value of the update by the coins three now let me same thing with update with the points with the four so this time you are going to update with the four so of course for the four I cannot even make the amount one two three it will start from here right so I is equal to the 4 right so now if you see that DP four so what is the fourth value is the two and DT 4 and now we have the coin of four right so 4 minus 4 0 plus 1 of course zero is the zero so plus one so 2 and 1 is the minimum so this one is the one and of course this should be the one because you need the amount of the four how many coins you need only one the one coins of the four right so if you see now again for the five if you see D5 is equal to 2 D5 take the one dp1 is 13 plus 114 we cannot take the 4 2 is the lows so it is already the two is there this dp6 value is the two six minus 4 2 value is the one plus one two so you can take any one so dp6 is equal to 2. right now seven so suppose here take the seven d i seven is the 3 7 minus four three and dp3 is the one plus one two so we can take the two so those seven Vari we can take the two go for the eight if this is the I is equal to 8 so dp8 having is the 3 right now and 8 minus 4 what is the fourth value 1. it's 1 plus 2 1 2 so I can make the two of course because for the eight you need the two points right the same thing for the nine we have the three take the nine minus four so there is no any change for the I 10 so I can vary right now for I 10 minus 4 6 value is 2 plus 1 3 and 4 so I have to make the 3. now go for the I 11 here so this is the 11 I i1 is the fourth value everyone minus seven value is 2 plus 1 3 right 4 and 3 if you compare so 3 is the race so for this one you make the right take the final one if it is the 12 so I 12 is the 4 right and DP 12 minus 4 is the 8th it value is the two eight values the 2 plus 1 is equal to 3 so we can make the change and this is your final answer so just you have to compare the two things that what is the current value and what is the I minus coin why I am taking the I minus coin because I is showing you amount right and coin c is showing the denomination foreign and of course that amount you need so suppose amount is the eight and denomination is the four so you have to find out 8 minus 4 so you need the 8 minus 4 right because you have the already one rupees coin so that you can pick from previous or not so of course if you see the 8 minus 4 you have already here one so you have to only one so it make that two so this is the way you can do that and let me do the code is very easy just three four lines you have the four but let me explain so always your answer would be the last index and one more thing suppose somehow if you cannot change anything this value is still 13. you can do the practice so if you say uh you take the different amount or you can take the different amount 16 17 and you can see if this amount is not changing then it is the minus one because we cannot make it code is very easy you make one DP foreign and you feel it you take this DP with the amount plus one so all DP of value is equal to the 13 but DP is starting must be the zero then you take from the coins right these ones so it must be in the coins area so you can see why should we get one coin in this for you start I always start with the coins because if this is the two piece coin you have to start from two if this is the four piece coins we have to start from the four because with the four rupees of coins you cannot make the one two three right and then this will go the equal the amount because my target is to achieve the amount and here the main logic what I discuss here you have to take the math minimum between the DPI and DPI minus y plus 1 that is the whole code and then you have to return what you have to return that if you have to first check if DP last Index right you can see the amount is also things so DP amount if this is the equal amount first one means if this is the 13th in that case you will return minus 1 otherwise return what the number is here so that number is here I will explain the code also this is the whole code so only this much code is sufficient to minimize but what I will suggest you also take the different denomination for the coins also take the different amount and go five six times to match the array and find out how to cut that so it is easy for you to also understand and also go through the code and make the code in debugger mode and find out how the value has been changing to get the more better understanding for this question thank you very much let me see in the code so what I will do first and foremost make our DP and DP event would be the same amount plus one right so you have to uh taking the jio index first right and then make this if this complete away with the anything more than the amount you can use the index integer Max or anything so here this DP with anything more than amount right but keep the first index is equal to zero that is about the base logic right then we will foreign take all the coins one by one right and if this is the two coins so our index we start from the I index start from the two if this is a 0.5 I will start the my two if this is a 0.5 I will start the my two if this is a 0.5 I will start the my index of the five from five amount five or index five because if this is the five coins it will not make the amount one two three four right if we make the amount from the pipe itself so that's why in the second array I am taking I is equal to points I will start from the coins and of course I need all the amount foreign take the minimum of what is in the DPI right now or DP I minus coin and plus one so this is the main logic right I minus coin and then we can return if the as I discussed if the DT last index is the same amount what you appeared it is didn't change then that means with the given denomination we cannot make the amount right so then we have to return the minus one so you can check it if we turn if DP amount mean means DP amount takes the last box right if it is equal to the same and same value what we have initializing then that means I could not find out the amount so we turn the minus 1 otherwise what I have to return the same number right it will be our minimum number is in the last Index right so this is the complete code and this is only the basic logic here this one so let me run the code was there one again so it is working fine so if you see it is saying the amount element so suppose uh in our case right we have taken the if you can change the two three and four and amount was the 12 right so if you take the output should be the T as we discussed on the Whiteboard right because it will take all the four piece one and make it right so output is the TV but suppose if you want to make the 10 right so how you make the 10 with this denomination either you can two rupees coins for the five times so output should be the five but otherwise that four piece 4 rupees and two so minimum is the three number let me see whether 3 is coming or not to making the amount of the 10 with the denomination 2 3 4 right so you can see the output so it's working fine let me submit the code it must be uh accepted because I have already tested it so it is accepted right thank you very much uh please support to subscribe this Channel and share among your friends if any questions uh videos hesitate use the comment box I will try to give the answers of your new questions thank you
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
509 |
hello everyone hope you all are doing good and in today's video we are going to start a new series um that is the medium difficulty questions for QA we have already covered uh the basic one so if you haven't watched that whole series I strongly suggest you to go and watch that and let me like give you a recap of all the questions which we have covered in the basic QA so these are the like programs and in that like we have covered the Fibonacci one and again like we are covering the same in the medium difficulty one so like you can ask like why are we repeating the same question so the thing is that like here uh we have to find the time complexity of the Fibonacci one and we will try to improve one because like this is a very basic program so let me show you the program which we have written uh this is the concatenation this is the filmlocky one so through recursion we uh we have uh like we have covered this program and like it is working perfectly fine but if we like find the time complexity of this uh solution then let me open a new tab and like we will try to discuss the time complexity Okay so what is happening right now like the existing solution which we have is that let's say we are finding this like Fibonacci of five okay so as you all know like Fibonacci this is the Fibonacci series so uh like Fibonacci of 0 is 0 1 is 1 and the Fibonacci of two will be like let me write down the numbers 0 1 2 3 4 and 5 okay so uh the Fibonacci of two will be the addition of previous two numbers that is one now the what will be the Fibonacci of three that will be two Fibonacci of four that will be three and Fibonacci of five will be uh three plus two five similarly uh Fibonacci of six seven eight will be uh this is eight this is 13 and I guess this is 21 okay so this is the Fibonacci series and if anyone asks you like what is the Fibonacci of four then that is three okay so what we have done till now is that let's say we are finding the Fibonacci of four so what is happening the Fibonacci is the sum of previous two uh Fibonacci numbers so here we are calculating the Fibonacci of three and Fibonacci of two similarly we have to calculate the Fibonacci of two and Fibonacci of one okay in this like Fibonacci of one and Fibonacci of zero yeah previous two okay in this like we have to calculate a single uh of zero and in this again like one and zero okay and this is zero so what is happening right now is that if you see um closely that we are calculating the Fibonacci of two like two times okay like if we have already covered the Fibonacci if you already know the result of this one then why are we calculating again here so this is the thing which we have to improve and right now the space like the time complexity is uh if this is a number then we have to take like n so I guess this is Fibonacci of 2 n like this is the time complexity okay we have to improve it and let us uh try to solve this and this is also a lead code question so we will like solve it on lead code also okay so let us try to uh this was the existing one so if we have to find the Fibonacci of if I open it again if we have to find the Fibonacci of four so three should be the answer so let me write four um if I run this Nokia 4 is 3 that is absolutely correct okay and now this is the basic one let me make a new package this is the medium the packages start from small I guess I'm not that much sure the classes start from the capital letters so in this like I'll make a new Java class fib that is okay and now let us write the same code which we have written earlier and after that we will try to improve it so public static void main we have to find the Fibonacci of um let's say and a is equal to 5. okay we have to like let us copy paste the code that will be more beneficial um find Fibonacci okay here and if we write find Fibonacci and pass it my a okay that will return us this is returning as an INT so we have to store it uh in result okay and in the end we are printing the result Fibonacci is result okay so this is what we are doing earlier in the basic one and everything is correct till here let us select test it we have to find the Fibonacci of five so if I run this uh FIB Nokia 5 is 5 let us cross check that FIB Nokia 5 is 5 this is correct okay now what uh what we are doing right now like what how will improve is that we will take an hashmap and like try to store the value so if currently this Fibonacci of 2 is already calculated then we don't have to calculate it again okay how we are going to do it let's see that um let me take a hash map okay and new hash map the key and value are of both integer types so integer okay and we have to pass it here also so hashmap integer and what kind of this is of map um okay now let me write the code in a more readable format so what is happening that uh the FIB is changing in this so let us write it in N key so in key is equal to fib okay and here we have to find that if map dot contains key okay if like whatever we are uh whatever the Fibonacci number which we are finding if it is already contained in our hash map then we have to return what uh we have to return map dot get FIB okay and uh like this is a recursive call so we have to uh like do it uh this is a recursive call so we have to um call it again so here like let us write map and map so everything is uh good everything seems perfectly fine till here now let us try to run this code okay I hope like you are getting what I have done here that like we have introduced a hash map and uh there like it will check that this uh like whether this FIB gnocchi number so in that case like if 2 is already present inside the map then it will return the value and we don't have to calculate it again okay so let us run and see if we are getting 5 so this is 5 and uh now how will we check uh that whether this like this thing is like how do we see that exactly if it is an improved code or not guys what is happening here is that uh like previously it was taking a big O of uh like 2N and let us see what is the time complexity it is taking now so every like this is of n type and I think this is less than of 2N so we have like improved the time complexity and I hope this solution was beneficial for you and if you have liked this video just uh hit that like button it will surely help me to make more such videos in future um thank you guys
|
Fibonacci Number
|
inorder-successor-in-bst-ii
|
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given `n`, calculate `F(n)`.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1.
**Example 2:**
**Input:** n = 3
**Output:** 2
**Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2.
**Example 3:**
**Input:** n = 4
**Output:** 3
**Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3.
**Constraints:**
* `0 <= n <= 30`
| null |
Tree,Binary Search Tree,Binary Tree
|
Medium
|
285
|
1,656 |
hey guys pain here so today i'm going to talk about question d called 1656 it's called design orders stream so basically what's given it's two functions there's two class functions we need to implement so basically first one is called order string and it will given uh order so basically it's inserting certain solution and then secondly we'll implement the insert function and it takes in the id key and the following so it's kind of confusing so let me break it down for you let's look at the example so basically what this question is asking is the longest list that start at index of pointer return only as long as this stop at the index of pointer and if the pointer is not pointing to an element return empty list okay so this idea and what i meant so basically for example so we have index id key at three and we have a value of c and one at the keys one and a two b five e four d and this is output so i will show you how do we get this output so you have a picture here so basically we started here okay we'll take it slow so at the beginning you know i think that's three fc and but the point is always starting at one so pointer is not pointing to c so we return it no empty list let me break it down so for example if you have a like that all right this is the list one return right so the pointer is pointing at the first one the pointer all right and then for example here we have so here we have looks pretty much read first so put c here but since pointer is pointing at index one is between the empty list it's not going into that and secondly we have one eight okay so we now we have something a pointer and point will increment to the next position and then we'll return whatever here so all right so next one we'll put b at two so check okay if we have something in the pointer yeah we'll move pointed to the next one or something i pointed i move it to the next one so we'll return b is right and then next one we'll add 5b right here the pointer f4 so lastly we're at 4d so point at something increment point something so we return b all right so this is what the dots process and then let me try to implement this for you so first we will point it so we'll set pointed to zero because index supply zero and result will initialize it taking the length of n because that's how they determine the company left the left of the input so here we will say operator list this is the reason why so call this so and then we need to put in every time when you're putting the value in the correct position so and since this is one index and if you enter the array is zero index so we'll just land this one at a key and then put in the body all right so and then the log condition basically is while the pointer still less than the left of the result and what else so end is not known you saw our point first no we'll add the body and then return to the list so yeah this should be it you know depends on the length of the islands so you take open you just want to light the length and pointer will basically increment when point will increment when d is not known so let's see items end with a thousand so it's a basically a constant you know it's basically a constant so because and go up to a thousand so the most is a thousand and each end course will make an answer so you'll basically we will make sure to go to all right thank you guys if this video helps you share to your freshman or who haven't studied computer science and like subscribe if this video helped you i'm gonna keep making this video after make a pain facebook google oh glory to god thank you
|
Design an Ordered Stream
|
count-good-triplets
|
There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each insertion. The concatenation of all the **chunks** should result in a list of the sorted values.
Implement the `OrderedStream` class:
* `OrderedStream(int n)` Constructs the stream to take `n` values.
* `String[] insert(int idKey, String value)` Inserts the pair `(idKey, value)` into the stream, then returns the **largest possible chunk** of currently inserted values that appear next in the order.
**Example:**
**Input**
\[ "OrderedStream ", "insert ", "insert ", "insert ", "insert ", "insert "\]
\[\[5\], \[3, "ccccc "\], \[1, "aaaaa "\], \[2, "bbbbb "\], \[5, "eeeee "\], \[4, "ddddd "\]\]
**Output**
\[null, \[\], \[ "aaaaa "\], \[ "bbbbb ", "ccccc "\], \[\], \[ "ddddd ", "eeeee "\]\]
**Explanation**
// Note that the values ordered by ID is \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc "); // Inserts (3, "ccccc "), returns \[\].
os.insert(1, "aaaaa "); // Inserts (1, "aaaaa "), returns \[ "aaaaa "\].
os.insert(2, "bbbbb "); // Inserts (2, "bbbbb "), returns \[ "bbbbb ", "ccccc "\].
os.insert(5, "eeeee "); // Inserts (5, "eeeee "), returns \[\].
os.insert(4, "ddddd "); // Inserts (4, "ddddd "), returns \[ "ddddd ", "eeeee "\].
// Concatentating all the chunks returned:
// \[\] + \[ "aaaaa "\] + \[ "bbbbb ", "ccccc "\] + \[\] + \[ "ddddd ", "eeeee "\] = \[ "aaaaa ", "bbbbb ", "ccccc ", "ddddd ", "eeeee "\]
// The resulting order is the same as the order above.
**Constraints:**
* `1 <= n <= 1000`
* `1 <= id <= n`
* `value.length == 5`
* `value` consists only of lowercase letters.
* Each call to `insert` will have a unique `id.`
* Exactly `n` calls will be made to `insert`.
|
Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good.
|
Array,Enumeration
|
Easy
|
2122
|
338 |
what's up everyone today we're going to go over lead code 338 counting bits first we'll go over the input and the output then we'll look at the code and the approach side by side and finally we'll go over the complexities i'm going to go over the dp approach because the simple approach is pretty straightforward so the input is going to be an integer and the output needs to be an integer array so we have 5 and the output is going to be 0 1 2. all they're asking is if we go from 0 to the input n what are the number of bits in each of the number for binary representation count those bits and put them in an array and return that array so straightforward these are the binary representations of each of these numbers and i put the actual count of those bits and that's going to be the output this is one of those problems where it's much better to look at the code next to the diagram because it really helps it click so first we have our numbers so 0 to 9 let's say our n is 9 and we have to get all the bits for that right these are the corresponding binary representations so 1 0. so each of them i've written out the count what you'll notice is for the powers of 2 the set bits is 1 and i've highlighted them in red so 8 4 2 1 all have one as a set bit and in dynamic programming we usually have a base case or something like that so in our problem zero is going to be the base case so for zero this is a zero and the count is also going to be zero another thing you'll notice is that these powers of two so one two four and eight have these blocks sort of attached to them so this b is going to be for let's say block is of size one this is of size two this is of size four this would be of size eight if we kept going that's how we initialize this b right here b is equal to one because it's two power zero next we also have this i pointer that's going to go from zero to b minus one so zero to zero and one for this block going up to two zero one two three for this block going up to four and zero one two all the way to seven for this block going up to eight that's what this i pointer is we initialized our dp array as well and our while loop is going to run until n because that's all we care about this b is never going to be larger than n we don't care about numbers after that next we know that we have an inner while loop where i is less than b you'll note that this i pointer is always less than the value of that particular block so that's where i minus b comes from and of course i plus b should never be greater than n what do i mean by that well i zero plus eight is going to be eight i one plus 8 is going to be 9. so we never want to go out of bounds using our n so that's where this comes in here's the recursion not recursion but reusing of the dp problem dp of i plus b is going to be dp of i plus 1. so these two powers 1 2 4 and 8 are reusing this base case so dp of i plus b we're always going to start this while loop with a power of two and it's going to reuse the base case so zero plus one this is zero plus one and zero plus one when we begin our block then we reuse i as a sort of pointer variable which goes within the bounds of the block b so i goes from zero to three and that's how we reuse it dp of 3 plus 4 7 depends on dp of 2 plus 4 depends on 1 plus 4 depends on 0 plus 4. that's how we do it for this dp and every time we increment the i pointer once we're done with the inner while loop we reset i is equal to zero because it's a temporary pointer for each block of b then we just double our b block and ultimately we fill up our dp table and we can return it the time and space complexity are both of n because well we initialize the dp array of size n and we're going to visit every single number in that range n so that's how you solve leak code 338 if you like the video please thumbs up and if you want to see more don't forget to subscribe
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
231 |
hey this is Topher with the lonely Dash and today we're going over lead code question 231 power of two which states given an integer n return true if it's a power of two otherwise return false if an integer N is a power of two there exists an integer X such that n is equal to 2 to the X power okay so what does this really mean it just means they're going to give us a number which will be an integer and we need to figure out if 2 to the X power could possibly equal n right and this x has to be an integer and our n also has to be an integer um and so normally what I'll do is go through these questions and say okay let's read the question let's understand it then look at the constraints but for our purposes today I'm going to look at the constraints right away which is simply stating that n or the number that they're going to give us is going to be between -2 to the 31st power and 2 to between -2 to the 31st power and 2 to between -2 to the 31st power and 2 to the 31 power minus1 so that's just really important to know right off the bat uh so that we know what we're doing so here are the examples that code gave us uh with an input where n equals 1 we know that's true because 2 to the zero with power is 1 uh if n was 16 we would also know that's true because 2 to the 4th power equals 16 but there is no power to two a power of two that can give us three so that's false so these are the things that we need to know in order to solve this problem properly we need to know and that we do know that n is an integer and how do we know that well it told us so given an integer n so n must be an integer and that means that the power that we're looking for or the x value must be between 0o and 30 right because if it's a negative number then it's not going to be an integer because it's going to be part of one so it could be like .25 or 66 it doesn't really matter like .25 or 66 it doesn't really matter like .25 or 66 it doesn't really matter so we know that the value we're looking for this x can't be negative right and we know how do we know that it's going to be between 0 and 30 because 2 to the 31st power is going to be greater than our constraint okay so if we know that it's going to be a Power of Two between 0 and 30 there's a couple of different ways that we can solve this and for me and for today we're going to solve it using binary search algorithm it's one of my favorites if you've not watched our video on the binary search algorithm please do that it is Elite code onto itself but for today we're just going to run through two examples and it kind of gives you an idea of what we're going to be doing right so we're going to start with our numbers 0o to 30 and we're going to start our left pointer over on the left side at zero our right pointer over on the right side at 30 and all we're going to be doing is trying to find the power here that is going to equal to n so here we'll just say that n is 26144 and for argument sake we're going to know that is 4 to the 9th power okay and the question is basically saying hey we've given you this number is this is it possible to have any number in here that is to a power oh this is four um sorry two this should be two and just for my argument sake I'm going to make sure that's actually the case so where's my calculator here's my calculator and we should always do this just to make sure so 2 to the 9th power is 512 okay so I must have been doing this uh 512 and I guess we better do 2 the 29th power over here just to make sure as well make sure that we're doing it right uh okay 2 to the 29th power is actually okay so we did this right sorry about that um okay so we know that n is 512 which to us we know is 2 to 9th but how can we figure that out well binary search if our left pointer is at zero our right pointer is at 30 the middle is left plus right divided by two which we know is 15 and we're going to ask ourselves hey is 2 to the 15th power is it equal to n if it is then we are done and we can just say true but if it's not we're going to ask ourselves okay is 2 to the 15th power greater or less than n and in this case we know that it's greater because 2 to the 15th is greater than 2 to the 9th so we're just going to take our right pointer and we're going to stick it one position left of our midp pointer and we're going to do this all over again we're going to take left pointer right pointer add them together divide by two and Bam we know our Middle Point is seven and we're going to ask ourselves hey is 2 7th power equal to n it's not is it Greater or is it less than well we know that 2 7th is less than 2 to the 9th which means it's less than n so we're going to take our left pointer and we're going to move it just to the position right of our middle position and we're going to keep doing this process over and over again so let's see 14 + 8 uh what is again so let's see 14 + 8 uh what is again so let's see 14 + 8 uh what is that is 22 / 2 is 11 so we're going to stick our 22 / 2 is 11 so we're going to stick our 22 / 2 is 11 so we're going to stick our midpoint there ask our question hey is this the answer it's not okay we know it's greaters who our right pointer moves over and we're going to do it all over again the midpoint between our left and right pointer of course is this nine and the first question we ask is hey is 2 the 9th equal to n and it is bam we're done so we know that the answer to this one is of course true that's important done true you're going to turn green hooray so that's how that's going to work same thing if we wanted to do it again with a much bigger number it's the same process over and over again so we're going to do 2 to the 29th power well we're starting our left and right pointers our midp pointer starts at 15 because that's the middle we're going to ask is this the answer it's not it's less than our answer so our left pointer gets to move over one position and we do the calculation process again so 30 + uh 16 is 46 / 2 is 23 so there's so 30 + uh 16 is 46 / 2 is 23 so there's so 30 + uh 16 is 46 / 2 is 23 so there's our midp pointer is it greater or less than or the answer uh we know that it's less than so our left pointer moves over again and this process is going to keep going and going until bam we find the answer now this is going to end up being one of those Loop statements that is as long as our left pointer is not crossing our right pointer because it's possible that our left pointer and our midp pointer and our right pointer are all on the same spot which means it's either the answer or it's not and then our left pointer will cross our right pointer and we've reached the end of the loop and if that ever happens if our left pointer crosses our right pointer that means that the answer will end up being false but in both of these cases we know it's true so this is all we're going to be doing to solve this question today we're going to we know based on the question that n is going to be an integer which means our power is going to have to be a positive integer and what else did we need to know oh yes the power must be between 0 and 30 because our constraint has told us so I don't think in this case that there's any edge cases to consider so we're actually going to skip that and go straight to our pseudo code ahha gotcha no there's really nothing to consider for edge cases all right let's move on okay so for our pseudo code the very first thing that we need to identify or determine is uh if n the number that's given to us is less than zero then what do we know well we know that it's false so that we can just then return false right because there is going to be no power of two that will come out to having n being negative okay so that's first and foremost once we've gotten that out of the way we can kind of start with our binary search algorithm here so we need to create left and right pointers at 0 and 30 um right and because that and don't forget about the 0 and 30 and how we got to the 0 and 30 we've got those from the constraints of the actual question once we have done that then we can create our Loop right so we're going to create um a while loop that iterates um iterates until the left pointer crosses the right pointer okay so that's just going to happen over and over again until this situation happens during that time we have got a couple of things that we need to do the first is identify the midpoint right between the left and right pointers all right that's that was our M our purple m in our earlier part of the question we also need to identify um the value of the current uh Power um so we're going to use just for argument sake we're going to make it a valuable use X as a variable okay so this is just saying X is going to equal two to the midpoint and it's just going to be sitting there and holding that value and then while we're doing that we get our if statements so if n equals our value so two to the midpoint power what do we get to do well we get to return true because well we found it congratulations we're good um if not uh in that case if n is greater than x what do we move the left pointer one position to the right of the midpoint all right and otherwise and I'm going to capitalize that if cuz it's going to bother me uh if n is less than x then we need to move the right pointer one position to the left of the midpoint all right and that's just going to keep going and going until either uh our midpoint value until our Mido value points to the right power or it basically ends and if it does end if the loop completes without uh finding a match which means we didn't find any power of two that matches our n if that happens well we just return false uh because it's not a power of two at least not within our constraints and that's it that's all of the pseudo code we need and if you are a person who recognizes basic basically this algorithm you know it's binary search so let's take it move on and get coding okay here we are and I'm just going to copy and paste our pseudo code into the python work area of the website and all we're going to do is start off line by line so the first thing is if n is less than zero meaning it's negative what do we're going to return false okay so that takes care of this lovely line here done now we got to start our uh left and right pointers so let's come down here and start our left pointer at zero and our right pointer starting at 30 and then we can kind of start getting through we just make this a little bit oh look at all those successful things uh little bit more into our algorithm so we need our Loop so while our left pointer is less than or equal to our right pointer what are we going to do well we're going to first identify a midpoint in between so our midpoint is going to equal our left pointer plus our right pointer and take all of that and we're going to divide it by two now remember to use your double divide because that always needs to be an integer because um otherwise you're going to have a non- integer as the going to have a non- integer as the going to have a non- integer as the exponent and we don't want that uh and then we're also going to identify the value of our current P power so we're going to use x just for argument sake and X is going to be two to the midpoint power right and we're just using this as comparison because we're going to keep comparing that to n so if n is equal to X well then we know that we have found the power that works for the question so we can return true if we haven't so else if n is greater than x what do we need to do and I'm just going to kind of keep looking down here and moving along if n is greater than x we need to move our left pointer so our left pointer needs to move from our midpoint plus one position otherwise we know that n is less than x so we need to move our right pointer to our midpoint minus one position and that's all of the binary search algorithm that we are doing we just need to basically say hey if we get to the end of our while loop and nothing happens what do we need to do return false and that's it that's following along so if all we did is to make a determination that n has to be zero or greater we created our two points uh our two points at 0 and 30 and we kept evaluating what was in between them and whether the two to the power of that midpoint was equal to greater than or less than the number we were provided and eventually we're either going to find out that it is a power of two or that it's not and we can return false so let's hit run I'm going to make this even a little bit smaller here hit run make sure I didn't make any mistakes so far so good going to hit submit fingers crossed and there we are so in this case in the power of two I find it's really good on memory using this binary search pattern uh 96.4% and pretty darn good on runtime 96.4% and pretty darn good on runtime 96.4% and pretty darn good on runtime 70% faster than most and you're going to 70% faster than most and you're going to 70% faster than most and you're going to if you're Elite coder and you go in and you start looking at all the Sol Solutions you're going to find a lot of oneline solutions and a lot of mathematical ways of solving this question but I found the fastest and the most or the least memory intensive has really been just to use the good oldfashioned binary search algorithm and uh if I was going to have to implement this somewhere this is exactly how I would Implement power of two number 231 of our lead code questions a
|
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
|
976 |
day 12th of October lead Cod Challenge the problem that we have in today is largest perameter triangle guys apologies there is renovation going on at my place and I'm not able to post videos right now but so far we have solved all the questions that came for the October monthly challenge those are already available on coding decoded so guys please check them out don't think that we are not solving or we are turning inconsistent now it's time to look at the question the problem that we have is largest parameter triangle here in this question you given an array of numbers and you need to identify the largest parameter of a triangle that has nonzero area that could be formed using these three using the numbers present in the array for example here they have provided us with few examples I'll be walking you through these examples as well as the algorithm behind it by the presentation so let's quickly hop onto it the question says you given an AR has slightly taken a different or a longer example so that you get a good hold of the concept what do we need to do the first property that we need to identify is that using three numbers out of this array we need to form a triangle and for us to form a triangle we learned in seventh and e8th standard that the three the sum of two sides of a triangle should be greater than the third side so let's assume we have a triangle with sides L1 L3 and L2 wherein the relation between these three side is somewhat like this L3 has the largest value and L has the least value and we can conclude that if some of the lower two sides is greater than L3 then we can easily form a triangle out of it also the rest of the two equations wherein L2 plus L3 is greater than L1 these will automatically be true by virtue of L3 being the largest L1 being the smallest and L2 being the middle one similarly if this condition is met we don't need to check the rest of the two conditions pretty simple and straightforward now let's talk about the array that is given to us so in the first step what I'm going to do I'm going to sort this array up and once I sorted this array I'll Traverse in the reverse Direction starting from over here I'll select three elements and I'll select the least two elements out of these three elements and that would be nine and 12 so let's check whether this fulfills our equation or not 9 + 12 fulfills our equation or not 9 + 12 fulfills our equation or not 9 + 12 gives you 21 is 21 greater than 22 no it's not that means you can't form a triangle using these three numbers let's move a step back now this time my window size becomes this and let's again check whether the sum of least two elements out of in this window 8 + 9 gives you 17 out of in this window 8 + 9 gives you 17 out of in this window 8 + 9 gives you 17 is 17 greater than 12 the answer is yes so that simply signifies that using these three numbers we will form a triangle and we will the process there and then itself why because in the question it is specified we need to identify the largest parameter triangle that could be formed all the values towards the left would be of lower value therefore we will ignore this we will Avo the process there and then itself and let's return the parameter sum of these three sides 8 + 9 + 12 that would these three sides 8 + 9 + 12 that would these three sides 8 + 9 + 12 that would be 29 and this becomes our answer the time complexity of this approach is order of n log n to conclude it up fully let's quickly walk through the coding section in the we first go we sort the array up and we sort it in increasing order then we move in the reverse Direction starting from the largest element towards the least element and with each iteration we extract L3 L2 and L1 and then we apply the same formula that I talked in the presentation L1 + that I talked in the presentation L1 + that I talked in the presentation L1 + L2 is greater than L3 if that is the case we abort the process there and then itself and we return L1 plus L2 plus L3 if this condition is never met we simply return zero over there the time complexity of this approach is analog and the space complexity of this approach is constant time also if you're looking out for Solutions in other languages then the subscribers of coding decoded regularly post them on coding decoded GitHub repo and you can see that all the solutions starting from August 20120 are being listed over here month-wise so let's go to October 2022 month-wise so let's go to October 2022 month-wise so let's go to October 2022 you will find Solutions in C++ Java and you will find Solutions in C++ Java and you will find Solutions in C++ Java and python the subscribers of coding decoded regularly post Solutions and by this they able to achieve great level of consistency so if you are also aspiring for it then this is a right place for you go ahead and create the pull request I'll review those pill request and I'll merge it into a master this would be a great contribution to the open source community and for all those who solve daily lead code problems with this let's wrap up today's session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel your subscription truly means a lot to me and I'll see you tomorrow with another fresh question but till then goodbye
|
Largest Perimeter Triangle
|
minimum-area-rectangle
|
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`.
**Example 1:**
**Input:** nums = \[2,1,2\]
**Output:** 5
**Explanation:** You can form a triangle with three side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106`
| null |
Array,Hash Table,Math,Geometry,Sorting
|
Medium
| null |
5 |
to find the longest palindrome substring alright so the interviewer tells you well given a string find the longest substring of the string that's a palindrome what would you ask the interviewer asks you this what would your first questions do the interviewer be alright some great questions there our special characters or commas to be considered or ignored that's a very good question so let's say the interviewer says you don't have to worry about it but that's something that you might have to handle when even you when you're dealing with palindromes you guys know what a palindrome is right it's basically a string which treats the same both ways typically people ignore commas or special characters because it's kind of like a part of the language but it doesn't affect the palindrome Ness of a string alright so you have this class of palindromes like Madinah madam right so there is a comma after madam and if you consider the comma you don't have a lot of palindromes which makes a lot of sense in English language so typically ignore special characters but let's say you don't wanna worry about that let's say you're given a string without any special character or solicit interviewer kind of simplifies that it says it's just alphanumeric characters no special characters can a palindrome not exist well that's a possibility yes let's say the panelled room cannot exist let's say you have a string that a palindrome does not exist however I should say that there are different ways of handling this if a string has no sub strings with palindromes that exists well a single character string is a palindrome right two character strings can be palindromes if they repeat but at the very least just take one character and say this is this the parent was the longest palindrome we can find you have a whole lot of those and then there's also a related question what if you have two strings which are palindrome sub strings but they happen to be of the same length well the interviewer can say well written any one of those all right these are great questions all right I hope some of you guys got this is one of those things where you have like the brute force approach where he can just go like I don't care about time complexity all I want is to find the answer and you just loop and loop you can't find the answer that way but what you're looking at is what's the most efficient way to find the answer and that's where the fun is right that's where the complexity of this problem lies so this is not something that you can do that like oh you cannot just do one scan and try and solve it I think you cannot do it in off n square as well mercy will work around this but then this is a fairly intensive operation but then the challenge is to see how fast you can make you can possibly make it but the chance with the constraints that you have all right let's think about this you guys know how to find if a given string is a palindrome or not right it's given a string how do you find out if it's a palindrome or not well that's actually hopefully fairly simple so what you need to do is I mean it is this guy here let's say this is your string ABCDE F II what you need to do is have a pointer at the start have a pointer at the end right compare these two characters if they match move this pointer here of this pointer here compare these two characters if they match both this year so keep doing this have these pointers approach one another until they meet in the middle they hopefully meet in the middle in which case you say okay this whole thing is a palindrome because I've started from both ends I've kind of validated both sides and at each position they will match right this will work but the problem is for something like this you need to know what the start point is and what the end point is if you're saying okay given a string and say check if this is a palindrome you know what the start point you know what the end point is and you can close this way however in this case it's a little different you have to seem any of the substring any of the hundreds of sub possible sub strings for this string happens to be a palindrome what's the brute force way the brute force ways to say okay I'm gonna check for every start I'm gonna check for every end I'm going to do this thing but I'm looking through and then checking each character one by one and then at any point of time I meet in the middle I'm gonna keep track of how many of those characters I add compare which is basically I'm going to get the length of that palindrome substring but I keep track of that somewhere and say okay I found a palindrome of size X starting at position n right and then I'm gonna keep going so I'm gonna do this for every possible start in every possible line okay how do I do that base Vidia nested loop right for I equals 0 to n J equals 0 to n that n is the size of the string that's the can work that can possibly work but then you're basically looping you're having a nested loop which is off n square and for each iteration of that nested loop we are basically comparing the size which is another loop which compares the individual characters so this is not efficient is that a better way here's an alternative so but before getting into the palindrome substring problem let's look back at checking if a given string is a palindrome right I'm gonna give you an alternative way to check if a given string is a palindrome and you will soon see how that applies to checking if the if there are sub strings which are palindromes all right let me show you so let's say instead of starting over here right instead of starting from the beginning in the end let's say this is my string a b c d CB e alright so i want to check if this given string is a palindrome or not instead of starting from here and here right I'm not gonna do that what I'm gonna do instead this start from the middle all right I'm gonna start from the middle and I'm going to expand this way then I'm gonna expand on both sides I'm going to check if this character is equal to this character okay if yes I'm gonna move on check this character is equal to this character if yes I'm gonna move on and then if I have the beginning in the end but then I know that this string is a palindrome it's basically the same thing what I'm doing is essentially the same concept but instead of having just start and end and looping in words I'm gonna start from the middle and loop outwards alright does this work technically this will work but there is a small problem here there was a small problem what if there isn't the middle like the example that I showed you here this one has a middle which is deep this is the guy in the middle right what if I have another string let's say it's like this a b c b a well this is a palindrome well now can you find can you use this alternative approach this starting from the middle and going outside can you apply this approach to finding if the string is a palindrome or not you technically can but what you need to do is detect that okay this is the middle happens to be two characters now you have to check if the two character middle is the same and then if that's the same go further so you basically need to have this if condition to check okay is the number of characters in my string odd or even if it's odd you have a middle you start from there any expand if it's even you take the middle two characters check if they're equal and then expand right so this is setting aside the problem if we try to solve now setting that aside this is another legitimate way of checking if a given string is a palindrome or not agree that'll work we might ask me well Kaushik then what's the point of doing this because you have to have this additional complexity if you're starting from start and end it's simple right you don't have to worry about whether it's even or odd you can handle that case when you meet in the middle but if you're doing this if you have trying to start from the middle and going outside you have to handle this extra use case why do we need this well here's why we need this is useful in our particular problem that we're trying to solve the maximum palindrome substring right here's how it helps there's my string now if I were to find out what are all the possible combinations of sub strings that I need to check for palindrome we said if you're going with the start and end approach you have a nested loop right and let me get this straight first of all I have to clarify you have to check each individual substring for a palindrome right there's no other way around there's no magical way of saying okay now I'm gonna do this little trick here so that I don't have to check everything you kind of have to check everything so the question is how we can optimize the everything part all right so let's look at this if you were to look at the start and the end approach right so let's say your URL hürmüz check palindrome and it takes in parameters your string start and then end okay now how do you identify all the sub strings well you're gonna have to do a pulse 0 to length J equals 0 to length maybe you can optimize the starting point of check here a little bit but then the fact remains that you're gonna have to do all these loops and for each loop you need to call check palindrome the string hi Jay alright this is necessary however let's say able to use this other approach this alternative approach which is check palindrome where I'm starting from the middle take the string and then the midpoint now if I were to use this to this method to check if the string is a palindrome one and how many loops do I need I see this I just need one loop because I'm just passing in the midpoint there so what I'm doing is instead of doing a start and a man and then checking of each is a palindrome I'm saying I'm gonna do one pass of the string and see for each character if it happens to be the middle of a possible palindrome alright it's a slight shift in your thinking but imagine how much it saves here you're basically saving an entire loop by having that shift in thinking you're saying I'm gonna do one pass of the string each character I'm gonna expand till I find two mismatched characters and like okay I found some palindrome and you do that for each character and there you go you have a possible solution for the maximum palindrome substrate here's what the code is gonna look like okay so let's say I have a class called solution I don't usually put a class here because but for this particular thing I'm gonna have a couple of member variables and I'll tell you why in a bit but let's say I have a class and this is my strength is my solution method the longest palindrome method which takes in a string and it returns back the longest palindrome all right first thing I'm going to do is get the length of the string and what is the minimum length of the string that I need to have in order to do all this business right boundary check there's the first thing you ask your interviewer do all the boundary checks and say okay what's your behave what's the expected behavior so in this case the boundary check is a string an empty string very much case you probably do just one order down the string right it's a string of one character in which case what's the longest palindrome we can get out of that it's that single characters string which is the entire string itself right so you basically need to check if your string is of length 0 or 1 then just return the string you don't have to do any of the stuff so that's gonna be mine if block here I'm gonna put enough block there and says if it's less than to just return right now do the actual stuff what I'm gonna do is I'm gonna loop through the string character by character and I'm gonna check if each individual character is a possible center of a possible palindrome substring and if it is no matter how long the palindrome is I'm gonna keep track of that length I'm gonna keep track of that starting position and then at the end I'm gonna say okay what's the biggest one if I find a bigger one I'm gonna put it to that same variable and then the end whatever that variable holds is the longest common substring right so what I'm gonna do is let's start from zero I'm gonna go until string 1-1 because of zero index start string 1-1 because of zero index start string 1-1 because of zero index start plus I'm going to get the possibility of that particular value start being the center of a palindrome so imagine I create this method called expand range alright so this is what this is gonna do like check palindrome was the method that I wrote in the notes there but I've called it expanded you call it whatever you want obviously so what I'm gonna do here is pass in two arguments I know there's three there but bear with me pass in two arguments one is a string the other is the midpoint then it returns back the longest palindrome that it can get right however this is not gonna be enough you remember that the midpoint check for a palindrome like starting from the center and expanding up you have another use case to think about which is what if the length of the string is even in which case you don't have one midpoint you have two characters start in an end all right so that's the reason right what I'm gonna do is I'm gonna call the same expand range method with the start and start plus one all right so what expand range does is it doesn't take one midpoint it basically takes two all the time but if the number of characters are odd the range is going to be the same character right so that because there is a midpoint it's going to be a midpoint comma mcfine but then if the number of characters are even it's gonna be those two characters which are which form the midpoint which is what I mean thinking ascending here if I start and start plus 1 they may not be the midpoint but then again we are just trying to see if okay are these two characters possibly a midpoint artha possible palindrome so you have to check for each and every letter each and every alphabet position in that string all right so how am I gonna do this let's say I write this method expand range which takes in a string takes in the beginning it takes in an end right takes in two characters and then it's gonna expand till it finds the largest possible palindrome now I'm gonna create two member variables here because what I want expand range to return is two values I wanted to return the maximum length and I also wanted to return the position where it found the starting of the palindrome right I need to start because I need to do the substring I need to somehow calculate the substring from the string and then return back because that's what the longest palindrome method needs to return it means to actually return the substring itself the biggest palindromes itself so I'm gonna keep track of two men the variables and then the expanded range all its gonna do is gonna write to those member variables and then when they're done I basically do a substring off the result start and then the result start plus the result left alright is this clear so far and of course the reason I do this is because the Java API for substring is basically the start in the end right you need to return the start index and the end index so what I'm doing here is the result start and the result start plus the result in the result length why am I not storing the result end why am i storing the result length I need the results length anyway because we are looking at the maximum palindrome so I need to keep track of the length anyway so I'm keeping track of the length and then I'm doing start plus length all right so as long as expand range does its job right given a string and given a Centerpoint which is two characters it expands and then writes to result start and result length as long as it finds a palindrome which is bigger than this as long as that's expand range job as long as that's doing its job this main method the important method which is the longest palindrome method there's gonna do its job and it's going to return the longest palindrome substring all right so we have delegated that expanding range to the expander inch method hopefully this is clear so far now let's look at the expand range method and see what it does what does it have to do it has to check if the character at the beginning is equal to the character at the end and while it is that while it is true keep going so that's inside of a loop right so vile character at beginning is equal to character at the end I'm gonna do begin minus n plus but then of course I also have the bounds check so while the gain is greater than zero you don't want to keep doing this beginners equal to 0 or less than 0 and at the same time you don't want to increase end if n has reached string length right so while the begin is greater than or equal to 0 and n is less than the length of the string and these two characters match I'm gonna keep expanding the range right so we can minus n plus you're checking if that thing that was sent is a middle of a palindrome or at least as big a padded room as you can find once you exit the while loop it means that it's found a palindrome or it just came up right at the beginning whatever it is right it's like the biggest palindrome we can find that thing is the center now I'm gonna check if the result lent the previous pattern room that I've found if that's smaller than what I've found over here so what if what have I found it's n - begin - if what have I found it's n - begin - if what have I found it's n - begin - one because of zero index right so I'm gonna say n - begin - one that's the gonna say n - begin - one that's the gonna say n - begin - one that's the length of the palindrome of found is it greater than what I found before if it's greater then I'm gonna save it to the class member variables when I say result started as begin plus one because I've done a - - now I need to do a plus I've done a - - now I need to do a plus I've done a - - now I need to do a plus one to get back to the start of the actual palindrome a result length is n - actual palindrome a result length is n - actual palindrome a result length is n - begin - one because of the zero index of begin - one because of the zero index of begin - one because of the zero index of arrays in Java so I'm gonna get that length and then I'm gonna save it to the member variable off this class all right so there's gonna keep happening I'm gonna call expand range twice for each character and then I'm gonna check if that's the center of the palindrome and then we'll find the biggest one that we can find and then the longest palindrome method is returning that as a substring all right so is there a solution again you can of course do the other approach which is basically having start and end and looping through the work for the most part but you are definitely gonna get bonus points if you cannot explain your rationale and say this is why I'm doing this I'm gonna start from the center and move outwards because I get to save on that starting and you have two variables so you need two loops Center you have just one variable so you just need one loop to do that for each character questions
|
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
|
287 |
Hello Guys Welcome Back Door And This Video Will Find Duplicate Number Indemnity Alarm Swift Code 25th June Challenge 16 Personal Problem Veer Vs Boys At Least One Number Only One Number One This Is The Very Important Not Give The First You Must Not Modified Cars Only Be used only on Twitter subscribe liked The Video then subscribe to the Page So more element will be a knowledge plus one president Anil Hai basically five elements and chronic from element value 120 subscribe element 2012 interside elementary subscribing element from 2nd class ninth straight only one Elements subscribe to the Page if you liked The Video then subscribe to the Page and have already mentioned OK Is Dahej V Vivah Sudhir Who Will Win You To The Amazing Values From This Values From This Values From This Point All Elements In The 2nd 0202 subscribe and subscribe Kare Andarche To Solve This Problem That Person Solution And You May Not Be Knowing December Singh Very Simple subscribe and subscribe the Channel Element Asteroid Already Number Positive So Let's Start From This Point Two Minus One Will Be Replaced - - - - - Has Actually E Will Be Taking Salute Value Of Index And Evil Spirits Of The Dead Of - 151 - Subscribe Now To Dead Of - 151 - Subscribe Now To Dead Of - 151 - Subscribe Now To Receive New Updates Negative This Has Already Subscribe 40 Thursday Will Only Work For All Elements Of Positive Subscribe So That The Solution Is Under Members of Solution Is Not At All Intuitive This Is Best Doctor In Cryptography Presentation Swadeshi Basically A Five Step Process Will Be Showing You All The Steps 151 Please Watch You Sleep Will Be Making Us Of Property Which Will Win In 2002 Property In To-Do List And Subscribe Property In To-Do List And Subscribe Property In To-Do List And Subscribe Now To You Will Always Avoid 90 Will Not Subscribe Video To Tenth Doing S2 Value Then Ok Novel Restore This Intake Poisoning Value To So This Point To 99 Subscribe Sauveer One Will Be Having No One Will Dare Attack You When You Will Not Going To Develop Not Just Will Not Listening This Will Not Already Subscribe Quote Desh Lado Thisis Representation Narcissus Elements of Repeating This Representation Will Always Be Having Cycle Latest This Point To Solve 102 Elements Of Obscuritism 100 To 120 235 12345 Veervansh 2nd Will Sleep this Elements for the last three four one two three and this is to episode one and converters enter into graphical representation and have already shown use this is the graphical representation handed over to elements of twelve 12345 switch setting off it 0151 value 2333 loot no Know what is the year will go to you in 110 index-2013 Sudesh will be in 110 index-2013 Sudesh will be in 110 index-2013 Sudesh will be removed and state 22this note three lag increase cycle even if you remove this and flu se 499 self rule for this point Say In Anywhere You Can Dare I Will Always Be Like This Point To Point Subscribe Element Festival 1000 Newly Appointed Nurses Four Can Never Come Back To The Way Saw What They Are Doing This And 109 Thers Center * Graphical representation of the Center * Graphical representation of the Center * Graphical representation of the audio New In This Will B and Customer no this point element will always be contained in the cycle of having the element subscribing element will always be in the same way as later to remove the subscribe to the Page if you liked The Video then subscribe to the Page The Index Point Will Have Any Three From Where You Will Move To Interest Rate Will Have Valid To Inform Every Month To Develop Subscribe Now To From This Point 90s Former Special Point To That Point To Subscribe This Is The Self Subscribing Elements Of obscuritism there is nowhere to eliminate this post element it will always be containing the cycle and will always also paintings depicting element in its component gift we will remove from this post element and will hit the element as well as no example of repeating element will always be having The intersection this point to 10 minutes this point servi representation subscribe this Video then subscribe to the Video then subscribe to be lit a message to the cycle intersection points basically this point will be present in the cycle and the intersection point will quit tobacco cessation Pontifical 999 At least to incoming and outgoing incoming this point to this unique festival to the Video then subscribe to the Page if you liked The Video then subscribe to the point so this must have established to incoming searches and who's in coming years will also basically our fitting element Because servi is having only one repeating element can defeat for any number of times later than 4000 three times a day will be coming to a different matter how many times number remedy only one element which will be doing so will be the only one interact with nothing But Solution Element Problem Regarding Subscribe Channel Presentation And Ali Representation Of Unwanted Dresses For This Is The Man Chapter Note Latest From This Point Se 0.5 Inch Mode Note Latest From This Point Se 0.5 Inch Mode Note Latest From This Point Se 0.5 Inch Mode On Tap And Subscribe Mumbai To The Point For This Point Thursday Subscribe To Jhaal What Will U Will Just Keep Traveling And Keep Comparing The Values And Fast Values And Fast Values And Fast Pointer In This Case Low And After Having Different Values Will Increase This Point Now 1512 This Point Is Point Se Sauveer What Is This Is The First Point To Point and subscribe button element will be coming from there will not be any interview before china get will have to keep comparing in order to find one the second last element of the intersection points rest ok friends its the second last element press it there matching will Zara Answer Saudi Saja Total Time Complexity Of Man And Not Have In Your Specific Benefits Will Work For Nutritional Value Starting From The First Element Subscribe And Subscribe The Video Then Subscribe To The Page If You Nuvvu Step At A Time And Its Logical To First Development Will obviously with repeating element after will return this point person 125 Very simple but did not give every element subscribe Video then subscribe to the Page if you liked The Video then subscribe to the repeating element OK So this is method one bothers may be present in the calling so please avoid any rate approach or solution in different languages in this post with everyone can different languages in this post with everyone can different languages in this post with everyone can benefit from like share and subscribe our channel like this video thank you
|
Find the Duplicate Number
|
find-the-duplicate-number
|
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive.
There is only **one repeated number** in `nums`, return _this repeated number_.
You must solve the problem **without** modifying the array `nums` and uses only constant extra space.
**Example 1:**
**Input:** nums = \[1,3,4,2,2\]
**Output:** 2
**Example 2:**
**Input:** nums = \[3,1,3,4,2\]
**Output:** 3
**Constraints:**
* `1 <= n <= 105`
* `nums.length == n + 1`
* `1 <= nums[i] <= n`
* All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times.
**Follow up:**
* How can we prove that at least one duplicate number must exist in `nums`?
* Can you solve the problem in linear runtime complexity?
| null |
Array,Two Pointers,Binary Search,Bit Manipulation
|
Medium
|
41,136,142,268,645
|
131 |
hello everyone welcome to coding decoded my name is an today I'm working at sd4 at Adobe and here I present solution to Daye 22nd of January lead code challenge last night at around 2 a.m. in the last night at around 2 a.m. in the last night at around 2 a.m. in the morning I published the video for day 21st of January lead Cod Challenge I know I was pretty late but guys it's all about maintaining the consistency and till how long you can do it so if you are with me I promise hums up consistency now let's focus our attention onto today's lead code problem which is palindrome partitioning the question says you are given an input string s what do you need to identify all possible palindrome partitions of a string that could be generated for example you have an input string S as a and there are two palindrome possible partitions of s that could be generated so as you can see all the sub strings involved in this output string are palindrome in nature similarly this is this case as well if you look in the reverse fashion then if you concatenate these strings together you will get the input string so basically what you need to do you need to divide this input string into smaller pieces smaller independent pieces such that each piece is palindromic in nature and you need to return all such possibilities since the question itself says return all possible palindrome partitions of s and you have to emphasiz on the word all possible pal Andres why because it somehow makes you interpret that this would be solved using the backtracking technique and yes we will use the same backtracking template that have been using from past 2 and a half years same concept applies today as well in case you're new to backtracking concept or coding decoded backtracking template either of the case then what you need to do you need to check out coding decoded SD preparation sheet and here you will find all the questions that are asked in interviews let me just show search for the SD preparation sheet that are highly asked in interviews and with each question you will find the video solution and you will find these questions in the increasing order of difficulty starting from easy medium to hard and I have tried to explain them in the best possible way using presentation for each problem so if you select backtracking over here then you'll find all the important questions related to backtracking once you will go through this sheet then you will yourself get to know that you have got Str strong hold on the backtracking template as you can see this is a mustat backtrack for a learning backtracking template so here is the link and here are the less is in the description below now let's focus our attention onto today's problem the input string that has been given to us is a time to start the iteration so in the first case what we are going to do we'll select a as the first substring and let's write a over here what we are going to do we'll partition we'll check whether it's palindromic in nature or not yes it happens to be palindromic in nature then what we are going to do we'll be partitioning the remaining string in all possibilities of being a palandro so let's continue and next we'll have something like this so we are basically saying that definitely a is palindromic in nature and for the remaining substring whatever it is we'll be applying the same set of operations that we applied over to aab in a recursive fashion so backtracking is nothing but recursion with the tweak and it's not DP remember it's not DP you are not memorizing anything you are generating all possibilities so the other possibility would be uh you have the second case where you are considering AA together and we will first of all check whether this is palom nature or not yes it happens to be palic in nature so we will generate all possibilities for this so the first part of the string substring is fixed which is a and the next part would is B so we'll generate all possibilities that arises over here the third case is the one where we are considering a b together so we will check whether it's palindromic in nature or not it's not palindromic in nature as a result of which we'll simply skip this up so we have to Traverse in these two possible cases and generate all possibilities that could exist so let me just change the color of pen for the next level of iteration and let's focus our attention onto this one now consider the case the input string happens to be only AB in nature then what all palum possible partitions are there so let's get started and let's generate the first one as this one so we have something like this uh since is a palindromic in nature yes it is we are going to generate the palindrome partition for the remaining portion of the string so the first case is this one the second case would be where A and B are treated together as one single unit so let's write it over here and what we are doing we are basically treating a and b as a single unit and we check whether it's palindromic in nature or not it's not palindromic in nature that means we have to abort from over here so this is an invalid case U moving ahead we'll be further traversing down to generate the final possibility and let's go ahead we have the string a then we have B there's nothing that and B happens to be palic in nature there nothing that remains as part of the input string it turns empty and we have finally found one solution that simply Means A and B when treated independently as single units will becomes our one possibility of answer each sub unit happens to be palic in nature which is in sync with expectation let's look about for the remaining portion of that reversal which is a so let's proceed ahead we have fixed the first portion as AA because it was palic in nature and we were traversing over the remaining portion and here the remaining portion only has one character in it which is B since it has only one character in it and B always is a palindromic sub string what remains in the remaining string is empty and we have finally found another possibility of answer so if you look around we are doing nothing but the same backtracking technique that we use in short using this we have generated all possibilities of strings that could be considered and to conclude it up let's quickly walk through the coding section and you guys will yourself see how simple and easy this question is so uh let's check out the first statement here I have created the result that will actually going to store the answer for me I've have created a DFS helper method it has three parameters in it the first one is the variable that will store the result the second one is the state the current state of the list of elements that I have for example I'm have travs so far till over here so it will store AA in this and for the remaining string the processing is yet to be done so a is what is being stored as part of the current list and to start with we have used an empty AR list the next portion happens to be the string input string itself so what do we first of all check if my input string length happens to be zero in nature that means we have found out one possibility of answer and this is the same check as I talked in the presentation where we you saw that after B There Was An Empty string and this check corresponds to it in every backtracking problem the abortion condition for the recursion is most important furthermore I have created a for Loop and the for Loop starts from the zerth index goes up till the length of the input string what we are basically generating we are generating substrings and checking starting from the zus index up till the I index whether those subst strings are palindromic in nature or not so this is a helper method which basically checks whether the string starting from the if index ending up till the J index is palindromic in nature or not and it returns true and false depending on that so in case we found out that from the Zer index up till the i index we found a palindromic string then what we are going to do we going to add that string into our current list so you found out that a happens to be palindromic in nature you added it over here then what you're going to do you're going to apply the same DFS helper method onto the remaining portion of the string which is and while invoking this helper method you pass in the result you pass in the current list and you pass in the remaining subring once you are done with the recursion and all possibilities by this um iteration what you're going to do you'll simply remove the last added element which is the most important step of every back ring problem so has to undo its effect and a lot of people are confused that why do we need to create a new R list over here every time so we have already a list and quite can't be simply added to this so this is a very important question and you should know the answer of it if you will directly add this current list without creating a copy of it and then storing it then what you're going to do you'll be corrupting this current list for the remaining portions that are going to happen in the DFS operation so you can try it yourself you can print the list over here and what you will see that if you're not going to create a copy of it then under the DFS helper method because it is getting passed as the same current string value it's going to be corrupted do give it a shot and you will yourself realize what is the reason behind it let's go ahead and submit this up accepted with this we have successfully completed Day 2 second of January lead code Challenge and I hope that you really like today's solution if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great Daye and stay tuned for more updat from coding decoded I'll see you very soon with a very interesting video take care goodbye
|
Palindrome Partitioning
|
palindrome-partitioning
|
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
132,1871
|
1,202 |
hello everyone welcome to day 27th of april liquid challenge and i hope all of you are having a great time my name is santiago deja i am working a software developer for at adobe and today i present day 666 of daily lead code question the problem that we have in today's smaller string with swaps here in this question we are given an input string s and we are also given an array of pairs that represents the two indexes that can be swapped what we need to do we need to identify the lexographically smallest string that can be generated by performing these traps across these pairs array and you can do it any number of times here they have provided us with few examples i'll be walking you through these examples as well as the algorithm to go about it by the presentation so let's quickly hop onto it lead code 1202 smallest string with swaps it's a medium level question on lead code however i feel it's a lot tricky i would want to rate this question in hard category also in case if you have any doubt understanding this question or if you want to ask anything in general from me please feel free to ping on the telegram group or the discord server of coding decoded i'll be more than happy to assist you with any of your queries even before jumping on to the core algorithm let's try to extract the maximum out of the question i have taken a slightly different example let's assume that the input string that is given to us happens to be a b and c and the pairs array that is given to us is zero comma one comma zero comma two so you can swap the zeroth position with the first position any number of times or you can swap zeroth position with the second position any number of times and let's try to think of what all strings can be generated out of it we have the input string as b c a stands for zeroth index b stands for first index and c stands for second index if you carefully observe then we can generate all possibilities of abc using the data that we have the input string as abc and the swapping pair are 0 comma 1 and 0 comma 2. how and why i am saying this let's see that in action so you have the input string as abc in the first screw what do you swap the 0th index with the first index so these 2 get swapped you get b ac and in the second go what do you swap zero with two so when you start zero with two what do you get c a b that means we have generated two possibilities b a c a b and a abc was the original string now what we can what we should do let's swap uh the zeroth index with the first index over here so what do you get b c a that means the both the possibilities of a string starting with b has been covered the first one is bac and the second one is bca now let's do some more permutations and here in this case what i'm gonna do i'm gonna swap the second character with the zeroth one and what do i get a c b so both the strings starting with a gets covered we have a b c and we have a c e b now let me just do it one more time and this time i'm gonna swap the zeroth character with the first one what do i get c a b and if you carefully observe then again we are able to generate both possibilities of string starting with c here the first string is c a b the second string is c b a so both have been covered and overall you will see that we are able to generate all possibilities of string so let's form groups here and the third one is this one that is highlighted in red so overall using this data you are able to generate all possibilities of the input string and if you have understood this concept you are very close to the actual algorithm what i am trying to say lets look at step two of the algo now lets take a slightly different example and understand the entire algo so the input string let's assume happens to be e d a b c and the pairs that can be swapped comes out to be zero comma two zero comma 3 and 1 comma 4 so if i ask you guys what will be the lexographically smaller string what would be the answer would be a c b e and d you can check it on lead code that corresponding to this string and this pair said the answer would be this now from the previous analysis that we did what we should do we should go ahead and form groups and for forming groups what is the best possible way union find is the best possible way so i'll apply union find approach onto this input string and the pairs that are given to me and i'll go ahead and form groups over it so once the groups are formed zero two and three will point to zero as the parent and in one comma four uh one will point to one four will also point to one uh if you find this parent concept a little new i'm attaching the link in the description below to the union find playlist where i've clearly explained the algorithm you can refer to that but the intent here is to form groups of all the pairs that can be swapped together so what result do we get after this grouping has been performed the first group contains 0 2 and 3 in ids that means the values at the zeroth index the second index and the third index can be swapped together and the values at one comma four can be swapped together in any number of times that you wanna do so once you have this information what you should do you should go ahead and extract those characters so what is the zeroth character happens to be e so we get the first character as e the second character happens to be a the third character happens to be b and what we should do we are interested in identifying the lexographically smallest one so let's swap these up so what do you get a you get b you get e and this gives us the order in which these character will be consumed whenever you see indexes zero two or three similarly let's do it for one comma four case as well so what are the characters at the first index it is d the fourth index happens to be c and let's sort them up what do you get c comma d so whenever you see the index as 1 or 4 you should use the characters in this particular order that we have generated similarly whenever you see the index as 0 2 or 3 you should use the characters in this particular order that we have generated and now it's time to derive the final answer let me just change the color of pen and let's build the answer the first index that we see happens to be zero so zero is part of which group it is part of these this group so which character are you gonna use you'll use the one which has the least value or the least value is a so you'll add a over here let's proceed ahead next we see is one so which character are you going to use you will choose the group which is which corresponds to this one and here the first character is c so you'll use c next let's proceed ahead next we see is 2 belongs to which group 2 belongs to this group so which character are you going to use this time we will shoot for b because a has already been consumed so let's go ahead and write b let's proceed ahead next we see is c three so three belongs to which group it belongs to this group so which character are you gonna use you're gonna use e so e gets added and in the last you have the index as four belongs to which group it belongs to this one and which character are you gonna use you will use d and let's go ahead and add d to it so this is in sync with our expectation and this is our expected result we have the final stringers a c b e d which is as expected now let's look at the coding section and i'll use my union finder template which i always use for forming groups and the rest of the algorithm will be the same as i have just talked here so let's quickly hop onto it so here i've create casted my input string into character format so that i can do easy manipulation over it then i go ahead and i create a map and this map will be of type integer comma priority queue of set of characters so the integer will represent the parent id and the characters will represent all the set of all the characters that corresponds to that parent id this will help us in the formation of groups so uh all characters that map to the same parent in union find and why i have used priority queue here priority queue will help us with the sorting part i don't have to explicitly sort those characters up because this priority queue will be of type min heap so it will implicitly do the sorting for us next i go ahead and create my union find object and i pass in str.length that object and i pass in str.length that object and i pass in str.length that means these many characters will be present in my union find algorithm then i go ahead and iterate over my peers array i unify uh the first element of my pair with the second element of my pair using the union find unify helper method that i have created and moving ahead once the unification is done what do i start the iteration over my input string i go character by character i extract the absolute parent of my current uh index and once i have that parent id what do i get the priority queue from the map i add the current character into the priority queue and i update my map once this is also done what do i do it's time to build my final answer so i again i trade over my input string i extract the parent id using my using the helper method get absolute parent in union find and once i have that parent id i extract the priority queue from the map and i pull out the topmost element what would be the top most element the topmost element will be the minimum one because we have created a min heap out of it and we set it over the string at the ith index once this is done i simply cast the str character into a string format and return the answer now you will ask me where is the union find core algorithm so let's go to coding decoded github repo and uh this is one of the example that i have already solved and where i use the unifying approach let's copy paste this template and let's apply it over here so i want to show that show you guys that this template works everywhere it's a generic template for forming groups and you can use it in any question where union find can be applied so let's see the magic accepted on with this let's wrap up 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 update from coding decoded i'll see you tomorrow with another fresh question but till then good bye
|
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 |
122 |
okay let's talk about base time to buy and sell stock too so if you watch 121 then you probably know the idea so in this question you can do it as many as transaction you like so uh it's not just only one buy and one cell it can be multiple by and multiple cell but you may not engage in multiple transactions simultaneously okay so there's the idea right so what do you actually need to do is you traverse the array right so for each biversal then you compare the two i mean two value first index and second index and if the first index is less than the second index which in this case one and pi then you add to the result for profit variable if not then we just we'll just skip it and pay three no so we skip three six yes so we add to the profit variable which is three uh three plus four right so you get a profit for it and then probably seven sir then two three ten seven so let's just call it for fun right so we need stuff for i versus lens i'm my f i plus sorry so it presses i greater than process i minus one okay so now we know that beginning that should be one right if you put i equal to zero over here then this then the index will be overflow so if pressure is greater than precious i minus one we just will just add to the profit variable which is prices i and then minus prices i minus one am i right yeah i'm right so you just return profit so let's just run it and i hope i don't make a mistake type of mistake so that would be good all right that's super good so let's talk about timing space you need to traverse every single element right so which is all the fun for time for the space is constant so that will be straightforward and i see you next time
|
Best Time to Buy and Sell Stock II
|
best-time-to-buy-and-sell-stock-ii
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
121,123,188,309,714
|
37 |
hi and welcome to solve 64. let's do leak code problem 37 sudoku solver we'll call a method solve with the board and then for the row and columns we'll put 0 and 0 so that's the top left cell we'll check if row has reached 9 and if so we'll say that it's solved and we'll print it and return true we were able to solve it otherwise we'll get the next row in the next column and we'll check if the current cell is already been filled in and we know that if it's not equal to a dot but equal to a digit if so we'll recursively call the solve method with board in the next row and column next we'll have a for loop and iterate over the possible values for the current cell by calling getpossibles which we'll go over in a second for each of them we check if it's not equal to an x but equal to a digit if so we'll try setting the current cell with that possible digit and we'll recursively call the board with the next row next column if that returns true then we'll return true out of here otherwise if none of the possible values work then we'll reset the current cell to a dot and return false that no we were not able to solve it to get the possible digits for the current cell we'll have the getpossibles method and we'll start with digits one through nine and the possible array we'll look in the current row and the current column and disable that number if we see it there next we'll check in the current three by three square and again if we see that specific number in the three by three square we'll disable it from the possible character array by setting it with an x at the end we'll return the possible array so when we enter the code and click submit and we get success our code was able to solve the problem so that's it support me on patreon for code access and one-on-one sessions if code access and one-on-one sessions if code access and one-on-one sessions if you need help with anything thanks
|
Sudoku Solver
|
sudoku-solver
|
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid.
The `'.'` character indicates empty cells.
**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:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\]
**Explanation:** The input board is shown above and the only valid solution is shown below:
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit or `'.'`.
* It is **guaranteed** that the input board has only one solution.
| null |
Array,Backtracking,Matrix
|
Hard
|
36,1022
|
1,018 |
what cool 10:18 binary prefix divisible what cool 10:18 binary prefix divisible what cool 10:18 binary prefix divisible by five keeping it away a of zeros and ones consider and survive drive away from a sub zero to a sub I interpret it as a binary number for most significant digit to a most significant bit to least significant bit we don't list of boolean answer where answer sub I is true if and only if and surprise there was blue by five okay you just keep on going okay I mean that seems straight for it right maybe no okay but you just keep on going and then left shift life in this case it is an actual live shift so yeah and that's what we're returning and then now we just for each bit in a I guess just keep current some yes we did we get we left by one which is multiplied by two because that's the binary digit and then you have ten weather and now we add it by the bit and we just check to see this it's there is a row by five okay it is a debugger now huh I mean I hope I don't have to use on easy bit I'm I guess he'll be a good time to use it if there is a you time to use it cuz I don't know usually I would tested more of it I should actually can to have it over I think this edge cases I may be better when you're the example cases okay I'm gonna do it anyway this sometimes the format it's not easy to copy and paste but just time to give it they use the copy and paste format so that's why as well but some sometimes when you have like five lines of code you just more confident about it so I said that and I got it wrong last time so sometimes you wash it but up but and he's on a more laid-back non and he's on a more laid-back non and he's on a more laid-back non pressured situation I don't wash as much cool okay I guess it could be faster I could've been that much faster I guess I could have pre-allocate the I guess I could have pre-allocate the I guess I could have pre-allocate the results and then instead of using a pen but I don't think that's that but maybe there's some maps that you can do but I don't mean I could optimize that much more and it's in Python time right so yeah this is just a very basic level math to handle shifts and binary numbers and so forth they even gave it to you in a way which is wearing a like a way easy to use format so yeah and this is pretty straightforward I think so I'm going to just move on I think if you do get this on India you - consider yourself on India you - consider yourself on India you - consider yourself lucky so I think that's okay and this is just all bandwidth and it's a number of gates I know right yeah okay cool so very basic problems right
|
Binary Prefix Divisible By 5
|
largest-perimeter-triangle
|
You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
| null |
Array,Math,Greedy,Sorting
|
Easy
|
830
|
1,823 |
hello everyone today we will solve liquid problem 1823 problem name is find the winner of a circular game so we will understand this problem by you know using one example so let's assume here we have one circular array also we have given one integer K and we have to you know delete that cap integer so if we starting from here then now let's assume case 2 so then 1 and 2 so now we have to delete two after that one and two then we have to delete four then we have to delete one then five and you know like that and whenever we have only one element in our array we have to return that one element so this is the problem statement now let me enable dark mode here yeah so now we will solve this problem so first of all what we have to do we have to find the index you know now let's assume if the value of K is greater than length in that scenario we have to change the value of our index so for that part we can do where to get the index so get index here we have our current index okay along with the steps how many steps we can do at a particular time and also our line now here now our new index will be new index is equal to current index plus steps minus 1. and we are doing here steps minus one because we want index not the length of you know the new array if our K is 2 now let's assume with the steps is 2 and the current index is zero so then we will get one year and you know here also we are getting only one so this is so we have to you know reduce minus one from here now if our new index is greater than equal to our length then we have to return new index you know we have to return the reminder and we will use length here and then return X so like that we can get the index of any array using current index steps and the length of that particular array here we have to you know write one more function get answered now as we can see that we are doing this perform recursively each in each iteration we are deleting some item also the length of our array is reducing and the index also reducing so that's why you know we have to write a function and then we will call that function recursively so here in this function we have our array and also index here we will find out the length of our array and if our length is 1 then we can simply return array of 0 because now we don't need to you know call this function again in the else condition first of all we have to pop that element from our array that particular index value will be left then now here we've got new array you know if the size of array is 5 now we will have the size of arrays 4. so now we have to call this function again our get answering function and that we have new array okay new array will be ARR and also we have new index so for that we will use our get index function here so get index in that we will have our current index along with how many steps and the length will be length minus 1 because we reduced well element here from our array okay so this is our second function that name is cat and sun and we are calling it recursively in the end we have to return our answer so for that we can call our function get answer okay here in the initial stage our array will be for I in range of 1 to 1 plus 1 and also we have our index so here also we have to use the jet index function here our initial is index is 0 this is the steps and also the length of our arrays and so as we can you know see that we wrote all the code now we will run it and we will find it out that it is running properly or not yeah as you can see that all test cases are passed now let's try to submit it yeah it run you know it passed all the test cases and all the hidden test cases so as we you know we have a problem statement in that in each situation we have to remove an item so first of all the first problem is that we have to find out the index for that we wrote One function you know get index in this second thing in each iteration we are reducing one item so for that also we have to write one more function for that we wrote get answer function and then we used get instant function to you know get the answer so like that we can solve this problem and if you find any difficulty in this solution then you can comment your problem in the comment section and also if you want to get the solution of some other problem then also you can you know comment the problem number or name in the comment section thank you for watching this video
|
Find the Winner of the Circular Game
|
determine-if-string-halves-are-alike
|
There are `n` friends that are playing a game. The friends are sitting in a circle and are numbered from `1` to `n` in **clockwise order**. More formally, moving clockwise from the `ith` friend brings you to the `(i+1)th` friend for `1 <= i < n`, and moving clockwise from the `nth` friend brings you to the `1st` friend.
The rules of the game are as follows:
1. **Start** at the `1st` friend.
2. Count the next `k` friends in the clockwise direction **including** the friend you started at. The counting wraps around the circle and may count some friends more than once.
3. The last friend you counted leaves the circle and loses the game.
4. If there is still more than one friend in the circle, go back to step `2` **starting** from the friend **immediately clockwise** of the friend who just lost and repeat.
5. Else, the last friend in the circle wins the game.
Given the number of friends, `n`, and an integer `k`, return _the winner of the game_.
**Example 1:**
**Input:** n = 5, k = 2
**Output:** 3
**Explanation:** Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
**Example 2:**
**Input:** n = 6, k = 5
**Output:** 1
**Explanation:** The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
**Constraints:**
* `1 <= k <= n <= 500`
**Follow up:**
Could you solve this problem in linear time with constant space?
|
Create a function that checks if a character is a vowel, either uppercase or lowercase.
|
String,Counting
|
Easy
| null |
852 |
hey there everyone welcome back to lead coding so i'm your host faraz and in this video we are discussing the solution to the assignment that we uploaded in our interview preparation series so the assignment was based on binary search i gave five questions on binary search so before watching the solution just try go to that video in which we uploaded the assignment it is just the previous video just go and try solving all those questions by yourself and if you get stuck you can continue watching the video all right so let us first discuss the problem statement so in this problem we are given an array and that array is called a mountain if these conditions hold so first condition is the size should at least be 3 the next condition is let us say i is an index between 0 and length of the array minus 1 so i is an index now all the elements before i should be sorted in increasing order till i and all the elements after i should be sorted in decreasing order so this is a mountain now it is guaranteed that the array which is given to us is a mountain and we have to return the peak of that mountain okay so peak is the largest element let me just represent this pictorially here we have this mountain like this and this is the peak of the mountain now these are elements zeroth index first index second third fourth let's say fifth index is the peak then six seven eight and nine so all the elements that is uh that is at the index zero and which is at the index one these all will be sorted in increasing order so let me just give an example as well here so let us say 6 7 11 15 20 25 and after 25 it will start decreasing 19 17 8 0 like this so all the elements are increasing order first then they are in decreasing order so we have to return the peak this peak so in the first method we are going to return the index of the largest element so for that we keep the largest element so m represents my largest element so far is going to be initialized with the minimum value the intermin now i will go to each element one by one from i is equal to zero i smaller than added or size i plus so i'm going to each of the indices and i will compare if area of i if this element the current element is it greater than the maximum element so far so m is the maximum element so far if it is the case then my answer is i so my answer could be i if in future i will find some other element to be largest that will be my answer but as of now i can consider my answer as i now array of i is greater than the largest element so far so the largest element will now become area phi so at the end i will have the largest element stored as m and i can see out that this is the largest element while i will be the index of the largest element so i have to return the index return answer so the um answer is going to be the index i will have to make an answer here answer is equal to 0 or maybe minus 1 i can initialize answer with any value so i will just return it and i will see if i'm getting correct answer so it got accepted let me just try to run this so that i can show you the c out the value of m so in this case the largest value is one which is at the index one it might be confusing so let me just take some other example here five no i will have to do it in increasing all right so this is my mountain array and then it should be in decreasing order right to 1 okay so my m should be equal to 5 my m is 5 and my index the index of m is 3 that is why i'm returning 3 in this case so this is a linear search where i am searching the largest element so also this could be done very easily using standard template libraries of c plus so let us discuss that as well so you can simply find the maximum element as you are finding the maximum element in the uh array in the vector so we can simply find the maximum element using this function max element okay so let me show you how do we use that so the syntax is something like this max element and we pass two pointers here the first pointer is going to be point to the first location so that is a r dot begin ar begin gives us the iterator pointing to the beginning of the array or beginning of the vector okay and add a dot end it returns the pointer pointing to the end of the array now this is going to give me the pointer this function max element it is going to return me the pointer pointing to the largest element so i will have to store it so let me name it as answer only okay this is the pointer pointing to the maximum element of the array so i can return this answer okay so why i cannot return this so as i can see i have to return an integer value and the answer that i got here is an iterator so this is an iterator pointing to the maximum element this is not an index right so how can i convert it into index all right so let me just tell you what this is so let me say the given array is this 2 5 7 9 and then 2 1 0. so this is the largest element so it is going to give me the pointer pointing to this element it could be a memory location right it will be in the form of some memory and i know the beginning element it the arr dot begin is going to give me pointer at this location also it will give me some memory location so what i can do is as this is allocated in a contiguous form so i can just reduce the value my answer which is pointing here and my array dot begin which is pointing to the beginning i can just subtract this from answer edit or begin and i will get the um i will get the distance right so i can just return that distance that will be the index i hope it is clear so if i want it in integer form in answer is equal to the this thing minus a r dot begin okay so this should give me correct answer it is supposed to give me the index right and yes we are getting accepted so i think i can just return this as well or return this value so it's just one line code using stls i hope this thing is clear right so maximum this function in which we are passing two arguments the first argument is the pointer which is pointing at this location the beginning this one and the second pointer the array dot and ar dot end it gives me the pointer pointing to the end not this element but right after this element right this is the end this is not the end this is edit.end this is not the end this is edit.end this is not the end this is edit.end which is next to this so the function next element it is going to iterate all over these elements still here and it will find the iterator pointing to the maximum element so it is going to return me the memory location of 9 so i have the memory location of 9 i have the memory location of 2 i can just reduce i can find the difference and i will be able to find the index okay so what do you think the time complexity of the solution is so just let me know the time complexity of this solution in the comments you can read about the function max element from here you can read about everything you can look at the examples you will be able to see the complexity here as well so what is the complexity of this solution let me know in the comments now let us move on to a better approach okay now we will try to do a better approach here what we are doing we were searching the maximum element so we are doing a linear search now we are moving forward to do this solution using a binary search so as we know that this is the mountain the all the elements which are below this point are in increasing order so these are the indices in this one two three four five six seven eight nine ten eleven so these are the indices so index seven is the peak in this example and all the elements from here they are in increasing order and all the elements after seven are in decreasing order okay so what i uh so instead of doing a linear search instead of going to each elements one by one and looking at if they are the maximum element we can apply the binary search as the data which is given to us is in sorted order so i will just try to find out the middle element using binary search as we usually do so at the same time i will keep coding so that it is more clear so for binary search as you have already seen in the previous videos we take two pointers the starting point which will point to zero the first element of the array and the end pointer which is which will point to a or r dot size minus 1 the last element of error now i'll run a while loop while start is smaller than equal to end okay and then i usually find m which is the middle element this is equal to start plus and minus star divided by 2 or simply start plus and divided by 2. so we can either write it this or we can write it at as start plus and divided by 2. sometimes this thing it gives us the integer limit exceeded and this thing it handles all those cases right so it is better to use this one start plus and minus starting where we do if you calculate mathematically these both things are same so now i will compare the middle element okay so i will compare a r of middle element with a r of m plus 1 the next element so in this example this is s this is e so s plus e divided by 2 is equal to 11 divided by 2 which is equal to 5 so this is my middle element let me mark the middle element with this pink color so this is the middle element here will compare it with the element which is next to this m plus one so this is what i'm going to do okay so i will see if the value at the middle element if it is greater than the value at the middle plus one element so a r of mid is it greater than a or r of mid plus one if this is the case so it might be possible that a r of m is the largest element it might be possible okay so if this is m this m plus one then our answer is this one m is the answer but it could also be the case that v r at somewhere here so this is the m plus one so in this case m is not the answer so we need to go backward okay so we need to go backward and how do we go backward in the binary search we go backward by changing the end pointer we go to the left side by changing the end pointer so where should we come so in the previous example we have seen that we do end is equal to mid minus 1 and start is equal to mid placement to shift to right or left but in this case we will do n is equal to m why m because we don't want to miss the answer it might be possible that m is our answer as well and we don't want to miss that is why we will not cross m we will only come to m so and is equal to m right so let me just do this so area of mid if it is greater than the next element then in that case answer could be equal to m and if it is not m then and will be equal to m okay and then not m minus 1 because we don't want to miss the answer in this in if it is the case that m is the answer we don't want to miss that also we are taking the element which is next to m that is m plus 1 and so we will change this condition to start is smaller than end because we are taking we are considering two elements so we need at least two element to be there right so if we put this condition then at least two elements will be there from s to end from s to e otherwise if i do this condition start smaller than equal to e then only one element will be there so i will put this condition because i want two elements otherwise what should be the case in the next case array of m this is smaller than array of m plus one right so again two possibilities could be there so it might be possible that m plus 1 is the largest element so this is m plus 1 it might be possible that m plus 1 is actually the largest element so in that case our answer will be equal to m plus 1 okay otherwise it might be possible that we are somewhere here so this is m and this is m plus 1 so we need to shift to the right side so for that we will make s is equal to now here i want you guys to pay attention we will do s is equal to m plus 1 why not m because last time we did n is equal to m right because we did we don't want to miss the answer but in this case the answer is m plus 1 and not m the chances are only that m plus one could be the answer anyway m is not the answer right because it is not the largest m is smaller than n plus one so m plus one could be the answer so that is why we'll make s is equal to n plus one and not m okay i don't want to skip my answer or i don't want to cross over my answer and here is correct to do s is equal to n plus 1 because m plus 1 the possibility is that m plus 1 could be the answer and not m so here i will do answer is equal to m plus 1 this could be the answer otherwise s is equal to n plus 1 and finally here i can return the answer and for that i will have to create the answer also answer is equal to -1 answer also answer is equal to -1 answer also answer is equal to -1 uh let me try to submit this now this is a binary search solution and that is why the time complexity of this solution is going to be big o of log n so the time complexity is big o of log n and we are not using any extra space here so the space complexity is constant so this is it for the solution if you like the video make sure to leave your likes and leave your comments and keep following the playlist i am going to include a lot and lot of lectures into the playlist and i will try to add the latest variety of questions into this playlist so hit the subscribe button and hit the bell icon so that you can get notifications to the latest videos thank you
|
Peak Index in a Mountain Array
|
friends-of-appropriate-ages
|
An array `arr` a **mountain** if the following properties hold:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
Given a mountain array `arr`, return the index `i` such that `arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`.
You must solve it in `O(log(arr.length))` time complexity.
**Example 1:**
**Input:** arr = \[0,1,0\]
**Output:** 1
**Example 2:**
**Input:** arr = \[0,2,1,0\]
**Output:** 1
**Example 3:**
**Input:** arr = \[0,10,5,2\]
**Output:** 1
**Constraints:**
* `3 <= arr.length <= 105`
* `0 <= arr[i] <= 106`
* `arr` is **guaranteed** to be a mountain array.
| null |
Array,Two Pointers,Binary Search,Sorting
|
Medium
| null |
91 |
hello everyone in this video we will be solving the problem decode ways the problem statement is a message containing letters from a to z can be encoded into numbers using the following mapping like a is represented by 1 b by 2 and etc until z which is 26 we have been given a string with numbers and we have to find out in how many ways we can decode it into letters if you look at the first example the string is 12 so it can be decoded into two ways we can either make 1 and 2 separate as 1 and 2 individually have their respective letters or alphabets a and b or we can club the two together and get the letter l which is also a valid letter if you look at the second example 2 to 6 this can be split up into three possible combination individually you can still build a string like 2 and 6 which will become bbf or you can do a combination where you can say 22 and 6 which will give you vf or you could make 2 and 26 which is b and z so there is the possible combination one of the criteria that they have mentioned is you cannot have a number starting with a letter 0 so if you get anything like 0 6 0 1 0 or anything of that nature is not acceptable so we need to make sure that our logic or the algorithm covers that scenario as well this problem can be solved into multiple ways you can build a recursive algorithm that will iterate through all the letters and then try to build it you can also build brute force algorithm that will iterate through all the letters in the string and find out the possible combinations i am planning to use the binary tree depth first search approach to solve this problem so let's dive into it so we will be using the example 11106 as our string in this problem we have two possible combination we can either take one letter or we can take two letters for example in here if i take one letter i will get one and if i take two letters i will get 11. so i will use these two possible cases and build my binary tree so i will put all the one letters on the left hand side and i will put all the two letters on the right hand side so this is going to my basic approach so let's start building our binary tree now if i start building my left leg i will be splitting the first letter and the remaining will stay as is so i'm splitting out the first letter and so 1 goes out and my remaining is 1 0 6 so now when i split up something i need to make sure that the character that i'm splitting out is valid or not because i'm splitting out one character the validation is it cannot be zero it can be anything from 1 to 9 because all the numbers from 1 to 9 are valid as it has its equivalent letters but we don't have 1 for 0. so if i get a 0 it means i cannot continue further and i will have to break the loop so in this case because it is 1 it is valid ok now i will continue drilling down further so for the remaining characters which is one zero six i will again break it down so i will do something like one comma one zero six this is also valid as one has its equivalent letter a i'll continue drilling down so now for one zero six it will become one comma zero six again this is a valid one now i will try to break zero and six apart so which will become zero and then 6. now here's the problem 0 is not a valid acceptable number so it means this cannot be broken further and we cannot build a combination based on splitting the individual characters throughout so this is wrong so i cannot continue further if i try to build the right hand side from 0 6 if i try to do 0 and 6 now here i don't have anything left because i only have left with two characters but one of the condition that we had is if we have two characters it needs to be greater than 9 because you cannot build a number with 0 in it like it should not start with 0. that was one of the condition that was given in our problem statement so again this condition is not satisfied so this combination cannot be built now i will go a layer up at 106 and now if i try to split it by taking the two characters out i will get 10 6 which is valid because 10 has its equivalent alphabet now i can go continue build an lhs for 6 and i don't have anything left here so it's going to be blank it means we have broken our input or decoded our input based on this combination so now we our combination is 1 which is a then from this way this and then we came down here broke it into 10 which is j and then 6 which is f so we built our first possible or valid combination so far now if i'll go a layer up going back to one zero six now i'll try to break it with two characters out so one zero six again zero six is not valid so i cannot continue further i will cross it out so we have done everything on the left hand side if i'm starting with splitting out one character now let's do the right hand side coming down here so now my characters will become 1 one zero six similar to the left hand side i will continue building on the right hand side so i will have one zero six i will do one comma zero six so this zero 6 is not valid so i will not continue further i will go back to trying to split it into 10 comma 6 which is valid i can break it into 6. so now i have found another combination starting from 11 then i'm coming down to 10 and then coming down to 6. so my possible combination that i built here is 11 is k and then i'm building 10 which is j and then i'm building six which is f so with this input we can build two combination or two decoded messages our time complexity with this solution is o of n square the reason is we are titrating through the list multiple times for lhs and then for rhs okay and our space complexity is o of 1 because we are only storing the result of how many combinations we have built ideally we don't need to save this word combinations as it is not asked in the question but you can just store the result like a counter if you observe something the 106 that we found out here we have already done the same combination on the left hand side it's the same thing so what you can do is you can introduce memoization or some sort of a caching where you are using the index of the string or the character and save the number of combination that you have accumulated or calculated and use that for the future calculations for example if i were to do this combination so at every point if i supposedly found a valid combination here so what i can do is i can save this combination like using the index and the number of combination that i could build somewhere in the cache and each layer i can keep on adding another entry in my cache to make sure i have the whole record so when i'm trying to iterate through it again in this case i will be checking the cash first and validate if it was already calculated if it was calculated then i can directly extract the cash value and increment my counter which would have saved me this compute time if suppose we introduce the caching mechanism then my time complexity will be cut down to o of n because i am iterating through all the letters only once and my space complexity will be raised to o of n because i am saving the cached value for each combination of i or for each index make sure that you're using the index as a key instead of the number itself or the substring itself because there is always a possibility that the same set of number or combination of input is there in the string multiple times so index is the only unique key that you can use safely without worrying about the possibility of the characters being repeated i hope you were able to understand this approach let me show you how you can implement it using c-sharp here is the implement it using c-sharp here is the implement it using c-sharp here is the c-sharp implementation to solve the c-sharp implementation to solve the c-sharp implementation to solve the problem for caching i am using a dictionary of intent and type and initializing it in my main method i have built a helper method called i trade which contains all the logic i start with verifying if the index that i am passing is already available in my cache if it is available then i return the value from the cache itself and save the compute time if it is not available then i start with calculating the lhs part so i extract the first number from the left hand side and verify if it is valid or not for one digit number the validation is it cannot be zero so i'm verifying that if the condition is met then i continue iterating further all the lhs side because it is a depth first search approach and try to find out if the combinations are valid or not if all the combinations are valid then we it would come to this condition where i is equals to the string dot length which means we have iterated to all the combination and everything was valid so far in that case we will return 1 which is captured in the temp result in the flow after calculating the lhs we start with the rhs the first step is to make sure that the index that we are pointing at can do a substring on that it means we have one more character after that so we are validating it on line 49. if that condition is met we then start with the rhs where we are taking the substring of the two characters from the current index and verifying using our rule that we define so the num2 needs to be greater than 9 and less than 27 if this condition is met then we continue with iterating even further so we call the same method again after calculating the whole flow we are recording the result in the temp result variable so we are adding the result from the lhs and the rhs and then adding it to the cache on line 62 and then returning the value from the cache at the end this method is going to return an integer which is being captured here on the in the result variable and then we return the result i hope you are able to understand the explanation that i provided to solve this problem after you understand the approach the building a solution or writing it into code is pretty straightforward as such there is no complexity involved over there the important part was to understand how this can be broken down into smaller problems and that's what i try to do that here if you have any comments or suggestions please feel free to reach out to me i would happy to hear your thoughts about this problem and the solution this code will be available on my github repository you can check it out from there i will be adding the link in the description too thank you for watching this video and i hope you have a wonderful day
|
Decode Ways
|
decode-ways
|
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s).
| null |
String,Dynamic Programming
|
Medium
|
639,2091
|
130 |
let's solve legal question 130 surrounded regions and this is our median legal question so give a m n matrix board containing x and o if you look at example here there is x here there's o here capture all regions that are four directionally surrounded by x so this question if your traversal the graph make sure it's four direction up down left and right not diagonal a region is captured by flipping all o's into x in that surrounded region so if you look at the example here there's x and there's o here and if um in the end result if our o is in the middle section then it will change all the o's flip them into the o that's a function that you need to write and if you read this part it surrounded the region should not be on the border so you want to make sure that all the o's on the border cell that is not get flipped into x because you want to keep the o as o any os that is not on the border it is not connected to an o on the border um will be flipped into x so that means that if there's a o this example it doesn't show you if a o is connected if this guy is not an x here this guy is a o it should be flipped into um oh it should not be flipped into x because according to this sentence is there any zero that is not on the border and it is not connected to an o on the border will be flipped into x so this is something you definitely need to pay attention to um two cells are connected if they're adjacent cell connect connected horizontally or vertically and it gives you another example here x is already x so you just keep it as x and here's some constraints here and this is an interview question asked by bloomberg six times google five times in the last six months and if you wanted to take a look at this question it's actually for this kind of question you probably um think about use either definite search or breakfast search the only tricky part is that it only wants you to it the tricky part is that it really wants you to keep the border cell as o right also the cell that is in the middle that are connected to the o is if it's o here you want to make sure it's o as well but then the rest of the cell in the middle section you all want it to flip into the uh the x so let's say so i'm going to use that first search for this case the idea is that if you want to reach the angle the way that you can do it is that you can use that first search but only run the different search on the border cell like the borders here so what you're gonna do is that uh first you're gonna run uh the different search function should change the o to a different character let's say something like e change this to e and then i'm gonna run that first search on this ease neighbor to make sure i capture those and i'm going to call the different search function on all the border cell so that they all get all the o's on the border get flipped into e and then for the middle section it's actually really easy i don't even need a daffor search function for the middle section all i need to do is just go through every single cell and just change all the o's to x and after that if there's any cell remember i change this guy the border ones to a different character like e you can use any characters that you want we want to make sure we flip them back to o as the angle basically that's the thought process and i think you will understand this when i show you how to do this in code so let's first roll out some edge cases so if not board or not board 0 here then i'm going to return right and um so then i'm going to define this rows and columns and its land of length of the board and length of word zero yeah so let me just write the default search function for the border uh cells so that we can call it uh that first search function what i'm gonna pass is the parameter src basically the row and the column number so if the row and column is inbound right so i'm going to say if it's 0 equals to r and smaller than rows and zero smaller equal to c smaller than calls basically inbound and board rc r c so basically the value is also o right if that is the case i'm going to change the board rc to a different character i'm using e here but really you can use any characters that you want and then once i do this i also need to make sure that to change the neighbors to do the death research on its neighbor basically four directionally and then so i'm gonna do is rc and all four neighbors to continue this that for search function to change the rest that i need to change if it's all connected then i need to change to e as well so basically r plus one r minus c plus 1 and c minus 1. um for the defer search function you don't need to say it's inbound uh like check it's inbound i'm just doing like a condition check like this but you can also check to say if it's outbound or down how you're going to do it but essentially it's the same thing so right now i'm going to call the diver search function but i'm only going to call the that first search function on the border cell because for the inside i simply don't need it so how you run the different search function on the border cell right how you do it is for r in so either the rows are in the row it our rows are in the row zero or rows in the r rows minus one for c in range of calls for all the columns basically these two right zero row and last row in all the cell i'm gonna run excuse me run the that first search for the rc and then i'm gonna call the diver search function on the left line in the most the right border right so how you do is for r is that i want to do in all for all rows right but for the colon i only wanted to do two colon one is the zero colon basically is this one and then this one is collins calls minus one so basically this one here and then after that i'm going to call that first search function on this line and this line so once i run through these for loops that i have already run that first search function and changed all the o's into a different character let's say e i already flipped them so then when i change the middle cell these border cell won't get impacted so i'm going to show you how to change the middle cell i simply don't need to use any different search function for the middle cell i just need to for r in range of rows and four c in range of calls so basically everything go every single one right so if board r c equals to o in the middle what i'm gonna do is i'm just simply gonna change the board rc to x basically the things i want to try to do but i'll try going through this right and remember we changed these part the data search function just change the these border cells to e right i need to flip them back to the o as it required so then i'm going to say if the border cell oh if whatever the cell it is we're looking at it's e it's not necessarily border cell it could be a cell like right connected to the border if the cell is e what i'm gonna do is to change the board um rc flip it back to o this way i will be able to achieve the final result i change all the borders to the o and that middle cell is all flipped into x should be right let's see yep okay i hope this is helpful please like my video and subscribe to my channel and i'll see you soon with more questions
|
Surrounded Regions
|
surrounded-regions
|
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
200,286
|
999 |
so this question is available capture for Rook so given the chess board there's is exactly one white Rook represent R and some number of white by shop and black pal empty square and then pretty much uh this is idea so you are given this diagram sorry 2D array right this diagram you want to go on your four different direction to check can you attack a PA and if you can just return the number of varable capture uh P for the white Rook so yeah in this one you are surrounding by yourself so not you know you're not Capt anything this one you are capturing three capture three because this one is blocking so it's pretty much straightforward we need to find out the location of the white rot so how do you find this be i = z j = rot so how do you find this be i = z j = rot so how do you find this be i = z j = z and then for in i = z and then for in i = z and then for in i = z sorry uh I'm going to say X and Y when i z I less than border lens i ++ Y when i z I less than border lens i ++ Y when i z I less than border lens i ++ j = j = j = z J less than border lens sorry Z lens in j++ if j++ if j++ if for AIG J is equal to what R is pretty much we know the location i x to i y = j and then we don't need to x to i y = j and then we don't need to x to i y = j and then we don't need to keep traversing all right so once we find out the location of this guy right so four different direction is pretty stra forward you know going be 1 0 0a 1 0 comma 1 all right so for in direction directions and then I can start in my attack right so imagine I'm here right I can Traverse all the way to the left and all the way to the top but imagine I'm here I'm traving all the way to the right all the way to the bottom so you want to make sure you're in know boundary right so for in you know uh I'm going to say a equal to what direction is z plus the X which is going to be the x axis right and Bal to Direction 1 + y okay so what and Bal to Direction 1 + y okay so what and Bal to Direction 1 + y okay so what are my boundary a less than eight right you can say both of lens and also a greater equal than zero and it's going to be similar to the b less than what uh for z. lens and B great equal zero and then we need to increment based on the what increment based on the direction so it's going to be plus equal the direction but we don't need a y and we don't need x wait this going to be A+ equal all right so this can be what this can be eight right because it's a fixed number of Chas board if I have you know uh a different chest board you still going to be have eight right and then if the board a if this is equal to the p represent pal right you can increment your result so result equal to zero result Plus+ return result and then is El if the b a b is equal to what anything um should be dot Mt dot uh if not equal to the dot which mean this is dot this is not a DOT if not equal to dot we continue which is going to break if you continue you can still keep going but we want to break out this direction go on the next Direction which is going to be you know from right to top or from right to bottom determine which one you go but this is One Direction and you break up and then you go on the next Direction okay so SP wrong and do wrong so I have five for case three okay so make sure I you know try to do this way okay pass the test case here's a reason why because if I using the else if right I can okay I eat this one but I am still going right I'm still going so even though this is not a DOT right if this is p and then we should stop right because we don't want to keep going right we don't want to keep going left and then yeah pretty much the idea I was doing since more so time this is also the time so this is going to be all of n times all of M this is all of four different direction and for different direction you know the maximum range is going to be 8 by 8 right so this will be the constant for this is going to be the worst case all of n * m worst case all of n * m worst case all of n * m space is constant right now allocate any space all right see you later bye
|
Available Captures for Rook
|
regions-cut-by-slashes
|
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**.
Return _the **number of available captures** for the white rook_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** In this example, the rook is attacking all the pawns.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 0
**Explanation:** The bishops are blocking the rook from attacking any of the pawns.
**Example 3:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5.
**Constraints:**
* `board.length == 8`
* `board[i].length == 8`
* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
* There is exactly one cell with `board[i][j] == 'R'`
| null |
Depth-First Search,Breadth-First Search,Union Find,Graph
|
Medium
| null |
174 |
Hello Everyone Welcome Back To Hindi Karna Hai Dare To Discuss Them Very Interesting Problem List Ko Damages Arising In This Problem They Will Give Electronic Officer Princess Line Right The Bottom Right Corner Of The Amazing Decide Top Left Corner Of The Great Khali We The Prince Is Subscribe Channel Like And Do Subscribe Button Number And Now Night Moves From Subscribe Many Insiders Said Thursday The Will Produce I Don't Want To Is Basically Night Shift To Reach The Princess Amazed At Least Amount Of Positive Health Survey Is Field Officer Below That Is Not Possible Benefits Sexual Tours From West To The President Prime Example Till 5 In Which Country Is Moving In The Bottom Right But What Would Be The Mission Impossible Minimum subscribe And subscribe The Amazing Solve And Subscribe Minimum Possible Subscribe To 120 Years In Jail That Not be entertained the notion of top traction or final attraction and exciting real life for reduction of water inspection listen enter old age stuff toys starting energy further and alerts denoted as Amazing from the cell quality of joint final health so let's Vinod Light Help by faith and believe what is the relationship between the to the best quality te amount of research and wild in the sale amit ko whatsapp relationship bahar s plus dl term deposit to f-18 hai b to help can dl term deposit to f-18 hai b to help can dl term deposit to f-18 hai b to help can live with all the guys positive always Feature Relationship and Edification More 1981 Radhe Loot Hai and Night Sweet Dream Good Topless Age Android Aa Bottom Right Cell Somewhere in the Distance and This is Reality Wilson Quantum Initial Energy's Toilet Adventures Editing After Taking Present Life in a Cardamom App and Similarly All The seventh dowry is basically Neetu and Cotton problem statement it has 5 to 6 values subscribe And subscribe The Amazing equal to how do they do it a spider device problem into smaller states problem basically in one-character time and tried to one-character time and tried to one-character time and tried to optimize the Value of the setting health point when skin the time and distance from the one true go this point and tried to minimize the value of disturbance deterioration solution so let's start with about their rights and basically where the and princess president electronic time amazon of health initial help Channel and Celebs - 5th What is the Meaning of the Final Celebs - 5th What is the Meaning of the Final Celebs - 5th What is the Meaning of the Final Decision Juice and Share Subscribe Health Tips Minimize Thee Ka Safar Bhi Chut That Request Andar Dishonored This SSC Cold Wave - Detox This SSC Cold Wave - Detox This SSC Cold Wave - Detox That Angry Node Not B0 Add To Appointment God All Happy The Meaning Of value pass maida relief s basically one saw to minimize the value of spirit to minimize the value of one incomplete value way shift such equal to one - delta-1 way shift such equal to one - delta-1 way shift such equal to one - delta-1 hair na effigy of negative 90 subscribe our channel subscribe and bank wala tractor mind in which they Safal Bhi Question Aa Mixture Tab Positive Status Use Request Hai Desert Festival Tata Value Homes Nawaz R.A. 8 - - Fennel 5 December Such a person is tough 8 - - Fennel 5 December Such a person is tough 8 - - Fennel 5 December Such a person is tough laddu idol inside left side loot real name on only possible he can no problems he sleeps at night nor will give vote to bottom left subscribe to this channel 6 ko saaf hum jis tal guaranteed yes Sorry for the final of distance to be quite aware of his cell a great you already know is 3818 questions equal to 9 6 - Delta Energy Systems equal to 9 6 - Delta Energy Systems equal to 9 6 - Delta Energy Systems Negative Monitor Amazon Basically Maps of Work Me 11 - Delta 1000 Atlist Meghvanshi 11 - Delta 1000 Atlist Meghvanshi 11 - Delta 1000 Atlist Meghvanshi Software Tools Equation 200 abs Pickup Maximum of Woman Power 8 - 2421 100 Minimum Help Yuvan 8 - 2421 100 Minimum Help Yuvan 8 - 2421 100 Minimum Help Yuvan Hai Na Download Tel Sirsa Finishing Relief for Distance in the Final of this will be option one Bigg Boss Vikramo Decoration for Actually Not Mouni Roy Certificate and Toys Hai 80 gin Use this equation is equal To Maths of One Cover I One - 10th I One - 10th I One - 10th That Me Aage One And Welfare Destroy Them In Thee Maps To Muddasar Itni Seervi Cup Sugar Li Hai A Part Of This Vansha Of Wave 16 - One Special Basically 5 16 - One Special Basically 5 16 - One Special Basically 5 Tomorrow Morning Sacrificial Fire On Earth In Particular Asal Name Option Lalit Dal Notification Movement Direction Distraction Oil Distraction But What Make Sure Basically You Itni Si The Question Aa Gaya Ginger Turmeric Switch Off Lemon Face Minimum Solve They Tried To Us Channel Minimum Subscribe The Value Of Download The Value Of 02 2015 witch one oo after if you and it - stand 100 gil after if you and it - stand 100 gil after if you and it - stand 100 gil beau referred 954 tower is - - - I reverse my treatment Sudhir and ka ras malai ko dip place vikram vibration and important addiction but what they want to waste water commission record Hai s minimum so f5 volume minimum of eleventh 310 wickets one-day and address - power 310 wickets one-day and address - power 310 wickets one-day and address - power steering and MS Word we maths of this dynasty Brahmin of this dynasty - - 50 - 6 this dynasty - - 50 - 6 this dynasty - - 50 - 6 ki Ramesh ka dal and Hai wickedness movement butter nation not in right direction fennel This basically the starting point of this service is 5 and tractor shri lo s victims maths of main one ko m 15 - 3 surat to 15 - 3 surat to 15 - 3 surat to hua tha na pardes particular word hai he more run mobile where distraction burst on them choose minimum balance of the soe Pimple to minimum of trucker a vision delta and it - 300 gas value a vision delta and it - 300 gas value a vision delta and it - 300 gas value development maps of a aa maithili ab ban pavk 11 - that sun part 2 - - visit 500 especially on that sun part 2 - - visit 500 especially on that sun part 2 - - visit 500 especially on December - 5910 particular festival in this direction December - 5910 particular festival in this direction December - 5910 particular festival in this direction 12th juice distraction development address slept on minimum pickup minimum of that 501 are more another mindless value maths 9th is 1.5 plus two class seventh subject is 1.5 plus two class seventh subject is 1.5 plus two class seventh subject hence and seventh pay commission value contest turning point of this gallant azhar optimal aaj tak subject wise previous starting value for the first president of plant sale And Have Been Started From This Point To Find The Satanic Verses From This And Optimized Solution For Toilets And Solution Subscribe Problem Subscribe To All This Problem And Basically This Water This Problem Ancillary Forms Of Seventh Cpc Tablet Problem Dependent On R Problems Point Solution Se Solution Dynamic Programming Solution Subscribe and into a Main Ashok mode of this particular problem is available in the discussion below and thanks for watching this video Thanks Luck Shabd
|
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
|
279 |
Hello everyone welcome to my channel code sorry with mike so today we are going to do video number 86 of our dynamic programming playlist ok lead code number is 279 which is marked medium I have already made a video on this problem through repetitions and memorization. Okay, I have already made the link in the description. Okay, you will go to the description, there you will see the link. Okay, I have explained the recurs and memos very well, so let me revise the question once again so that you can get an integer. Okay, you have to return the least number of perfect square numbers whose sum will be equal to n. Okay, and what are perfect squares and do you know like 1 4 9 16, all these are perfect squares, 3 and 11 is not a perfect square, so let's see an example, let's say 12 is given, then the least number of perfect square whose sum is 12, then there are many perfect square numbers, if 4 is not there, then even one is a perfect square. Right, if you add 1 P 12 times, you will definitely get 12. Okay, so look at how many numbers are added, the total is 12 numbers, but it also means that it has become a very big number. You need 12 numbers to reach 12. Ok, let's look at the next perfect square, like look at four is also a perfect square, add four three times and see, you will get 12. If you need to add only three times, then see how many minimums did you find to be perfect, only three minimums were found to be a perfect square. You have to bring 12, so look at the answer, it is three. So, what is the minimum number of perfect squares with which you can bring this number. You are being asked to do so you have to tell the count. Look here, 4 P 4, 12 is done, ok. So now let's see, I have told you that the video of Recurs and Memo is already ready. You will get the link in the description in this playlist. See what I have discussed in it, so go and watch it once. I have discussed this in it. Why can't we use Greedy to solve this? Secondly, why is this a DP question? I had explained it to you through the tree diagram as well. I told you in detail about the tree diagram. It is ok in that and story to code. I always do it is done very well, so do watch the video of Recurse Memo, the code I have done there, I will make it bottom up using exactly the same code of Recurse Memo and I generally do this all the time. I keep the Recurs memo in front and derive the ration memorization from it. At the bottom up, look, I have written the code here, derive the bottom up from Recurs memo, so this was the code of our recurs and memoization, that is why I am telling you that once I Watch the video on recursion and memorization, link is in the description, so this is the code we have written, okay, this is what we are going to derive exactly, this is okay, so you must be seeing a clear cut thing here, which we have written in recursion. It was written in it that you are seeing only one variable is changing, so I got a little hint here that we will take the bottom up DP, we will take the one dimension of the bottom, we will be fine. Look, what have I done? Hey, I have taken the one-dimensional thing. Because of my values, Hey, I have taken the one-dimensional thing. Because of my values, Hey, I have taken the one-dimensional thing. Because of my values, I have taken only the one-dimensional thing. Now look, pay attention. only the one-dimensional thing. Now look, pay attention. only the one-dimensional thing. Now look, pay attention. Always do the first step in the bottom up. What we used to do was to define the state, right. So first of all let us see what we have to find out, what is asked in the question, minimum perfect squares to get n, if n is there, then we do not know the answer, then what will we do, if we find out the answer for small chunks, then we will define a state. Let's take t, what does it mean to get minimum perfect squares to get i, because right now I don't know the answer of n, that's why I will first find i, then i + 1, i then i + 1, i then i + 1, i + 2, then lastly I will find n, + 2, then lastly I will find n, + 2, then lastly I will find n, okay? So that's why I have defined the state here Minimum Perfect Square to Gate i, okay now look pay attention, what is asked in the question is that Minimum Perfect Square to get n has to be calculated, then from the last I will return t of n till it is clear. Now let's see how to solve this. See, I have just told you clearly that I have to find out A completely but if I don't know then I will find out t of A. First, find out A from i = know I don't know then I will find out t of A. First, find out A from i = know I don't know then I will find out t of A. First, find out A from i = 1 till i. I will do it like this, it is okay, this for loop must be clear, first I will take out i = 1, then I will take out i = 2 and so first I will take out i = 1, then I will take out i = 2 and so first I will take out i = 1, then I will take out i = 2 and so on, ultimately I will take out i = n, I am on, ultimately I will take out i = n, I am on, ultimately I will take out i = n, I am okay, it means a simple DP, whatever is mine, right? If I have to calculate it up to n, then it should be of size n, so its size will be n, okay, I write this, it will be of size n, it will be from zero to n index, okay, it cannot be zero, right? If the target is zero then you can't do anything, leave it aside, target is one, two are three and so on, no, so on, till n has to be calculated, okay, we will calculate target one, we will calculate target two, we will calculate target thi, and so on. We will find the target n. It is clear till now, so this is what I have written in the for loop. Now look, pay attention. Now let's come to our recurring code. If you pay attention then remember, to find any number, let's say I am here. Had to find n, okay so first I tried which are the perfect squares, one is one, okay so first I tried with perfect square one, after that see if i is plus then the value of i will become two then i I will check 2 cross 2 i.e. then i I will check 2 cross 2 i.e. then i I will check 2 cross 2 i.e. four is perfect so four is perfect then I tried again. Look in n I have crossed i cross aa means subtracted 4. Okay so we had tried all the possibilities that is why I am saying this video is mine. Please check it out, it will be very clear from there, so we will do the same thing here also, what will we do? Look exactly the same in the for loop, I am copying and pasting this one, ' copying and pasting this one, ' copying and pasting this one, ' Brother, what can I do?' I don't know how to find the answer. So Brother, what can I do?' I don't know how to find the answer. So Brother, what can I do?' I don't know how to find the answer. So what I will do is first start with j = 1, this is my first start with j = 1, this is my first start with j = 1, this is my perfect square and I will ensure that j * j must be equal to a, only that j * j must be equal to a, only that j * j must be equal to a, only then I will be able to bring till a, see I am doing the same here. I started with i = 1, I am doing the same here. I started with i = 1, I am doing the same here. I started with i = 1, I am insuring that i * should be less than equal to insuring that i * should be less than equal to insuring that i * should be less than equal to n because I have to bring n, so n should be slightly greater than n, I have to bring in the answer, okay, so that's what I am doing here. That I have to get the answer of i, so I started from j = 1, That I have to get the answer of i, so I started from j = 1, That I have to get the answer of i, so I started from j = 1, this is the first perfect square, okay, and why did I do 1 * 1, because I okay, and why did I do 1 * 1, because I okay, and why did I do 1 * 1, because I want a perfect square, so 1 * 1 is want a perfect square, so 1 * 1 is want a perfect square, so 1 * 1 is obvious, only one will come, then the perfect square will be equal to i. Need more If there is a value then I will compare it here off a comma, look, they used to call recurs 1 plus rec, then see what they did, they called plus ration and in recurs, look what they used to send, now whatever is my remaining a, they used to send, okay. So what was I supposed to bring? Aa was to bring okay and in that I have subtracted j in j okay so what will I do aa minus j in j Now bring the answer of what is remaining okay till now it is clear so just replace us here. What to do was to replace t with t instead of solve t off a mine j in j Okay till now it is clear now just what do we have to do in the last as soon as everything is filled up last we have to do t off what we need We will return t of n in the answer. See how simple it was. If you understand the basic way of solving a problem, like bottom up, then we followed the same method. If you follow that method then you will definitely reach somewhere in your solution. It is okay but at some places you may get stuck at the bottom up. If that is very much then yes brother, how much for loop do you have to put and recurse memo since you write it? If you give, you will definitely be able to start relating from there, that is why always follow this thing, whenever you are writing bottom up, then it is okay, it is clear here and we do not have to worry about what i - j * j is. It will go out of have to worry about what i - j * j is. It will go out of have to worry about what i - j * j is. It will go out of bounds, this will not happen because look, I have written here that j * which should be equal to aa, * which should be equal to aa, * which should be equal to aa, then it is obvious that i - j * j will never go out of bounds here. There will be then it is obvious that i - j * j will never go out of bounds here. There will be no bound index. Okay, so it was quite simple. Look, we derived it from the recursion memo and wrote the same code. So let's go and its time is clearly cut. You can see how much it is, and here o of n times is going on. Nah, here too, if we take the value o of n, then we have seen that it is quadratic. o of n is s. Okay, let's make it time complex and finish it, so let's code quickly. First of all, what I said is that I take a vector. I will take it, okay, I name it t and its size, I took n pw and why I took it, I also told you, okay, and here I define the state that what is off aa, what is the min number of perfect square two. Get A is fine and what do I have to return of Ok, so I have put zero for that, int i = 0 i sorry i = 1 i <= n will be for that, int i = 0 i sorry i = 1 i <= n will be for that, int i = 0 i sorry i = 1 i <= n will be found till i + p ok now found till i + p ok now found till i + p ok now I want to find each i, so try each perfect square. Will try with j = 1 square. Will try with j = 1 square. Will try with j = 1 and insure that j * j is what it is, and insure that j * j is what it is, and insure that j * j is what it is, take = i should be j take = i should be j take = i should be j + Okay now look, pay attention to + Okay now look, pay attention to + Okay now look, pay attention to what we used to do in recurs that brother of aa = minimum brother of aa = minimum brother of aa = minimum of t of aa comma okay yes here. But I had missed One Plus, since I have taken a number, then you will do One Plus, you will do right and recurs, we used to call right and recurs, right? What did we send in rec, whatever number was there, we used to subtract perfect square from it n my j*j. subtract perfect square from it n my j*j. subtract perfect square from it n my j*j. Because J We are finding the minimum, okay then put a big value here, okay put int max or anything big, put a doti ch pa, put anything big value, okay then all the test cases have passed, let's see after submitting. Have any doubt please raise in the comment section I will try to help ya out see you guy in the next video
|
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
|
1,920 |
in this question we are given array nouns and we are going to return our array and in which case nsi equals to nums i initially uh women think this question is so easy we can just create an array and assign nums i to ensign but after taking a closer look there is a follow-up question can you there is a follow-up question can you there is a follow-up question can you solve it without using an extra space over memory which means we have to return numsai we have to do this change in place how to approach this question let's take a look at this oven solution we need to apply the changes in place but how to make nums i equals to nums i without using any extra space we can define two variables a equals to num psi and b equals to nums i uh by observation we can find a plus b and divided by an equals to b and a plus b and mode n equals to a so we can use a plus b and to preserve a and b by applying division or mode that's how we can do this change in place so we can apply about rule two numbers i here times i equals to nums i plus n multiplied by nums i mod n you might wonder why do we have to use this mode n in the end it's because we want to get the original value of nums numbers and the during the processing as we go through the loop num snaps i might have already been processed as a plus bn so we have to apply this model to get the original a value back i can use an example to further explain this i'm using the example from example one so the original number is this array and the answer should be this array keep in mind when i equals to 1 after calculation num's i equals to 8. number one equals to eight but the original numbers one here is two so one i is two in the calculation of numbers two we are using nums one but this times 1 has already been altered to 8 we cannot use it directly we have to mod it by 6 to get the original value 2 back so that's how we can get the original numbers one back let's take a look at the code initially they define variable n to preserve the length of nums array and we will do two loops in the first uh first pass we go through the loop and the nums i equals to because to this b equals to a plus b and they use a mod n to get the original value of a and in the second loop now nums i is already equals to a plus b n so by dividing it with an a plus b n divided by an equals to b is num synon by definition so after uh in this loop after applying the division operation numbers i equals again so we've already applied all the changes in place without using extra space and that will return the new unknowns array um is a little tricky uh but uh hopefully after this explanation i will have a better understanding of this method thank you for watching my video if you like the content of it please subscribe to my channel thanks
|
Build Array from Permutation
|
determine-color-of-a-chessboard-square
|
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
**Input:** nums = \[0,2,1,5,3,4\]
**Output:** \[0,1,2,4,5,3\]
**Explanation:** The array ans is built as follows:
ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\]
= \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\]
= \[0,1,2,4,5,3\]
**Example 2:**
**Input:** nums = \[5,0,1,2,3,4\]
**Output:** \[4,5,0,1,2,3\]
**Explanation:** The array ans is built as follows:
ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\]
= \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\]
= \[4,5,0,1,2,3\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < nums.length`
* The elements in `nums` are **distinct**.
**Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
|
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
|
Math,String
|
Easy
| null |
1,576 |
Hello Friends Welcome Back To My Channel Should We Are Going To Discuss Problem From Weekly Contest 0.5 Inch Replace All The From Weekly Contest 0.5 Inch Replace All The From Weekly Contest 0.5 Inch Replace All The Way Sharma Studio And Positivity Character Sundha Were Given Is Singh Sn Food Which Content Parties English Latest And Will Mark The Question This Year 2012 convert all the best in the characters in the alphabet ranges from her use responsible 500rs lion director it is not from this ritual for breeding institute character of taking some mistake in example1 few years back when ur great s doing so they can replace this question mar By The Character t-20 But Not With Others And Character t-20 But Not With Others And Character t-20 But Not With Others And Different Ways But Not With Him And Abuse And Its Relationship With Him Vs Characters Tool For Defeating Positive Chapter 16 - Not Tool For Defeating Positive Chapter 16 - Not Tool For Defeating Positive Chapter 16 - Not Valid CSS K Ok Toh 210 Bulaya Aur Hai Sonalika Ruk Alphabets Characters And Others Day 5 Singh Dhoni in Adelaide Test Match Loot Up For Pimples Operation Referee Testing Minutes Meeting Facility Center Singh And Moisturizer Your Feet Is Question Mark This Occasion They Can See Only Motive Intent Character Fertilization Maths There Three Cases Let's Check The Specific Index Of Kia Middle After the opposition 's publication Math Reasoning in Between Life One 's publication Math Reasoning in Between Life One 's publication Math Reasoning in Between Life One Dose - Wonderland 2463 Dena Hai Aur To Ye Jo Dose - Wonderland 2463 Dena Hai Aur To Ye Jo Dose - Wonderland 2463 Dena Hai Aur To Ye Jo Maine One Plus One Can Update Your Character And Only One To The subscribe Video then subscribe to the Page if you liked The Video then subscribe to the Last Specific Things Which Form Last Date The Behavior Cash Withdrawal High Puberty Character Sunna Bhi Matching Melta Plus One Another With No Character Sauda Ho Gaya Wahi Front Is Program Schedule Accept This Should Accept It Will Cover All The Scripters List To Show It's Quite A Steer With solution android phone
|
Replace All ?'s to Avoid Consecutive Repeating Characters
|
reorder-routes-to-make-all-paths-lead-to-the-city-zero
|
Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters.
It is **guaranteed** that there are no consecutive repeating characters in the given string **except** for `'?'`.
Return _the final string after all the conversions (possibly zero) have been made_. If there is more than one solution, return **any of them**. It can be shown that an answer is always possible with the given constraints.
**Example 1:**
**Input:** s = "?zs "
**Output:** "azs "
**Explanation:** There are 25 solutions for this problem. From "azs " to "yzs ", all are valid. Only "z " is an invalid modification as the string will consist of consecutive repeating characters in "zzs ".
**Example 2:**
**Input:** s = "ubv?w "
**Output:** "ubvaw "
**Explanation:** There are 24 solutions for this problem. Only "v " and "w " are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw " and "ubvww ".
**Constraints:**
* `1 <= s.length <= 100`
* `s` consist of lowercase English letters and `'?'`.
|
Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge.
|
Depth-First Search,Breadth-First Search,Graph
|
Medium
| null |
153 |
today we will be solving problem number 153 find minimum and rotated sorted array on lead code which is basically a website where people who want to get better at coding or just want to practice their skills and improve could go to this website basically has like a lot of problems just like this one and different ones so people could go here and practice today we will be solving this problem which is basically we have to go through a list of numbers and find the smallest one but the challenge here is that not always will the list of numbers be sorted like this sometimes they will be rotated to where like the smallest numb is like maybe back here in the middle so we have to write an algorithm that finds where that smallest number is for example in example number one you could see that the this was the original rate array and it was rotated three times so started off here so one two three and the one would be right here so you would be searching through this array so you could find where the smallest number is so this is basically this problem there's different examples as you can see the length varies so you want to try and find an efficient solution or you could brute force it if you want but it's not going to be really efficient so yeah this is what this problem basically is one solution you could do this is basically a simple solution which I would call a Brute Force solution since you are basically going to start at the beginning and check to see where that where the smallest what the smallest number would be in that array so first we could make a variable an integer variable and we could set that in integer variable to the max value and inte could be which is basically two to the 31st power and then after we make a variable so we could store our lowest number and return that at the end we could make a for Loop which starts at index zero the array so we could make in IAL Z and then we would go until that last number in the array we do numbers. length and then we would iterate one by one and after we make that for Loop we would check to see if whatever is at spot nums of I we would check to see if that is less than whatever is our Min value and it if that comes out to be true we update our Min value to the um whatever is that spot of nums of I then after we do that we could just come outside this for Loop and return our men and that should give you a solution the other solution I will be showing you is I will be using an algorithm called binary search so basically binary search is when you start at the middle and check to see if your target is on the right side or on the left side if your Targets on the right side you basically just cut off whatever's on the left side so you don't search that and waste time searching through it you just start the middle and go through there you keep like halfing it so it would be faster and more efficient so first we could make an integer called the left side and we could set that equal to zero and then we can make another integer called the right side where we would set that equal to the last number in the array which we could do that by doing nums do length minus one and then after we do that we could make a while loop and in that while loop we can do while the left side is less than the right side we keep doing this while loop over and over again until we meet this condition and inside the Y Loop we could create the middle variable where that would basically be the low plus left plus the high which is basically the right side and then divid by two then after we do that we check to see whatever nums whatever is that spot nums of mid is basically the middle of the array we'll check to see if that is less than whatever is nums on the right side if it is that we could just basically cut off the right side and set it equal to Mid so we don't search that right side and if it's not that we do an L we come outside this if make an else we check to see and if this first condition isn't true we would instead of doing the right side we would do the left side we would update the left side to be the middle plus one so that would cut off the whole left side and we can start the middle and after we do that we come out of this W Loop and return our nums of the left side which after everything is run that whatever is in here should be your smallest number in the array as you could see all test cases passed so this would be a more efficient solution because you don't have to go one by one you would split the array and look on one side or the other side which that would basically be an algorithm that runs in this in log in time which is more efficient than the brute for solution which was all of then as you would iterate through each and single each single number in the array okay so for this I will be trying visualizing the first Solution by using this tape what got set up right here so the first thing we did in the problem was create a Min variable which is which we set to the max value of n which would be 2 to the 31st power then after we do that we created a for Loop where we start at index zero and we check to see if whatever is at spot numbs ofi which is 26 is at less than our men and if it is we update it to whatever is at that spot and then after we do that we go back to the for Loop and keep iterating until we find something that's smaller so it's 27 less than 26 no we move on and so on until we find a number that's smaller and then we replace it and we keep going until the end of the for okay so another example is where let's say the smallest number would be in the beginning we would start by starting at index zero and checking to see if that is the if that is less than what is in our men and if it is we just set it and as you could see the first number was the smallest so a computer doesn't know that and it has to go spot by spot checking to see if this if would be true or not so it would basically waste all its time searching through this when it's already found it to answer in the beginning so we would be wasting a lot of time running this code okay so for this part of the video I will be trying to visualize the second solution which is the binary solution so first we created a left and a right which our left we set it equal to zero and right which is the length of the array minus one and this length is8 so 8 - one is seven then we enter the while - one is seven then we enter the while - one is seven then we enter the while loop where we create a middle or we do left plus right 7 + 0id middle or we do left plus right 7 + 0id middle or we do left plus right 7 + 0id 2 is 3.5 but since we're using ins we 2 is 3.5 but since we're using ins we 2 is 3.5 but since we're using ins we use integer division so we round down which our three will our mid will be three and then we check to see if this if statement is true if nums of mid which is basically 0 1 2 3 28 is 28 less than whatever's on our right it's not so we do left equal middle + middle + middle + 1 which is going to be 3 + 1 which is 4 1 which is going to be 3 + 1 which is 4 1 which is going to be 3 + 1 which is 4 so our left side is now four so 0 1 2 3 4 anything up to that 29 gets deleted so we don't search it again and as you can see we don't have to go to search those and now we only have to deal with these four then we go back to the start of the wild Loop is left less than right it is and then we do 7 plus 4 11/ by two is and then we do 7 plus 4 11/ by two is and then we do 7 plus 4 11/ by two that's 5.5 again integers so we our mid that's 5.5 again integers so we our mid that's 5.5 again integers so we our mid is now five then we check to see the if statement numbers of middle which is 0 1 2 3 4 5 is 22 less than one turn our right it is so we do right equals middle which is five so we cut these two off and now we're left with only these two go back to the while is left it is this while is still true so we keep going middle left plus right 9id two it's 4.5 again integers mid is now four so if nums of middle is less than numbs of right is 0 one two three 4 is 29 less than 22 it's not so we go to the left and 4 + 1 that's five is five less left and 4 + 1 that's five is five less left and 4 + 1 that's five is five less than five it's not so we exit the W Loop and return numbs of left which is basically 0 1 two 3 four five 22 so that's how we would get 22 and a more faster and time efficient solution than the first solution we used
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
383 |
okay so let's talk about rinse and no so you're given two string original and magazine so you have to return true if the ringtone can be construct from magazine and force otherwise and later each letter in magazine can only be used once in reasonable so if you look at example right if the one is pretty simple it's definitely false example two is false because there are two letter a but uh you only have one in magazine right this is why you do return false and example three easy you have two a and your two a right so let's talk about how i do it i will use the in the rate to store the number of the later the frequency in my in array so i'm gonna code new range 26 okay so uh so the constraint actually till you only can consist of lowercase english later so uh what i would do i would traverse the stream magazine first and store it into my in the rate and later on i would traverse the ring and rinse and note and to see if i had the frequency number to deduct if not i will return false so three um here's it so in i could you i less than a plus um i do have index and that's equal to magazine or add a i subtract by the killer a and go into my in array and i increment by one because this is the uh frequency count frequencies count right then i need to you triverse brings the note uh rinse and note dot 30. and this is going to be exactly the same idea but i'm using a rinsing note instead and i will have to find out if my array index is actually equal to zero i will return false others while i would just decrement by one because you need um you need that character to beat the dot otherwise when you look on the second one right um there is a problem right so at the end it just returns true this is how i actually did it and let me run a code and all right i do have problem so i less than sorry i less than answer notes that length and here we go and pretty good so let's talk about timing space so for the time it's all of them right you can't uh okay it's not all of them it's a maximum between the magazine string and rinse and note so it's out of m or either all of our right so i mean you know my idea which one is longer than that will be the time complexity first space is constant is 26 and that will be the solution and if you liked the video leave a comment leave a like if you want it and subscribe channel if you want and i will see you next time bye
|
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
|
387 |
hey everyone today we are going to solve the question first unique character in a string okay so let me explain with this example so for this question what data structure do you use my answer is hashmap because uh we want to keep two information one is each character and the other is frequency so um let's say uh freak and uh so let's focus on L and how many times one time right and how about e how many times so one two three right and how about t one time and how about c one time and how about d one time we will create a this hash map and after that we have to find the first unique character so uh e is definitely out of Target right because we have three times but l t c and d are unique right so how can we find a unique first unique character it's simple um we iterate through all character one by one again and then um check current character is unique or not and uh if we find a unique character for the first time so that character is a first unique character so let's iterate through one by one and first of all l actually L is only one time so that means L is a first unique character right so that's why we should return current index number so that means zero okay so let's write the code first of all create a hashmap freck and then so let's iterate through all character one by one so for C in s and uh freak and the key is character equal one plus um freak do get and the key is character and the default value is zero and then we iterate through again but this time we need a index number and a character in enumerate and S and then if freak and c equal one in that case that is a first unique character so return current index number if we don't find a unique character we should return minus one yeah so let me submit it yeah looks good and time complexity of this solution should be order of n where N is a length of input string and the space complexity is o1 so constraint said s is consistent of only lowercase English letters so that means um at most order of 26 right so simply o1 and uh yeah I'll show you another solution um so time complexity and the space complexity is are same but uh it may be uh useful for you okay so let's write the code in the second solution we use asky value and first of all create a freak and initialized is all zero and multiply 26 so 26 is coming from number of lowercase English letter and then after that iterates all character one by one and freak and we have to um calculate the index number to do that we use ask key value so or D and uh C so current character minus or and a plus equal one and after that so for I and C in Miner rate and S and if freak and uh so we use same calculation equal one so return current index number if not the case return minus one yeah so let me submit it yeah looks good and the time complexity is o n and the space is order of 26 which is 01 yeah so that's all I have for you today so please support me with your action such as comment and hitting like button I'll see you in the next question
|
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
|
766 |
hey everyone today I'll be doing another lead code problem toplets metrics 766 this is an easy one given mnx MXN Matrix return true if the Matrix is topless otherwise return false so Autoplex Matrix is a matrix in which diagonal entries are the same three two one four five all the diagonals entries are the same so here it is not the same will be turning false so that's it we have to return true or false if it is not so that's it so let's write our function which will be just checking the diagonal is diagonal okay which will be taking the row and the column yes and we'll be returning a Boolean these are ends so just say they aren't okay so we'll be taking the value of the certain you can say Matrix so a matrix at Matrix at rho and column because we have to compare it later so while uh for while our row is less than the length of The Matrix so the length of the Matrix will give the length of the Matrix obviously so it will be uh having the length in this condition is going to be 3 so Matrix and the column should not exceed also so the length of Matrix so we can get the column by just taking the index for zeroth index you can take any and this but we will be taking the zeroth index so now we know if the value is not equal to Matrix at row and column then we are going to return false okay this is done now we have to do things so we know that whenever we have a diagonal we are going to increase our row by 1 and also our column by 1. so this was 0 this is 1 this is going to be 2 yes it is going to be 2 so row is incremented by a 1 and column is also incremented by one and after all of this we can just return true if there is no false you can say detect it so now we know we have a diagonal uh entry that is diagonal in the whole Matrix now we have to check it for the whole Matrix so for column in range we will go till the length of Matrix at 0 so we'll be checking the first row basically and if not is diagonal okay passing it the row 0 because we are starting from the column 0 and uh call row 0 will be passing the column is passed and now we can just return false because we are using or not here if it is returning true then obviously it is going to return if it is not returning true then obviously we are going to return false we are done with the column now we have to check it for this 5 and 9 so we'll be incrementing our column so for Row in range I will be starting from 1 because we already checked the zeroth row we can't go from zeroth row but we'll be starting from one because we already have done the other part till the length of Matrix doing the same if not is diagonal passing it the row and column 08 this times because we are going in this direction up to down uh yes up to down so we'll be using the column 0 and returning false also here if we find a value that does not match its diagonal so that's it and after doing all of this if we didn't return false then obviously we are going to return true so that's it let's see if this works or not this works and let's submit it
|
Toeplitz Matrix
|
flatten-a-multilevel-doubly-linked-list
|
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._
A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements.
**Example 1:**
**Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\]
**Output:** true
**Explanation:**
In the above grid, the diagonals are:
"\[9\] ", "\[5, 5\] ", "\[1, 1, 1\] ", "\[2, 2, 2\] ", "\[3, 3\] ", "\[4\] ".
In each diagonal all elements are the same, so the answer is True.
**Example 2:**
**Input:** matrix = \[\[1,2\],\[2,2\]\]
**Output:** false
**Explanation:**
The diagonal "\[1, 2\] " has different elements.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 20`
* `0 <= matrix[i][j] <= 99`
**Follow up:**
* What if the `matrix` is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
* What if the `matrix` is so large that you can only load up a partial row into the memory at once?
| null |
Linked List,Depth-First Search,Doubly-Linked List
|
Medium
|
114,1796
|
1,887 |
hello good morning uh guys welcome back and you can see there's something different in this new theme just let me know what's you what you think is different uh we'll be solving the question reduction operations to make an array element equal uh it has been asked by Microsoft right not quite a lot but yeah it has been asked so we'll see what the problem says and then we'll go on to the intuition wise how it can be solved so just says that we are having an integer nums and your goal is to make all the element in nums equal so ultimately I want to make all elements in nums as equal now what how I make it uh I can do the following operation in this order how I have to find the largest value in nums okay uh that's first operation again remember largest value in nums is the first operation and then let's say its index is I and its value be the largest if there are multiple elements with the largest value pick the smallest index okay smallest index we have to pick that is one thing which we are saying we have to do but let's see if it is actually affecting us or not now find the next largest value in the nums which is strictly smaller than the largest value which again it should be strictly smaller than the largest value if the largest value is five it cannot be five itself even if in my nums I have five but it cannot be five it has to be four or may be less right now reduce the nums of I which is the largest value to actually the next largest value which is the just a strictly um smaller value return the number of operations to make all the elements as num equal now I want to the number of operations to just make all the elements and nums as equal now one thing is for short I'll just do exactly what the question says I'll take a five and then I know that my five needs to be replaced with a three okay firstly as per problem say I have to take the largest element if I have this array with me what is the data structure I can use to take the largest element I can use a priority Q I can use a set I can use a map right standardly to find to take the largest element we usually take a priority Q or a set so let's take a priority Q Maxi so I'll grab a five I know that this five needs to be replaced to the next larest element which is actually a three so I know I'll just grab in my par it would look something like this I grab the top element five I'll grab the next element which is top three I know that five needs to replace by three okay I'll just have a three I just have five and three I'll replace five with a three I know operation one has been performed my answer has been increased by one and I just push those both of these back into my priority Q it will become a 3 three now again if I just ask the priority for the top element it will return me a three but the next small element will also be a three so rather than just pushing three rather just say one thing okay I will have a pair of element and it's count so every time I let's say one was there so it's count was also one so every time I'm just pulling out an element so I just know okay it is a next largest element I don't have to pull it multiple times out right and push multiple times in so I'll just pull it back out I know the top element is actually a three with a frequency of two remember that and also the next top element is one I know for sure all of these thre need to be converted to a one which is the next smaller element so I just convert that to a one so operations required two because I had two threes so answer is plus two so answer is three for sure as simple as that I just did exactly what the question was saying let's have a quick check with this example 1 one with a frequency of three it has just one element it has no next smaller element for sure just stop right here and return answer as zero nothing happened here we'll just do same thing we'll just firstly have a count of every element frequency I'll just have one count as three sorry two uh two's count as again a two and three counts as one and for sure our priority will only be sorted on the basis of their uh values so I just grab the top two elements from the priority Q I know that the three needs to convert to a two I'm only concerned about the three being converted so I just add a one in my answer which is my three got converted to a two okay this will go away the frequency of two will actually increase by one of the three which what which got as you saw that it was two right three frequency was one you know this three got converted to a two and all these threes as in all these ones which means the frequency of three got converted to a two so just add this frequency in the next element which is actually two so I'll just get a two as new frequency as three because I remove both of them I push back the two only now I have these two as the top element I just remove two okay and I have to I know that I have to make it as one as the nums so I'll just make all of these three as one so I'll add a three because I know that Transformations are done on top of these two element of the value two and on these three elements again this is gone I had just one element remaining with the frequency of five voila we are good we are done that's what you have to do in this entire problem and the answer is four so you will see that you are using a priority Q right so the operation is nothing but n log n right so the operation is n login so again uh when the entire thing is done firstly you will use entire map kind of an map you can use to actually map the frequency which will take a o of n operation and then you are simply using a priority Q to just pop out push back all the elements iners case so time will be o of n plus n log which is n login oh that's fine uh space will be okay uh for using a priority Cube um you will have some n elements in that particular priority at point of time okay that's cool but you also know that you are also using uh you know map to actually map the stuffs out which is frequency to like element to the frequency for sure you also need a space for that so that's o again in operation so you are using space time can we improvise it like firstly can we improvise it maybe we cannot but let's see how we can improvise it firstly the intuition was nothing much more we just actually solved what the problem was saying itself but you saw that we are using a map we are using a prior Q maybe it is overkill as in what we are doing actually was we if we had a 3 22 1 we ultimately know one thing firstly we have to take from the maxim element so I will have to sort it in the maximum order which is either sorted in the reverse order or maybe you can just sort it in Ascend also and go from the back now when this is the ARR I have I know that I should be knowing okay what is the count of this right or rather I should say okay what is the count of this is Sir one now just simply add in your answer the one because you know as this 3 to two is going for sure I'm converting this three to a two so if the count of this three is one simply add in your answer as one because you know this three will get converted to a two now you will simply go on now you know now this two and one came which is a difference came in so you know for sure this entire thing will get now you know as this three got converted to a two so it has also become a two so I'm just keeping the count of whatever I have got previously now again this transformation which is 2 to one has come so for sure add a one add a three for it which is 1 2 and three okay I add a three for it and simply again it will just keep on going ultimately it ends it never got the transformation again which means okay something is there and next it's something different we never got this kind of stuff so okay good so the answer is actually a four so ultimately what we did in this question was we just simply have another variable as count rather than we have rather than taking priority and stuff we will simply first sort in the descending order or maybe ascending but go from the back but we will sort in the ascending order we'll go from the starting itself we will keep the count okay the count so far is one oh bro as soon as you get encounter something different which is I and IUS one nums of I and nums of IUS one if it is different friend bro please add this count in your answer count was one so far so I just add that in my answer become one now simply keep on going okay count will increase by one I keep on going count will increase by one count has become so far three keep on going now firstly as I am saying I keep on going I just check nums of I num of IUS one it was same as it is I and IUS one it is different bro please add this count in your answer cool bro I added that count okay cool Count has become four count has become five but yeah it has never counted something else which as I is different so please answer is four so that's how with just o of n login because for short you are doing a sorting and it is a time and space is nothing but login but for sorting itself you need a space itself internally that is the ad hoc space which is which sorting needs so for sure login will actually be countered in that case as well but yeah this is the more optimized way to solve this problem cool let's quickly quote this up it's pretty simple logic intuition start from the priority q and then it goes down and try to reduce the space with this fact cool now let's quickly solve this up so as we saw earlier also that firstly we will have to sort this entire stuff out now I'll just sort it in the descending order now to sort descending order we just do a r begin right be G now uh it is our end now uh when everything is sorted uh now we want we know that the answer will be zero initially uh we will have a count initialized with one because I want to compare I and IUS one so for Zer I will never go onto it so I'll just initialize with the one and I will also have a n for Simplicity and not writing num. size again and again so as I showed you I'll start from the one itself and not from uh zero so that's the reason I just have a count already as one so I'll just check okay nums of I if it is not equals to nums of IUS one oh bro then I have to add this count in my answer I just add that in my answer and then I'll just simply again increase the count because at every step I have to for sure increase the count and ultimately I can just return the answer let's quickly compile this up uh it should work if you have no typos and stuff So yeah thank watching again byebye
|
Reduction Operations to Make the Array Elements Equal
|
minimum-degree-of-a-connected-trio-in-a-graph
|
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3. Reduce `nums[i]` to `nextLargest`.
Return _the number of operations to make all elements in_ `nums` _equal_.
**Example 1:**
**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.
**Example 3:**
**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 5 * 104`
|
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
|
Graph
|
Hard
| null |
546 |
hey what's up guys this is john here so today let's take a look at uh 546 remove boxes it's uh i think it's kind of difficult dp problem okay so you're given like several boxes with different colors represented by different positive numbers so each number represents a color and you can remove any of the boxes okay until there's no box left so each time you can choose some continuous boxes with the same color and then after removing that colors you know you get the uh the k times k point and it asks you to find the maximum points you can get right so for example this one and so we have like this three twos together right so basically if at the first round we remove any of the two here since we have a three tools uh dot together that's why on in the first round move we got three point three points right and after removing the three tools here we end up we ended up like this one here right and then next the next round we're removing four here right so by removing four here we get one point one times one and then the next time we have like these three threes together and by removing those three numbers we get 3.3 again right in the end we have two 3.3 again right in the end we have two 3.3 again right in the end we have two ones together and then that's 2.2 right so in total we have 23. 2.2 right so in total we have 23. 2.2 right so in total we have 23. that's how we get this number here all right and then we have a several boxes uh the length is it's not that big only 100 right so then the uh so to solve this one by using dp you know the you know i mean at the beginning you know someone may we might start thinking about dpi inj something like that right so i and j means that starting from i to j right what's going to be the maximum point we can get right from starting from i to j okay but if you read this uh the descriptions again right or carefully you know that right so by giving this i and j we don't know like let's say if the inj is here let's see if the inj is too 2 3. let's see this is the ing we cannot simply do a like a check right only within the range of i and j because you know since we have two here you know we have another two before i here and if we only check the string uh the array i and j here we see two twos here right so we're seeing okay so by removing any of those two we will get two times two but the but it's not right so by removing any of this two and two we are getting actually three points three times three it's not two point two so then it means that i and j is not enough so which means we have to introduce a third dimension to help us solve this problem so i mean i think we have already seen a potential candidate for the third dimension which is the uh like how many numbers the same numbers that's i mean it's the same as a current i so i'm going to call it inj and the k here so k means the they're like uh k numbers case same color right as i right so for example this one we have i and j here so which means so the dp i and j and the k is that basically the k will be one it means that before i there is a one additional two before i so that we can that can help us like get the correct numbers by removing all the numbers here right all right so once we have that you know the actually and if we have the definition here and then the next thing we need to figure out is the state transition function right and actually that state transition function is even trickier than the state definition itself so and i'll give you some examples here so let's see what i'm drawing like a example so let's say one two three four uh two one three four all right so and let's say we have a i and j and let's see i's here right let's see i's here and j is here how about that okay so let's see there we are trying to calculate this i and j so by i mean when i when we're trying to get uh come up with the state transition functions we always try to split i mean the current problem into a smaller size of problem that's how this dp works right and if give by given like this i and j and by given like there is case same numbers before i how can we split these numbers into a into the smaller version of number that depends on like basically we're trying to see how many like uh between those between i and j how are we going to remove the numbers right actually you know if you if we go through if we're going through these uh examples a few more times we have might already find out actually there is a strategy here right basically you know we're trying to get okay we're trying to get the uh we're trying to make this uh the same numbers the as most as big as possible that's why when we're at this one we're at this state here we're not removing three and three but we are we're removing four here because after removing four here we'll have like three and three we'll have three together that's why they can kind of guarantee us to get a bigger number right so i should be so basically within each of the state here we do have like a greedy approach here so what's going to be the great approach uh actually there are two ways of doing that there are two options you know the first option is to remove the current one the current eye until we are reaching the uh another a different numbers so which means that for example this one i and j the first option is which will be uh basically we're trying to remove the we're moving the eyes until we have like we meet encounter different numbers then we have the total counts right of three here so that's going to be our first options to remove right that's gonna we removed this part until we have reached encounter a different number and second thing second and the second options or other options is to remove what is to remove we just keep going to the right side until we have seen we have fined uh i mean after we have find this location right we're going through the right until uh until we reach j and we'll find if there's like another two on our way right so for example if we have this number where let's say the current is here right after finding after moving to the right until we reach a different numbers right and then we're going to through to the right side until we find an another a two here right so let's say this i am here so why is that like so like i said right i mean it's because we're trying to remove this part after removing this after removing the parts in the middle then we'll have like the we'll have the have like the uh a longer twos because we have already have two here and by having another two here right basically we'll increase the next point the next length up by after removing this three four three here so and that's going to be our second strategy basically every time when we see an another like two here we will uh try to remove anything that's in between so that we can have like a different uh the next one so and with the uh with a longer two here with a longer length of the same number then the actually the uh the state transition function will be like this you know so let's say we have like the uh dp right so dp i j and k so i'm going to type it here so basically the dp i j and k right equals to what equals to the uh so the first option is this we have like we need to remove this one first right that's gonna be uh the dp of what the uh let's say i right so let's say we have a this is ii right after going through this the first one at the first while loop here so we have dpii and then j right and then equal to zero because after removing the i mean after we move this part here we have like we have three here right so which three means that there's nothing before three because remember we have already removed er everything that's outside of i and j so even though we have a three here you know but the three was already gone right so it will not affect the three here that's why after removing this after removing anything that's before this i and i we have dpii j and zero plus one plus account right count uh the power of two so that's the first uh option and second option is that we have from here from the ii until j here we'll try to find another number that has the same number as a two here that's why we're going to have like what the dp i and j and another one is like the dp of i right to what to m minus one and then zero right so if we decide to remove anything i if we decide to remove the thing in between i and m here basically uh we have this is going to be another a sub small sub problem and the starting point is i and i here right and the ending point is m minus one right because we want to keep this the current atom here because the same number as a two here that's why the starting point and the ending point is i and to the i minus one and the same thing right so for this kind of sub problem you know it's also like still the zero because three there's not there's no there's another there's no more threes before the current i here that's why it's that's that right and what the other one is the uh any that's something that's after anything that's after this one right so what do we have uh let's see what do we have like the dp starting from amp right starting from m to r and then the is the k plus the uh the count right so you know this part is also kind of not too difficult to understand right so basically we're starting from m and then we are like uh until to the to this j here sorry this is j right so why is that because now we only need to consider in this part because after removing this part in the middle we know that you know that we have like from here to the left we have like k plus count number of twos right on the left side that's why we can basically and convert this part into our definition again right so now we have starting from m to j right and but the count is basically the k plus count so that's why we convert we split this it's i j and k into a smaller version of problem and that's how this dp will work and after figuring out all this kind of uh dp state transition function here i think all is left is just uh some implementations so okay so let's start doing that so we have dp with i and j we have a k right so same thing we're going to use this uh the python's built-in cache the python's built-in cache the python's built-in cache functionalities can which will can save us a few lines of code right and then in the end we simply do a start from zero and the length is the uh the endpoint is the length of boxes minus one right and then at the beginning k is zero right so and okay so let's do a hmm let me think and i'll do i equals to i here you know so that we can uh you can keep this i later on or we can use the same thing but i just want to make them like uh separate so the way so like first you know we find the consecutive you can consecutive numbers right from i starting i right and we have a count equals to one and the uh ii class one right so that's the beginning because we wanna do a while loop here anyway i mean there are like different ways of doing swag up here but this is just my way of doing it you can just do it your own way it's fine so while ll is equal to the same of r right that's the and the boxes of i uh equals to the boxes of the ii minus one right so if that's the case do i plus one and then we do a count class one right so that's that now so the first option right option one right is to remove the uh the current number the current ith number right and the way of doing it is going to be a dp of the ii to the right after removing the uh the current ice numbers we have this ii right to r and then we'll be having gonna be have a zero of the case and plus k plus count we do a power by two right because you know by removing the current i here it doesn't really matter because we don't have to try the other ones uh try anything between the i and i because they will give us the same results that's why we are only just removing the current ice number right and by removing the current ice numbers the remaining part was starting from the i and i right and then it will be ending to uh to the right side to sorry to j here okay i think i'm using this j here and then the uh the point we're getting by removing the current ice number is this one okay and then the option two right option two is to find the same number right starting i and i okay so now we have four i'm in the range of i right to the j plus one right and then if the boxes of the m is equal to the same to the boxes of i right because i is the numbers we're trying to look for right if that's the case right so we have into a max of answers of the uh so the first one is by removing anything in the middle right it's going to be the ii right to m minus one right that's something in the middle so remember we have this kind of uh one three two right three four three two one three four right so let's say we have i here this i'm gonna i'm drawing this one more time just to make sure you understand the state transition function here so let's say we find another two here right that this is gonna be our middle here right so the next the second the options we're doing right here is that okay we decided to remove this part three four three which is the i to n minus one and then the k will be zero right so oh sorry i have to do a dp here it's not it's the uh we're doing like the top down so okay this is the j and zero right so that's the first one and how about that's the lap anything left is the m to j right it's gonna be dp of m to j and the con will be k plus count right and then yeah there you go that's gonna that's it and then in the end we simply return the answer and don't forget to do a base case so the base case is if i is greater than j right we return zero which means nothing yeah i think that's it so if i run the code yeah accept it and it's accepted right so yeah i mean so that's pretty much it is and a time and space complexity right so for the time complexity we have i and j you know let's say we have an n here right so we the i and j there are both are like the p the possibilities for i j and k i think that's n to the power of 3 because we could have one different i or 100 i 100 and what for each of the i and j we could have a different uh number of 100 up to 100 different possibilities that have like a the same numbers of i that's why the uh for this dp and i if it's for the state we have n to the power of three and within each of the dp functions here method here we have uh yeah basically we're doing like a for loop here right so we have a n here and then we have another end here yeah so in total it's going to be a n to the power of four that's going to be the time complexity of that right and for space complexity it's a state of the dp right it's going to be the oh of n to the power of three cool yeah i think that's it for this problem and yeah i think this is a pretty hard dp problem especially you know i mean especially you have to come up with a third uh dimensions and after the third dimensions you also need to uh to somehow come up with i mean the first option is kind of straightforward but for second options you have to be able to find the pattern right so it's a little bit of gritty approach here you know we're only trying to remove the things in the middle if we find another match for the current ice number right and then just keep doing it until we find the max number all right cool guys i think i'll just stop here thank you so much for watching this video and stay tuned uh i'll see you guys soon bye
|
Remove Boxes
|
remove-boxes
|
You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
Return _the maximum points you can get_.
**Example 1:**
**Input:** boxes = \[1,3,2,2,2,3,4,3,1\]
**Output:** 23
**Explanation:**
\[1, 3, 2, 2, 2, 3, 4, 3, 1\]
----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points)
----> \[1, 3, 3, 3, 1\] (1\*1=1 points)
----> \[1, 1\] (3\*3=9 points)
----> \[\] (2\*2=4 points)
**Example 2:**
**Input:** boxes = \[1,1,1\]
**Output:** 9
**Example 3:**
**Input:** boxes = \[1\]
**Output:** 1
**Constraints:**
* `1 <= boxes.length <= 100`
* `1 <= boxes[i] <= 100`
| null |
Array,Dynamic Programming,Memoization
|
Hard
|
664,2247
|
153 |
hi guys welcome to yet another video of course from scratch so proud of you for showing up every single day consistency is very hard for me also i am managing two channels installing in everything so it would mean so much to me if you could like motivate me by sharing the channel with your friends motivating them also to start consistently practicing every single day with us i hope you're liking the content i am trying to take all the feedback i'm trying to clear all your touts one by one open to all your feedback always please do motivate me and each other by commenting liking sharing it would mean a lot to me let's look at today's question so it's very similar to yesterday's question but there's a little change and actually this question is asked in multiple ways so i thought it is like something that we should cover because you know from this you will get the idea of how questions are tweaked a little bit and asked in the interviews so for example here the question is that minimum number in a sorted rotated array so again we have an array which was initially sorted rotated at some particular point okay so for example this is what we have so sometimes the question can be that you know instead of returning the minimum number return the number of rotations that have been done in the sorted array so that actually means that you know we had a sorted array and now we are doing the rotations one by one so what is the number of rotations that have happened to finally generate the array that is given to us so that actually is same as returning the index of the minimum number sometimes if we ask to return the index sometimes it will be asked to return the number itself sometimes you will be asked to return the number of rotations it's all the same question which is the question that we are going to do today so let's look at it see in the example given to us the array is rotated once anti-clockwise so the minimum element is anti-clockwise so the minimum element is anti-clockwise so the minimum element is at last index so this once could be the answer the number of rotations or in this particular question we are asked the minimum number itself not the index so that is what we are going to return so usually what we have to do we start with you know calculating the lower and the higher point and then we keep reducing the search space here instead of the size of the array we are given the lower the high points itself and here the expected time complexity is given to us order of log n and the expected auxiliary space is also given order of log n let us take this particular example to understand here you can see this is our array that we are considering our original array would have been one two three four five six seven eight nine ten it has been rotated around the pivot ten so now our minimum element that we have to return as the answer over here is one so now let's make some observations to try and understand what we can use to you know come up with the solution what does minimum element mean let's focus on that first what does actually minimum element mean it will be basically the only element in the array for which the previous element will be greater than the element itself right because see this part will always be sorted there will be only one element present where the previous element will be greater than the element itself and that will be our answer that is the minimum element that we have to return so this is the observation number one why there will be only one element because the question it is given to us that there was a sorted array which was rotated at one point so there is only one minimum element that is possible and for that particular element the previous element will be greater than that element so that is one observation the second observation that we have is similar to actually it is exactly same to what we did in the last question so if you have not watched it i recommend you to go watch it but if you haven't we will be covering it now also so whenever we pick any particular element we know that element is going to divide the array into two parts now one part of the array will always be sorted and the other part of the array will not be sorted why because we have rotated the array around one point so if the minimum element exists on right side we know that the left side is sorted so if this part would have been sorted we know that the answer is on this side so again see in the last question when we were searching we had to actually see that okay where our answer exists but in this question it's actually much simpler because whichever part is sorted we know that our answer is going to exist in the not sorted part in the other part see if we were not considering 9 if we were considering say 2 we know that this part is sorted and this part is not sorted right so i we know that the part that is not sorted that is where our answer is going to happen this is any way sorted so the here the answer will not exist right we are looking for the point around which the entire rotation happened the minimum element right so this is what we are looking for one so here our main catches firstly our answer will exist in the part which is not sorted secondly our answer will be the only number for which the previous element will be greater than the number so to quickly revise it once say this is the array given to us so if we pick the middle element we know that okay this part looks sorted because this number is less than this number and we know that okay this number is not less than this number so okay so this part is sorted and this part is not sorted so our answer is not going to be here answer is going to be here so we reduce our search space to this part now and we start searching over here we again take the middle point and we see whether this part is sorted or this part is sorted we know that the right part is sorted so now we reduce our search space to this part we again take the middle element and we see that okay this is the answer how is that the answer because the element is smaller than the previous element right and this is the only element where this happens so this is our answer so this was the entire concept of the question but there is one edge case so before moving ahead i want you to think about it yourself what is the edge case that is possible okay and now when i tell you should tell me the comments whether this is the edge case that you thought of or not because now we have done some questions now you should be able to think of edge cases yourself this concept building is fine we are doing this but in interviews we're coming up with edge cases is extremely important so i want you to think yourself and come up with edge cases not just me telling you because then it's not that useful as it will be when you yourself will come up with the cases okay so the edge case that i was talking about is that the minimum element is actually the first limit itself see the if the array was 1 2 3 4 5 6 7 8 9 10 itself then we know that the first element itself is the minimum element and why is this an edge case because here what was the condition that we were taking for h k is that the previous element is greater than this element right but in this case there is no previous element for this element and what will happen whenever we take any middle point this left array will also be sorted and the right array will also be sorted so basically both the paths are sorted so that is why our first element itself becomes the minimum element and we can return from there itself so in the question it is given to us that the array was initially sorted and then we rotate it now how many times it is rotated at one point so here it is rotated at point 10 but see there are if we see like one time rotation we are moving one by one then see here we have rotated four terms right from the left side to the right side now say we keep rotating again and again around one point itself we can actually come up with the original array itself which is this right to understand again say it like this here we were given that okay rotation has happened now rotation has happened around which point here it is 10 here also it is 10 only but here our first limit itself is the minimum element here our first element is in the middle right now in order to handle this case it is an edge case because whenever we take any middle limit both left and the right parts will be sorted for sure okay before moving ahead with the code let's quickly revise what are the points that we noted first point that we noted was that our answer is going to be in the unsorted part right and what is the case for the minimum element that the previous element will be greater i apologize for my handwriting it's really weird to write on ipad but yeah so the answer will be on the unsorted part and the minimum element will have previous element will be theta and also there is an edge case basically in that each case our first element itself is the minimum element and when will this case happen when both the sides of the arrays will be sorted so whenever we take any element both sides will be sorted for this case right now let's start writing a code let's get to the code part now here low and high point is already given to us so let's just write a while loop so while low is less than or equal to the high point and let's calculate our mint value and how is that calculated i hope all of you know this now so low is low plus high minus low by 2 okay so this is how we have calculated the middle point so when do we have our answer first let's see when will mid be the answer and we can return it there itself so for that what is the condition that the previous element so array of min minus 1 should be greater than array of min so if that is the case then we know that we have our answer and we can just return what do we have to return the index or the element we have to return the minimum element so that is why we are going to return array of mid okay so this is when we have found our answer now when we have not found our answer we have to see whether the left part is sorted or whether the right part is sorted and our answer is going to be in the non sorted part okay so when are we going to reduce our space to left side or right side so let's see when the left side is not sorted we are going to move our source space to left side when the right side is not sorted we are going to move our space to the right side when the left side will not be sorted if basically array of low is greater than array of mid then we know that our left side is not sorted so if it is not sorry that we know then our answer exists on that side so that is why what we are going to do we are going to move our high point to mid minus 1 okay now else if array of basically mid is greater than array of high that means our right side is not sorted so in that case what are we going to do we are going to move our space to right side so for that we are going to do low equal to mid plus 1 okay now why have i written the else if condition is not just else so in the previous question we did that okay if one side is not sorted the other side will obviously be sorted right but here there is a case possible when both the sides are sorted for sure okay in that case our first element itself is the minimum element and that we have to return so if both the sides are sorted we know that the first element that we're dealing with itself is the answer so what do we just uh sorry s return basically array of blue okay so this is our code but we also have to have like a written statement outside so i'm just adding return minus one and again this one edge key is missing again before i tell you i want you to come up with it yourself have you thought about the case that i'm missing if not think about it and once i tell you tell me why did you miss it because we have discussed similar cases in the previous videos this is how you will learn do you know notice similar edge cases again and again so if you have not thought of it i want you to tell me the comments why you think you missed it and if you have thought of it i wanted to give yourself a pat on the back in the comments okay so here array of mid minus 1 i took if i am taking min minus 1 we can go out of bounds so we have to make sure that if mid is equal to zero or area of min minus one is greater than area of mid we write an array of moment so what if say there was only one element or if the middle element turns out to be the zeroth element then there is no mid minus one if we do this we can go out of the bond so if this is the case we just return it and we do not check this condition at all right so let's try to compile it this is right let's try to submit it so we have passed all the test cases i hope you understood the question properly and i hope you understood the variations by which this question can be asked if you have any doubts let me know in the comments i will definitely pick it up and do show up tomorrow really excited to see
|
Find Minimum in Rotated Sorted Array
|
find-minimum-in-rotated-sorted-array
|
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become:
* `[4,5,6,7,0,1,2]` if it was rotated `4` times.
* `[0,1,2,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_.
You must write an algorithm that runs in `O(log n) time.`
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 1
**Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times.
**Example 2:**
**Input:** nums = \[4,5,6,7,0,1,2\]
**Output:** 0
**Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times.
**Example 3:**
**Input:** nums = \[11,13,15,17\]
**Output:** 11
**Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* All the integers of `nums` are **unique**.
* `nums` is sorted and rotated between `1` and `n` times.
|
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go.
Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
|
Array,Binary Search
|
Medium
|
33,154
|
1,865 |
hey everybody this is larry this is me going with q3 of the weekly contest 241 finding pairs for a certain sum so this one to be honest looks like a really hard problem and you should go to my discord channel or hit the like button hit the subscribe button we could chat about it uh but no but this one was kind of tricky i think and it could go many different ways i think the way that i was initially thinking about was like some sort of real binary search but note that there's an adding a positive number which makes it a little bit awkward because a dynamic data structure and stuff like that you can still probably figure something out maybe um but it's a tricky problem i don't know if i know how to solve it in a reasonable amount of time but that's why you have to look at constraints and this one is a laundry list of constraints and i think the one thing that surprised me a little bit when i was like okay let me take a quick look first is that numbers one and numster are asymmetric if you missed that it's gonna be hard to solve this one but um but yeah uh that means that numbs two is the longer way but also keeping in mind that number one only has a thousand elements and then the second thing i notice is that at most a thousand core to the count function add function i don't really care that much but the count well okay you could do ad reasonably fast anyway but the there's only at most a thousand calls to count that means that now it becomes feasible to have some elevation that for you to count loop you're counting a thousand times a thousand is gonna be a million which is gonna be fast enough for most things even python uh maybe a little bit foreshadowing but yeah so basically then it becomes bookkeeping and what i mean by bookkeeping because i get questions about this is that it's just about keeping track of stuff like keeping books of like accounting and like in accounting and you like keep track of where everything is uh making sure you put it back in a good place to take it out and all of that stuff that's bookkeeping uh it's just a it's just kind of keeping track of everything and this is basically my code so i just keep track of well for numbers away uh or for numbers one we keep tr well for both of them we keep track of the number of um uh the frequency so i use for a frequency table um f1 is just the frequency of all the numbers and numbers one f2 is just a frequency of numbers in f2 uh so for count let's go to account first count is very um naive it goes through every frequency or it looks at every number in the frequency uh in numbers one sub array uh we do it for the key so that it dedupes but the same idea is the same and then we just sum up the um some of the different pairs right there um because x plus total minus x is equal to total which is what your um what is the input for count that means that you know the x the this number uh numbers the number of x's on f1 and the number of total minus x on f2 so then you know you do a cartesian product thing and the number of cartesian products uh of course just this multiple right um so then you sum it all up and that's the answer um you know note that this is going to be n1 number uh number of keys so you know and this is all one for each loop so this is also going to be the running time right and because this is going to have q queries say this is going to be all of q times n1 in total in theory right and in space well we'll talk about space later and then the harder part um is keeping track of the ad right and here we just also just keep track very naively we have make a copy of the array for each index we look at what it used to be we make the delta we add the value and then now we have the new number right this is i think the code this is actually my contest code i think it's pretty self-descriptive actually self-descriptive actually self-descriptive actually um and then yeah and then in the previous variation we minus one and then we add one to the current number and that's basically all the bookkeeping you need to do um this function is not even worth analyzing because this is just o one everything is over one so if you have q curves this is going to be o of q time in terms of space um note that we don't use any extra space in count or add so all the space is going to be in the pre-processing step in the pre-processing step in the pre-processing step and this is going to be linear which is o of n1 plus n2 time oh sorry in space and i guess time too because we kind of de-duped them into uh of de-duped them into uh of de-duped them into uh frequency tables so yeah as well so yeah um so i think that's pretty much it i think if you have trouble with this um the number one thing is just look at constraints i think this is a really sneaky problem it's not a tricky problem per save you but if you notice this you'll be like oh yeah of course you try to optimize for numbers one and then you know it's just about putting all the constraints together i think the problem is not that interesting otherwise but yeah and once you do that then you could you know have complexity that are tailored for this particular set of inputs um that's all i have for this problem uh you can watch me suffer live during the contest next i think i did this one about like three four minutes um i had to i forgot to multiply it here i think and that took an extra minute or so but uh mistakes happened let me know what you think and watch me stop it live during the contest next okay no behind slow on the other one uh hmm so number two is way bigger than numbers one that's the big one okay now i have to keep track of it as well uh okay that's already wrong have i misunderstood it why'd i do four seven oh whoops this should be um okay now that looks good so yeah let me know what you think about today's contest today's farm did you have the same annoyingness that i had on stuff uh yeah hit the like button hit the subscribe and join me in discord talk about these things i will i try to do most of these so yeah stay good stay healthy i'll see you next problem and you know to good mental health bye have the best to stop on
|
Finding Pairs With a Certain Sum
|
checking-existence-of-edge-length-limited-paths-ii
|
You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types:
1. **Add** a positive integer to an element of a given index in the array `nums2`.
2. **Count** the number of pairs `(i, j)` such that `nums1[i] + nums2[j]` equals a given value (`0 <= i < nums1.length` and `0 <= j < nums2.length`).
Implement the `FindSumPairs` class:
* `FindSumPairs(int[] nums1, int[] nums2)` Initializes the `FindSumPairs` object with two integer arrays `nums1` and `nums2`.
* `void add(int index, int val)` Adds `val` to `nums2[index]`, i.e., apply `nums2[index] += val`.
* `int count(int tot)` Returns the number of pairs `(i, j)` such that `nums1[i] + nums2[j] == tot`.
**Example 1:**
**Input**
\[ "FindSumPairs ", "count ", "add ", "count ", "count ", "add ", "add ", "count "\]
\[\[\[1, 1, 2, 2, 2, 3\], \[1, 4, 5, 2, 5, 4\]\], \[7\], \[3, 2\], \[8\], \[4\], \[0, 1\], \[1, 1\], \[7\]\]
**Output**
\[null, 8, null, 2, 1, null, null, 11\]
**Explanation**
FindSumPairs findSumPairs = new FindSumPairs(\[1, 1, 2, 2, 2, 3\], \[1, 4, 5, 2, 5, 4\]);
findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4
findSumPairs.add(3, 2); // now nums2 = \[1,4,5,**4**`,5,4`\]
findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5
findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1
findSumPairs.add(0, 1); // now nums2 = \[**`2`**,4,5,4`,5,4`\]
findSumPairs.add(1, 1); // now nums2 = \[`2`,**5**,5,4`,5,4`\]
findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4
**Constraints:**
* `1 <= nums1.length <= 1000`
* `1 <= nums2.length <= 105`
* `1 <= nums1[i] <= 109`
* `1 <= nums2[i] <= 105`
* `0 <= index < nums2.length`
* `1 <= val <= 105`
* `1 <= tot <= 109`
* At most `1000` calls are made to `add` and `count` **each**.
|
Find the minimum spanning tree of the given graph. Root the tree in an arbitrary node and calculate the maximum weight of the edge from each node to the chosen root. To answer a query, find the lca between the two nodes, and find the maximum weight from each of the query nodes to their lca and compare it to the given limit.
|
Union Find,Graph,Minimum Spanning Tree
|
Hard
|
1815
|
424 |
complete code problem 424 longest repeating character replacement so this problem gives us a shrink and an integer k and basically we can choose or any character in a string and change it into any other characters right and we can perform this operation at most K times right so this is where the K comes in so our goal is to return the length of the longest substring containing the same letter after which we perform the substitution so for example for this ring since we can substitute two characters we will substitute other bb or a which will make all of them B's or all of them A's if you give us the result four right so that's a length the length of these four characters for this case since K is 1 we can only substitute one of the characters we would change either this to an a which will give us four characters A's or we'll change this into a b which will give us four character B by the way the output would be four okay my approach to this problem is to use a sliding window technique but without two pointers right so I only have one pointer which is I'll call it and I have I'm using a map to store the characters in my window okay so let's say now I have very full loop iterating through from the start of the string to the end of the string notice how I'm I made it into a list so it's easier to visualize but technically a string is just a list of characters huh okay so first character comes in it's an a all right so this count will basically store the most character in the window so let's say for example if my windows were to be like this count would be two right because the most characters is two the most of the same character is too long okay so for this instance since my window is only one character long my account would be replaced with one right which is this a after that I calculate whether or not this window have enough substitution to still be a valid window so what this means before the explain later but if we do the math result is zero minus count one so technically this will give us negative one and negative one is less than one okay the middle okay remember we implemented uh a here so it is so now our map looks like this after that we increment I have no one now we're looking at a and again we have to increment the basically the value the occurrences are of character in our window okay now I mean it looks like this right so let me just forward it again this is uh so increment a and then we see since 2 is more than one so count will be replaced with two and again uh oh just now I forgot to increment a result okay and since result is now one minus count will still give us negative one Which is less than k so our results we can increment again okay after that I becomes 2 and now we're looking at a new character right so this character if we were to look it like this we would know that we need to substitute B with a for it to be a valid window right so I have to call my account and since B is a new character so you have only one column in it and since my column is more than the existing character so the count doesn't change it will still remain too so calculating this again result minus count is still less than K right that means what we did is we have used up all of our substitution to make this into a valid window right we incremental result and then we increment our Point our printer so now we're looking at c a new character again we increment in our map our count does not change and if we were to do this Corporation 3 minus 2 is 1 right and one is not less than one so what we have to do is to remove the first character of our window and to do this we use the index which is where we are currently at and removing the result which is the length of the current window right now so this will bring us so this will give us the index of the first character of the window which in this case will be a so if we decrement a like this okay for that a window looks like this right okay again we increment I form this time we meet B right so increment B and now that we did that I'll count we'll see the same if I if we go to account this result 3 minus two it was all not less than okay with this one so what we need to do is to actually remove the first character of our window right in order for our window to continue expanding so remove the first character would be zero or zeros like this I have an increment I again so now we have five and now we are looking at this right okay again we calculate count and since count since B now has three occurrences in this window we can update our account which means that in this window the character that appeared the most B appeared three times right and if we were to use result minus count it is 0 is less than one so we can increment our result that means this window is valid right that means after that we increment our I again so now we're looking at a we count our count since 1 is less than three let's not do anything and if we were to calculate this 4 minus 3 is 1 and 1 is not less so then K which is also one so in which case we remove our first character almost our first character in the window which in this case will be C of which the for Loop ends right because we have already reached the end of the string and we return the result which is 4. for this example right that's all I have to show thanks
|
Longest Repeating Character Replacement
|
longest-repeating-character-replacement
|
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times.
Return _the length of the longest substring containing the same letter you can get after performing the above operations_.
**Example 1:**
**Input:** s = "ABAB ", k = 2
**Output:** 4
**Explanation:** Replace the two 'A's with two 'B's or vice versa.
**Example 2:**
**Input:** s = "AABABBA ", k = 1
**Output:** 4
**Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ".
The substring "BBBB " has the longest repeating letters, which is 4.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only uppercase English letters.
* `0 <= k <= s.length`
| null |
Hash Table,String,Sliding Window
|
Medium
|
340,1046,2119,2134,2319
|
850 |
850 rectangle area - we're given a list 850 rectangle area - we're given a list 850 rectangle area - we're given a list of access aligned by tangos each rectangle sub I is just the corners find our total area covered by all rectangles in a plane since the answer may be too large return a module some number Wow that's tricky okay sound about this example we have just other inputs it's 10 to the 9th wait so I don't know why do you well I guess maybe there's some language where there's no long like JavaScript is weird with dad so that's my name thank you mind but when I'd say my name is 200 ok guess the tricky thing is kind of forgot in this section and handling in this section in a good way I think the canonical way of doing it is actually summing core what is it caught a sweep line algorithm or whatever you're having sweep line probably solves this was it 200 so basically you have you can think of each rectangle as boxes that sentence just didn't make sense I just heard myself sorry but you could think of each rectangle as defense where and in each one you can maybe do you could do an O and then yeah and then that's probably sufficient and I might do something yeah I mean the end goes 200 I could actually do something in linear per frame so guys like ant square-ish because other than because if square-ish because other than because if square-ish because other than because if not yeah because I could do something n square ish because otherwise I would do something with like segment trees or something like that to get it down to end my again but doesn't seem necessary don't maybe it's good practice but I don't want to do it but uh well yeah I mean that they kind of have the requirement is so big that I know this one's it's 49 but it's actually 10 to the 18 because this was in a billion because it's a billion by a billion worth way and I think the tricky thing that they don't talk about and I should have a tickle ate this so it is my bad it's not you know is that you know you have 200 rectangles I kept like a lot of crazy in the sections and you have to figure out what intersections are and then when they intersect you know maybe like two of them in the set so three people three rectangles intersect and then well what happens there well you have to make sure you double don't double count or maybe even triple count because if you just take like you know the sum of their areas then you definitely can with trouble counting stuff right because of the overlaps so you try to figure out the area that is covered with overlaps right and I think so sorry I need to explain this better about explain but I just want to make sure that I'm just thinking it for in my head where but you basically have a script line album where you start Simo and then you go to the next event and so forth and each event is just the bounding box so you can sleep either way you can sweep from left to right and then your events would just be like okay we store it we start a box in from height X 2 to a lower height except lower right and so forth I think that should be sufficient because given a good to end operation every time there's only 200 rectangles and so you're going to go join 400 segments or whatever is something like that so that should be sufficient okay I'm gonna start coding and then I could explain my code afterwards I maybe my kind of explanation is a little wonky definitely feel free to ask more questions I could kind of explain it the best I can I just you know sometimes I think it's because I don't have like an iPad or something to kind of draw some visualization I've done in the past but it's a little messy so just I don't think it helped anyone so I mean just wait to come in and see if I could explain it down over okay now one language try one yeah that's to pipeline like I keep on switching to Python didn't do anything in Python have I done anything - today I don't have I done anything - today I don't have I done anything - today I don't remember sir so okay hmm okay so what can you pick I guess I like what you're saying I'd one I - and you know how Tyler I don't know any a better name for this okay hopefully you see maybe flag type okay so I get to this for now naming saw it so now what a great tweet fans so oh I forgot that inside of why actually so this is problem so Demings y2 is always hiding by one okay seven and it's friends and then the target was just it's the beginning of the event so that I should say it's one and we also want to do the other event which is one but now is for the second why we just do we hopefully you guys are the best and now we sort it yeah she'll be okay fine your lambda is this sufficient we swap by why yeah should be okay we sort by height so we should start from the bottom okay and now for I guess there should be just say oh I need a name we just actually wanted just because I have a weird type of compiling things okay it's a good question no - I mean dude it's a good question no - I mean dude it's a good question no - I mean dude the pipeline expert so your body I think I was thinking of another thing I was out speaking of pairs but uh yeah you're right I'm this is what happens when you mix languages there yeah let me think okey I actually don't remember syntax okay oh yeah name - oh yeah that's why I oh yeah name - oh yeah that's why I oh yeah name - oh yeah that's why I named tapas Yeah right you're that very right now - it's something that I've right now - it's something that I've right now - it's something that I've definitely used in the past this is why words when you don't use a language for 3-4 years 3-4 years 3-4 years production-wise try wearing it apprentice Yeah right just went awry no yours everybody named tapas it's been a while oh yeah like that okay that seems like us right okay well I know it's right there is maybe one life okay now we keep track of area so say we turn area oh I went into some bad stuff oh I should I forget how long books in Python because I worry about that now like sixty four-bit ends so I'm just like sixty four-bit ends so I'm just like sixty four-bit ends so I'm just doing a quick and okay well we'll see what happens i mmm yeah it's the way to do it declare this is it just like this the one time I used her I used by finite I had to do some time to get so anyway uh so what happens here okay so that so what happened doing a sweep effect okay I think about to start with why it's okay there should be in zero so let's say we start with why we start at zero and then we have the set of stuff that's already in so on going say her name is me so now what happens okay it's not that's why then we well then we go food on going to calculate to an area right okay yeah well maybe not yet hmm just wanna make sure I get this right but yeah I mean this is also where I should use name topics for the second part now I guess use my good top ohms I think I should go back yeah I mean I think it's kind of like I'm what I'm gonna end up doing is just kind of use because another way to do this is to kind of keep track of a little bit more but maybe I'll just use two sweet lines to calculate this that makes sense and yeah I wanted co-ed you find again yeah I wanted co-ed you find again yeah I wanted co-ed you find again that's why I'm struggling a bit brother but I just call it this I should also practice using name tuples but I'll do that offline used to set up light actually - yes and you see and then you add to area okay times the total between a sex and this event are the signs my son should be right that's the excess you go to and in theory they should be good because they should all be close to the lens so I'm just thinking if my code is correct when I have to set this up so it is not quite right good okay well no I doing so it's testing right but now we just have an event that starts here and ends here okay leftist well this is only if the event I'd flag is right now that's not what am i doing well this is just a processing point of it I just wish to always execute even it's just at this if statement allow us to save some time because if we already the same writing all these will be zero so okay that's actually nothing otherwise you are you right this is okay if these otherwise you actually have to remove stuff it just made me move back with an index to them what not even okay someone like that except for but you have to sort you fight well maybe not this good we've got to start ongoing I guess this is where we bring down to actually showed me how they do it last time but uh so I'm gonna try to do it with it insert bisect something like this I have to I will have to go away something like that you by sector prices yeah I mean this is writing first time I'll be kind of actually surprisingly amused bit I also I didn't do the mod so this is actually one but that's fine that point is okay like we have easy solutions for that point thanks tell - okay well it's just a thanks tell - okay well it's just a thanks tell - okay well it's just a fashion that we're either edge cases like the first one is actually and I want to say it's I would say it's a best but it's pretty good maybe not stress test fit yeah okay Yolo maybe I'll just get something wrong no well hmm that's actually kind of refreshing ly surprising okay um well thank you don't know dude uh what to say about this so I mean trying to think about it a little bit I mean this is because sometimes it's almost kind of counterintuitive they would you know the palm like if you know the answer in term of problems then wait what am I saying if you already know the solution then obviously is you know I'm gonna I guess what I'm trying to say it's I'm I think it's possible that I'm gonna have blind spots for this problem just because I saw just play away too quickly like if you know the answer then obviously everything is easy right but I think sweep line is an album that is a little bit underrated I think for a lot of in this section II things especially well I mean in this case they tell you that it's access a line which means you know if you think about like a sweep climb then like you know you're going from left to right then you could draw a line but actually if you think about but it doesn't always have to be like a straight line when you do sweep line it's just like sweeping events and then kind of rounding them up in kind of some ways because I think they're having to the kind of nautical example that people do for sweep line that is nine straight line sweeping line is kind of the convex hull would be yeah there I also like 80 billion comics home some algorithms been think about in comics holes for some problems like you can think about parallel like you could have lines sweepy things that out based on parameter well palabras like quadratic type of equation type things so it is something to think about I think for me not gonna lie I think I'm gonna have I'm gonna struggle a little bit to kind of just explain how do kind of how to category the pitfalls because I definitely do it use sweet line which is a thing that I think I've won so just that hasn't been true for a little bit but when I was nd wearing that with one of my go-to palms wearing that with one of my go-to palms wearing that with one of my go-to palms we're using sweep line that I would say that probably maybe 20% or less or fewer that probably maybe 20% or less or fewer that probably maybe 20% or less or fewer 20% of fewer people actually use the 20% of fewer people actually use the 20% of fewer people actually use the sweep line type way to solve it usually they like I think the way that you if maybe think about it another way is having a lot of if statements for these kind of problems like you'd want to do like segment intersection so for example you might have like a lot of if you know like you could visualize you know segments like stairs and like oh if X sub 1 is in between except 2 and Y sub 2 or something like that where if you do a sweep line then you just sort them and you don't have to worry about I mean and there is some trade-off with mean and there is some trade-off with mean and there is some trade-off with depending on what you're doing like maybe some stuff can be done in linear time but because you're doing swoop lined and you know maybe it's n log n instead but when you come back say so much or you're coding complex there is so much easier so I think one thing that I would recommend just for this problem to kind of look up and beat up a sweep line or a line sweep sometimes different I yeah sweep line or line sweep algorithms or event type algorithms and I think the key thing here is providing a structure that you could kind of go left away and actually I should explain this palm and step just generalizing a little bit for me what I did is that for how that visualize this in a good way I speak from left to right and then from left to right I kind of count up to the sub rectangles for so for this poem from 0 to 1 at point at the vertical height 1 I would look at well like what are the segment's I have way the segments I have of them 0 to 2 well go Mizzou - and then you kind of get the area that - and then you kind of get the area that - and then you kind of get the area that way and then you gotta get the rectangle between up from zero to from zero - between up from zero to from zero - between up from zero to from zero - excuse me from zero two one two and then you can and then the next one well you actually have segments from one zero two three and it kind of sum it up that way and actually I've put that down given to like even minor chunks of and this actually does more than was required but what the depth does is counts the number of intersection at those points but then but because those in the section those rectangular or a cylinder in the sections you only count want instead of tap number of times you don't double count that's kind of day alguma will do and then and I wasn't put down rectangle by two events right or different types one is you add your add segments which is what this part is for and then second points will be moving those segments actually probably I could also probably do this we move over by section two right yeah I got that grab I could just quit so I could even after my stat - and in this case actually stat - and in this case actually stat - and in this case actually everything is like ready no it's still n square as a result because this is right but yeah so just to make it explicit because I think I mean that's why you know sometimes pipeline of alpha skate there's a little bit in terms of complex state but because your for you to pin cell for loops or so that it's not always clear how far they go but this is all and because you can have n defense it or in the sector in the same time and you have to and events so it's off n square away where space is well and you saw it but it gets dominated by this n square anyway and in terms of space you only need yeah you only have ever half of N Things in ongoing or two and maybe well of and things ongoing and or n things in your fans so you're space complexity is linear yeah and I think so that's in terms of solving the problem this is a definitely a tricky problem I would say and there are a lot of educators if you do this another way but I think this is something that I have on my sleep that I do and you could kind of see it like and you could kind of reason it a little bit but you have to have some prior knowledge but because like I mean it's so I think the thing about it is that it's really clean right so like you see me coded by the first time I make a lot of statistics about my ones and so forth so and if I could do this correctly the first time without kind of thinking about it necessarily in depth almost like in quiet like unbelievably then you know that's what I would recommend yeah so that's kind of me discussing the solution because I think it's a little unique or like the way I saw is a little unique in terms of interview I definitely a lot of these type of problems so I'm thinking so I think like if you happen to actually know how to do this technique it's kind of good in a sense that like you always have a lot of similar ones like was it called the water level problem or water drop level problem or something like that where you throw water to building or like you have a skyline and you have to figure out like what's the area or something like that okay a lot of similar problems today so I think I so I think for better for worse it is something that and as I talked about it before I asked I do ask line sweep problems and I have or I had in the past actually easier than just one though but yeah that we definitely use it and this one but still sick many problems that you could solve by line sweeping so I would definitely recommend looking into it out and but also like I think that is within the expected difficulty of an individual poem so maybe this one's slightly harder than hoping by that much to be honest so definitely something that I would consider as an interviewer as I think I kind of there's a lot of overlaps right so in what I've talked about I guess that would be a good pun given the problem which is that yeah I mean I think this is relatively unexpected difficulties I like maybe slightly harder but still the album is the same and I like I said I didn't 29th of code so I would recommend that yes I mean I would definitely ask just or something similar so I wouldn't be expected by having don't Eve and I think there's a there is a good progression but it's qualms in the sense that you know if maybe anyway let me walk through it in that like if you're stuck then you could do the naive for a solution or what is the naive solution maybe okay well if n is say eight what can you do right well then you could do the you know 2d and type thing to kind of tuck it in this section with inside our algorithm which comes in to play on different type of pause but mere not just one excuse me but we could walk through like different ends to kind of simplify the problem a little bit and maybe give hints to you know because I think you could do this more kind of commutation the only it's just that it's very tricky so then we could kind of walk through that and kind of see what an edge case is okay and well what I would like to see is at least like the candidate is kind of thinking through oh this is wrong because X Y and C or well this is why because you know but just not fast enough excite over way over all right I mean I like I said it might have a bias on this one to them take me at my word for it but it is something that is very you know possible to be on hand away possibly even one phone screen so cool
|
Rectangle Area II
|
insert-into-a-sorted-circular-linked-list
|
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**.
Calculate the **total area** covered by all `rectangles` in the plane. Any area covered by two or more rectangles should only be counted **once**.
Return _the **total area**_. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** rectangles = \[\[0,0,2,2\],\[1,0,2,3\],\[1,0,3,1\]\]
**Output:** 6
**Explanation:** A total area of 6 is covered by all three rectangles, as illustrated in the picture.
From (1,1) to (2,2), the green and red rectangles overlap.
From (1,0) to (2,3), all three rectangles overlap.
**Example 2:**
**Input:** rectangles = \[\[0,0,1000000000,1000000000\]\]
**Output:** 49
**Explanation:** The answer is 1018 modulo (109 + 7), which is 49.
**Constraints:**
* `1 <= rectangles.length <= 200`
* `rectanges[i].length == 4`
* `0 <= xi1, yi1, xi2, yi2 <= 109`
* `xi1 <= xi2`
* `yi1 <= yi2`
| null |
Linked List
|
Medium
|
147
|
11 |
hey guys today we're going to go over the code problem called container with the most water where the problem statement says you're given an integer right height of length n and there are n vertical lines drawn you have to find two lines that are together with the x axis that form a container such that the container contains the most water in the example below we can see that in the diagram there are a bunch of heights given and we need to find the maximum area where the water isn't overflowing past the container and to do this we can use a linear search with the left and the right indexes that are stored and to do that we need to create two different counters the left index which can start at zero and then we also need the right index which will start at height dot length minus 1 which is n and we also need to store the max value or the max area of the given container and so what we can do from there was we can create a while loop that will make sure that the left index will always stay less than the right index and make sure that when they're equal to each other we'll go back to the area of zero which we had started we first need to make sure that we store the current area from the location that we're in and so to do that we need to get the minimum height of both of the left and the right indexes indices which is so that the water doesn't overflow and we can do that using matt's min method where we pass in the height of the left and the height of the right and we have to multiply it by the distance between the two in order to get the area and so we can do right minus left and now we're able to store the current area if the current area is greater than the max value so if max is less than current area we need to make sure that we redefine the max value as the current area because now we have found a new max now we need to make sure that we're updating our counters are left and right to make sure that we have the highest value though the highest value stored currently and so if the height of the left is less than the height of the right we need to make sure that our left counter is going up by one else we can allow the right counter to go down by one and this will make sure that we don't get into an infinite while loop and also make sure that the highest height will be will contin will stay the same and so then we can return the max area and if we run our code we can see that our solution will be accepted and thank you for watching the video
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
1,800 |
Hello guys Ayush in this video and I got beaten to death in Delhi ok number this morning number one plus one from one and according to that is gold fennel so now what we said is that this is after a survey like and Well, okay, whose maximum possible group is given to the element of morning in send a quarter like in this it is 1038 so what can be its answer 2030 lol Seth and then second is morning it can become 510 150 so its answer is sixty. Five, so which is the maximum among these two? 1665 message text five. So once I see its algorithm, I add the latest one first, so what do we have to do in the first case. The condition in the preparation for this case used to say that I will add the latest one first. To maintain it, we should take maximum time in the morning, it is okay, so what will we do in this, by taking method one, let's hit the method of mind, which is our fruit source. Okay, how to make profit, what will we do with tailor. Will start and from equal to zero we will start from here then on the second photo I take the algorithm once how from equal to zero to go to my - * shift request to go to my - * shift request to go to my - * shift request to go from i plus one to go to my n minus one Till now the sum is inclusive so here we will come here because I have to go till this level because I will complain so let's see how to do it so what I will do in this is that these are the elements of i20, first I will compare it or with this or I We can add, this will be wrong for us, we will go to Bansi and go to the end - 151 - Vansh - Banata will and go to the end - 151 - Vansh - Banata will and go to the end - 151 - Vansh - Banata will take a look once. Are you going to know what should I do or will I take it in the morning first, okay, now I will look into it. That this first element of the computer will come from Plus One so it will be inclusive so here we - two will it will be inclusive so here we - two will it will be inclusive so here we - two will come Z Plus One I will comeback from Plus One my husband if this is then here I will delete one time available and support the time I will keep doing it, how first I added the tan, made it fit, then went again, I saw the same thing again, I tapped thirty from the previous one, it is great, yes, so I took 30k, we will go to the pipe again, we will compare the pipe with the entrance one. If it is, then it is five, which is smaller than the people around me, so what should I do, I will do this and then I will compare it, which will be returned and I will reduce the result to this - Infinity S.A. So - Infinity S.A. So - Infinity S.A. So what will I do, whatever happens, I will do the parade from here, if this minimum condition comes and I will check my request, now which one will I consider, I will reconsider this, then in the same way, I will consider this one 13250 Then like this here, after taking all the money, he will come under inquiry, so what is the main motive of brute force that you consider all the remedies, check the condition of the phone and smell in the morning, keep doing this to the maximum with the ascending wali plus you. Keep on starting the maximum. If you become a recruitment angel, then its complexity will be very high, so how are we going to do it, who hit method two or even looked at it, I was the two man, what will we do in this, actually we will use the maximum modification algorithm. It means that I will take the idea of Pradhan Sinku Nigam means that I will take the idea of Pradhan Sinku Nigam means that I will take the idea of Pradhan Sinku Nigam and take inspiration from it, I will modify the algorithm and find out the answer. How will it be? Let's see right now. Okay, so return yesterday evening. What we used to do was to check the computer every morning. The good thing we used to do was that if you do n't know it yesterday evening, then first go and find out about the best fruits and I have made a video earlier also, so watch that too, then you will understand what is the dance algorithm, so what will I do here now? The first thing I will do here is that I will appoint a growth element in the information I will give about it, why I will do that, I will also tell you why I will do it, later when we will see it completely, we will understand, so first of all, what will I do? I will start a flop from equal to one and I will go till the last element and the last element will become end and it will become loud from electronics and will go to the first index. Okay so what will I do? First of all I will take a result which will be mine. Max will tell the final answer, it's like I am one and a half, I will become like I am Katha Shilpi, I and most of the present ones, what did we do first, what was our first test, like we increased by 1 liter in flu, what did we do to it, added infidelity. Then what do we do with second time? We used to give less importance to time and result and then we used to check the tempo whether it is the license or not. If it is zero then we used to grow by the tempo. What did we give to the result here? Max was very high. A of these two, okay, so this was our main cell, the highest A, so what I will do here is that the first thing I have to do is to maintain the ascending order, so how will I maintain the ascending order, I have taken the zero element because the host is positive. If more entries are made then it will start from the last one, then the first element will always be what, it will not be ascending because Swiss roll is absolutely smooth salt ISRO, on this address, then what will be the first case, I will check, not from time to time, I will check. I will do it, I and I - One, which is the previous element, which is the and I - One, which is the previous element, which is the and I - One, which is the previous element, which is the current element, is this ascending order being maintained, if this is happening then what will I do, will I add it on time and brother, it is fine and what to do now. In the end, whatever will be our result, we have to make it maximum, again the result will be in commerce time zone, so our first toss was the first one which used to be in the class, now here we have tried the second one, this one has become ours, now this one is ours. Torch in this it will not be there because this time pass we will not be clan chains because we are oh positive energy sass crazy now one more thing is that if and I come in the help chart that if ours see in this that if ours the sum I - One is if it is greater than or sum I - One is if it is greater than or sum I - One is if it is greater than or equal to yours then what will happen that we have to see now one thing is that if we have been considering from here in the morning till here we have been giving this answer and in increasing order like this Element, if you this element is a little small IF I - first element I - first element I - first element is from minus one element Hello friends, a different morning will start from there, then from five the possibility is here now that it will end again in the morning, which will be the maximum. What to do in this case is the health partner in the help chart or will we do the treatment from time 20 now and then if or traitor we will run equal to one from the end till the end, then if we talk about its time complexity then the time complexity is that by Because we have plus for 1 liter, if we talk about the complexity then how much will it be that Rocky of one because here we have two bariya ballia result name and one extra has up and done this gang phone so that it will not make any difference so It looks at the time court, first of all finds out its size, which will be useful to us and we can find out its size by entering the name function from the start side. Now what will we do, will we give it to that person, if it is a small size, we got it at the ends or if we got it by hand. If I get zero, then what should we return? It will not be done from the patients' website and if not be done from the patients' website and if not be done from the patients' website and if this is the first element, separate in the same element, then what should we do? I will return ₹ 100. then what should we do? I will return ₹ 100. then what should we do? I will return ₹ 100. If there is an agreement, then the maximum is the same. Everyone will be giving number now, what did I say that first of all, say, what did I say that first of all, what will I set in the front of this, I will set Shyam, now in the start packet, I will tell zero, I have inserted it, now which We will also get it, what will we say in it, we will set the heroin, now what did we have before taking two strong results, I - due to acidity, this is why I had to results, I - due to acidity, this is why I had to results, I - due to acidity, this is why I had to do it - Meethi, let's see how I do it - Meethi, let's see how I do it - Meethi, let's see how I can understand, friend, this is a positive list, which is my result. If the positive coming comes, it will always be - study from the heart and secondly, always be - study from the heart and secondly, always be - study from the heart and secondly, what did I have to take temporary available Khusro, what did you have to do, I called, I gave you that this is another eye lens, that I love you do the size is ok now No enjoyment, at least two who is the son of a number of - one, what is that number of - one, what is that number of - one, what is that lesson, we have the money, what do we have to do, set the time, let me message you now, what is the result of the joint mix? Result Comedy MP Indore Hum Then if we do further, I set this name of nothing else for this lineage and we will start the first element and go, so now whatever is there has been changed, so I do that because I set or Then what can I do in this, I show it by doing this, then I also do this that God, I am sending this 10's sleeping antenna and here I must be this antenna, so it is saying that a If you put it in the picture, then this element eye, something like this will not work, so let's check it again. If you like it, then I will show it in Chapter 23 matches and after some time, I will show it. Okay, so its front arm hole. Family Second Hunter Percent Poster All the submissions done till now its memory usage is 25mb so thanks for watching video subscribe my channel videos and notifications
|
Maximum Ascending Subarray Sum
|
concatenation-of-consecutive-binary-numbers
|
Given an array of positive integers `nums`, return the _maximum possible sum of an **ascending** subarray in_ `nums`.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is **ascending** if for all `i` where `l <= i < r`, `numsi < numsi+1`. Note that a subarray of size `1` is **ascending**.
**Example 1:**
**Input:** nums = \[10,20,30,5,10,50\]
**Output:** 65
**Explanation:** \[5,10,50\] is the ascending subarray with the maximum sum of 65.
**Example 2:**
**Input:** nums = \[10,20,30,40,50\]
**Output:** 150
**Explanation:** \[10,20,30,40,50\] is the ascending subarray with the maximum sum of 150.
**Example 3:**
**Input:** nums = \[12,17,15,13,10,11,12\]
**Output:** 33
**Explanation:** \[10,11,12\] is the ascending subarray with the maximum sum of 33.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
Express the nth number value in a recursion formula and think about how we can do a fast evaluation.
|
Math,Bit Manipulation,Simulation
|
Medium
| null |
718 |
hello everyone so today's lead code challenge is maximum length of repetitive sub error so here in which we have given with two arrows of num1 and num2 and we have to find the maximum length of a sub error here as you can see the number one is one two three two one and the num two is two three one four seven so here as you can see the three two one and the three two one in num1 and num2 is common so it is a sub array of both and the maximum length of it is 3 so let's jump into the code and see how it's gonna work so here in a code what we gonna do we convert the number 2 into the string so num2 underscore string equal to empty space dot join character of i for i in num store so it will return the string of number two we also create a maximum string so max underscore string equal to empty string and we declare result so result equal to zero now we iterate through the number one list so for i in nums of one and we append the eighth character of number one to our mac string so max string plus equal to character of i character i so after that we check if our mac string is in number two string so for that if mac string in numbers to underscore string then we what we then what we gonna do we return result equal to max of our result and lan of mac string and if max string is not in number two else we ignore the first character of mac string so max string equal to mac string one column so what it gonna do it returns the list without first character and then we return the result so return result now let's try to run it and here as you can see our output is three now let's try to copy the code to the site so let's try to run the code run and our code get accepted let's try to submit it submit so our code gets submitted here is a code thank you for watching see you soon you
|
Maximum Length of Repeated Subarray
|
maximum-length-of-repeated-subarray
|
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100`
|
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
|
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
|
Medium
|
209,2051
|
712 |
to my Channel today we are going to solve the lead code delete challenge number 712 minimum ask the lead sum for two strings so it's very straightforward we are giving two strings as one and as two we just need to calculate the operations for delete after delete we should make the S1 equals to S2 for example here with the letter as character and for S2 we just need to delete this key capture after deleting this EA equals to this EA and what is the operations of the delete so after deleting we first needed 2 plus the ask values for example s equals to 115 we need to plus this value and what about the deleted T we need to end this value 116 yeah so for this S1 and S2 it is less than one thousand yeah if it is like this and if we did some political questions like edit distance we are sure we will use the dynamic programming and here for this one I will use the tabulation for the dynamic programming so I will first explain in whiteboard after that I will go to the code Editor to finish up the coding now let me go to the code editor now let me go to the Whiteboard first to explain what this means yeah as we can see from here we have two strings as one is CSEA S2 is eat e a t with us what to make those two strings e equal and calculate the minimum operations for deleting as one yeah or deleting S2 to maximum equal now let me explain how we're gonna do that so we're gonna initialize a DP array so the DP array will be a 2d array so inside the 2D array we're gonna initialize as a zero so everything inside will be zero yeah and we can see that so after that we're gonna calculate the first row and the first column so as I said this S2 so this is S2 it is means here is empty three and this is e a t yeah and for S1 for the first one it is empty string after that it is s e a so we're gonna first yeah exactly the first of those so how to make this entice 3 equal to this empty string there's no operations so that is zero yeah so after that we have our e so what is the operations it is Audi but for simple I just make here E Yeah so actually this is the odd e because I'm going to use the odd to calculate the numbers of this e yeah after that here I have a so EA to this end history what is that it is e plus a so here plus actually it is also the odd e Plus or a yeah so what about to the next it is a e plus a and plus T yeah so this is the next so what about the column similarly it's also the same what about the first it is a s what about the second it is S Plus e and what about the third it is a S Plus e and Plus plus a right yeah only in this way we can make so the meaning of that is also easy to understand so the meaning of that because the DP dprc is a the minimum operations to make the two strings equal yeah so for here this is a zero because m t is doing to empty string it is a zero but for here this one this adds to empty three what should I do I should delete this one so what is the operations it is odd s so here I will write s yeah similarly here S Plus e and here S Plus e plus a so for this one s not equals to e this is one of the conditions yeah so if this string not equal as one not equal to S2 C minus one it's S1 R minus one not equal to S2 C minus one so this is the first condition actually it is here yeah so if they are not equal so there are two conditions we can make them equal so how can we mix them equal for example this e not equal to this s yeah we can first take out this e right if we take out this e from 3 S2 so it is the empty string yeah empty string to this string s so what is the minimum operations it is s so in order to make them equal what should we do so the S should plus e yeah and also we can do similarly like that what about we take out this s after we take out this s it is the air empty string what is the minimum operations to make this empty surgery to this string e because we already have the record it is e so it is with the E plus s so e plus S and S Plus e minimum of them is also the same it is e plus s yeah now let's go to the next position so next to position this s not equal to this a character what should we do so we saw the first use the E plus a yeah if we use e plus a it means we will take this as out if we take this F out we have to plus the S character so it is the E plus a plus s and here e plus S Plus a it's also equal so the final result minimum of them should be e plus a plus s yeah and what about the last one so this is the e a t so here is s yeah if we take this s out empty string to this is e80 we should plus this string s yeah so there are four characters what about here if we use this one e a s we need two plus Z T it's also the same so the final result is e plus a plus t Plus s right yeah plus t plus s so what about here is another condition this condition is E equals to this e so if they are equal we are sure we can delete this one and delete this one they are equal but we can teach them if this E equals to this e we are sure we will keep this e and keep this e here but what about the previous conditions it is a DTR minus 1 and say minus one so we need to check this place so it is s so here we can put a s yeah for C is the time I'm not going to calculate every condition but I'm going to check here for example if I were to this one yeah let me calculate this one first so this is the EAS if so this is s so S Plus a and combined with e plus a plus S Plus e so of course S Plus H would be minimum so here should be S Plus a and what about this position as we know this s is a minimum so this adds through the plus a yeah as here is also S Plus a so what about this one for this one a equals to A so we're gonna take this s so here should be S so what about the final one I'm going to calculate yeah actually I calculate every everything so this is as a so s a through the plus T because here is always be bigger so here should be S Plus a plus t and what about this one so for this one a naught equals to T we are going to take the minimum so this is s yeah we're going to plus this T so here should be S Plus T yeah so what's the meaning the mean is if this is 3 equals to that character if this character equals to that character we are sure we will not do anything we first need to check the previous value so that the DTR minus 1 C minus one yeah for example if this a equal to this a with us to take out take the previous value we just compare with E and S E Yeah so if they are not equal we are going to take two combinations it's the minimum of so the DPR minus 1C and the tickle and then need to plus this odd of S1 and here the odd of F2 yeah because this one will take out a column we need to plus this column yeah I think if we understand this basically the code should be much simpler than that now let me go to the code Editor to finish the coding yeah as I said I will Define a DP array before Define defining the DP I really I need two variables so the r and C R would be the loose and C would be columns so the r will be S1 plus 1 and C should be the length of S2 Plus 1 after that I will Define my DP array so the DP array will be initialized as 0 times columns and for R in range capital r after defining the DP array I will initialize my first row and the first column yeah so for the first row it should be for R in reads 1 2 r what about the First Column it should be for C in range yeah for C in range one to say because the zero DP 0 and 0s should always be zero yeah so here should be say yeah now that means have the first condition the DP hours and zero because I'm going to check the first so this I'm going to check the first though yeah if I'm going to yeah let me talk so this is a yeah this is actually the first column yeah because the loaf the column is zero yeah so DP yeah let me explain and try to explain this one so the dpr0 means here so the DP are zero that means the first column yeah so the zero is column we are going to check the First Column and then take the first Loom so the DP are zero should equal to DP R minus one zero plus the odd yeah because we need to use the odd to get the value yeah to get to the number not to the character so what is the odd the odds would be the low as one R minus one so this is very important to avoid any mistakes because according to our definition this is always BR and S2 should always be column so if we want to change something about the rows so here the odd should be S1 R minus one yeah and similarly we're gonna put it into the those so here actually we are defining the first rows so the for the first row it is a DP zero say should equal to DT 0 C minus one plus the odd S2 say minus one yeah so this means it is a yeah like the first character e and second character a and the third character t yeah so this is a DP yeah so this is a defining the first those actually I'm defining each columns in the first row here I'm defining the first column actually I'm defining each row of the column yeah now I will go for the next one the transformation function so for R in reads 1 2 r for say in read 1 2 capital c I'm going to tag is S1 yeah if S1 R minus one equal to S2 say minus 1 because S2 is a four column yes if they are equal I'm going to take the DP R and C so the equal to DP R minus 1 and C minus 1. if they are not equal I'm going to take the minimum so the DT RC should equal to the minimum of DP R minus one column because I'm taking out the rows so I should plus the odd value of S1 R minus 1. similarly I'm going to yeah check another condition it should be let me copy this one yeah so here I just need to put this rows and here should be column and here should be S2 column minus one yeah after that I can return the result so the result would be DP minus one and minus one so for the DT agree if we use a tabulation it's really easy to make mistakes we have to yeah attack so this is a trans transformation function and here is the initialization of the row and column so here I initialized the First Column yeah let me talk if this is okay yeah so for saying rate yeah let me run it to talk if it is the same like my drawing or not yeah it seems okay because when we are writing this function normally we should compare with here yeah compare with this kind of drawings in order to avoid making any mistakes yeah for example if we are setting our function we need to compare with this one here yeah if other definition of the rules or columns so for the column columns here is S1 yeah it is a column so for here this is for rows yes so the first row it is for F2 yeah so edit means it is totally the same as my drawing let me compare with the drawing it seems okay now let me submit it to tag if it can pass all the testing phases yeah as you can see it really works and it's pretty fast so the time complexity will be o and square that means suck yeah S1 and F2 so if F1 the length is M so the length of F2 is n so the time complexity will be M times n so the space complexity should also be M times n
|
Minimum ASCII Delete Sum for Two Strings
|
minimum-ascii-delete-sum-for-two-strings
|
Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum.
Deleting "t " from "eat " adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
**Example 2:**
**Input:** s1 = "delete ", s2 = "leet "
**Output:** 403
**Explanation:** Deleting "dee " from "delete " to turn the string into "let ",
adds 100\[d\] + 101\[e\] + 101\[e\] to the sum.
Deleting "e " from "leet " adds 101\[e\] to the sum.
At the end, both strings are equal to "let ", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee " or "eet ", we would get answers of 433 or 417, which are higher.
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1` and `s2` consist of lowercase English letters.
|
Let dp(i, j) be the answer for inputs s1[i:] and s2[j:].
|
String,Dynamic Programming
|
Medium
|
72,300,583
|
140 |
Hello hello viewers welcome to my channel today 30mb problems but back to saudi only and problem of world problem give me dad dictionary bold content list of all subscribe our channel subscribe and gives life bj gym dictionary multiple times in a sentence example 1232 subscribe and subscribe the view from dictionary aur swadeshi jab problem wave in this problem 200 g sentences and aggressive may be but can do subscribe our dictionary subscribe and subscribe our dictionary subscribe channel subscribe to do the self possible world first with you That cat send that dog that into two parts so let's mv rack heavily with the left side and before going inside check dictionary who is not withdrawn in 9 points to subscribe and subscribe the Channel subscribe to subscribe and subscribe that Android app members Young Possibility Absolutely Reciprocally To Back This Swimming Spring The Right String Of Wearable To Do When Will Construct A Sentence Spacing In Between The Video then subscribe to subscribe Again Will Be Pleased For May 's Member To Call Will E Two Traps Continue 's Member To Call Will E Two Traps Continue 's Member To Call Will E Two Traps Continue Like A Demon Tractors Positive They Will Try To Solve This Will Not Be A Porter Bird Jo Iss Video Laga The Same Will Agree With U Main Safe Sex Dog Radhe-Radhe Safe Sex Dog Radhe-Radhe Safe Sex Dog Radhe-Radhe Video Two Sentences subscribe for More Video Subscribe Play List Of History Which Will Return Subscribe Our Already Contents That Directional Current String In That Case Will Not Enter Into One Result That After Death Will Process Running Teenager From Microsoft Want To Start Land Resources And Process Normal Note Will Conclude On Twitter Subscribe To Id Check Birthday Dot Research Labs Call The School College For The World From The From President Is Vansh Video De List Of But Sunna Fauj Virwal Re Sentences Of The Mid Point Of Birth String Morning 2.5 Veena Malik Body Birth String Morning 2.5 Veena Malik Body Birth String Morning 2.5 Veena Malik Body Voice Sentences With Gautam Gambhir Virat History Sentences Into The Independent Director And Updated Result Subscribe Sentence For Indian Villages subscribe and subscribe the Imagine Matter Vaikunth Hey So Let's Ab Isko Swadesh Mein Bhi Time Out S8 Test Cases Reported Cases Which Will Take Subscribe Button Length Of The Receiver Like This Example2 Subscribe Ki Ego Ki Show Main Late Se We Will Get First Agenda Dictionary exactly for remaining five of the actors in this sacred evil of rather like plus remaining like plays will remind z plus will always be third to zinc world record for the meaning of computer in the middle age subscribe for calculation subscribe to convenience and the next time Beach Canis News Room for Catching Data Structure in Adhir and the Hai Abe Lewis Our List of Sentences Which We Can Know Form Using a Part of History So Let's Addison Biology Solutions for Adults A Map of Spring Come List of Strings Flash Light Call Our What Have only life itself is used mostly map name is better fit in this year which comes to do anything which contains the string picture using the value of from list of sentences w part of the problem epistle otherwise will be the end of calculating this map. com Result Convenience Twelve Years So Let's That Testis Custom Test Cases Where No Weather This Passing Or Not True The Ring Now He Near 388 So Servi That I Top Spot Member We Result Hair And Love Current Spring Wear Processing Fee Control Of Later Written In The Written Exams Vinod Result Of The Spelling Of Resident Evil Is Acid That's An Ax Update Services Simple But According To Amazon Politics And Taste Marriage Is This Festival Solved Problem In Questions And Avoid Like Share And Subscribe Thank You
|
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
|
41 |
in this video we'll be going over first missing positive so given an unsorted integer array numbers find the smallest missing positive integer so in our first example we have one two and zero and our first missing uh positive integer is three so we have one two and three because zero is not positive and our second example we have three four negative one and one the first missing positive is two because we need one two and then three and then four and then this third example we have seven eight nine eleven twelve and our first missing positive is equal to one now let's go over the thought process the positive so the range of positive numbers is from one to num style length plus one this is because for example if we're currently at with a length of three here our missing positive can be one two three or four because if the input rate is one two three they are missing is equal to four so the range of positive numbers is from one two numbers down length down four this means all of the numbers of the positive numbers can fit inside the input rate except for the last one of course except for the last positive number which is the numbers on length plus one we can mark the indices that we have already found a number for so for example if we have found the integer x which is in the range of one two number.length of one two number.length of one two number.length we can place the integer at x minus 1 at index minus 1 and index x minus 1 to mark as seen then for all of the other integers which are not within range we can mark the index as zero so let's go through a simple example so let's go to this example so initially we have the number three so we have found the number three ends within range of our missing numbers so we can place three at index two here so before that we got place zero at the current index and then we want to place three at index two so we place it here but we should know that we have we should have to save negative one because we do not just want to replace it without replacing it right so our current number is negative one since negative one is out of range we do not need to account for this anymore so we can just continue to the next element which is four and four is within range so we gotta place four at 3 4 minus 1 so index 3. so we got to place 4 index 3. so we place 4 here and of course we got marked as a 0 because we moved it now we have our current element one is the one that we have replaced with four and four is still and one is still within range so we gotta populate one at the index at one minus one so is that index zero so we place one here and now the element where we place is zero and zero is not within range because we only want positive integers so we just continue to next iterate uh we do not we just need to skip this and then we continue to the next element is three now three is right located at the index three minus one is two so it's already at this index so we can skip it and then four is also already at index three so we can skip it and now we can find our first missing positive just by iterating it through and check the first index with a value of zero so in this case in this index one we have a value of zero so that means we can increment one to the index one plus one is go to two and two is a missing number and now this is the side case of the handle is what if the input array has all the missing uh of the positive integers like for example if it already has one two three four 1 2 3 4 then if there are no zeros inside our array then our missing number is equal to nums down length plus 1 which is equal to 5 in this case now uh let's go over to pseudocode so we're going to create a variable n which is the length of the input ray empire array nums now we're going to iterate through the indices of nums we're going to denote it as i will first save the current elements so create a variable x and set it to nums i now we want to set the current index to zero once set to zero because we have already placed it at the current elements right um uh we set it to zero because we are about to move it for example if we're current at this and we're about to move it to the next index we're going to set up there here then we're going to say while true if x is outbound or if x is less than 0 or greater than n that means we cannot place it inside our array or x is equal to nums i'm x minus one this means we have already placed the elements at the index is supposed to be so we do not need to continue uh we do not need to place it anymore so we can break from the loop now before we replace the elements we're going to create a variable and save it first we're going to create a variable y and save nums x minus one then we can set x nums x minus 1 to y out to x and then we can set x to y this will allow us to continue our loop because if the number that have if we replace at the index is valid we have to continue on our looped loop to continue to replace elements now we're going to iterate 0 now we're going to iterate through the indices of nums this is to check the index with a value of zero so when denoted as i if nums i is equal to zero then we have found our first uh missing positive so we can return i plus one else we'll just return n plus one that's this means there is no missing positives inside our input array so the missing positive must be greater than the length of the input array so let's go over to time and space complexity so the time complexity is go to of n where n is the length of the empire this is because we visit each index at most twice our space complexity is go to of one we can say is that g of m plus of n because this is our second loop to find the missing elements or by missing positive let's go over the code so let's first create a variable n to be the length of the input array and when iterate do we're going to save the current elements into x equals the numbers i and then set 0 at the current index because we are planning to move x so while true if x is less than zero or x is greater than n that means we are not allowed to move it and it's not a valid number or nums or x is good to nums x that means x has is already uh numbs x minus one that means x is already in the location it's supposed to be so we can just break from the loop now before we place the elements and nums x minus one we have to save it then we place num x minus one to x now we wanna continue our loop until we have found an invalid number now we're gonna iterate two to find the first missing positive if nums i is equal to zero then we can return i plus one else if there's no missing positive in our input array then we can return n plus two oh n plus one oh if it's less than one because zero is not valid it's less than one let me know if you have any questions in the comments section below like and subscribe for more videos that will help you pass the technical interview i upload videos every day and if there are any topics you want me to cover let me know in the comment section below you
|
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
|
1,424 |
hello viewers welcome back to my channel I hope you are enjoying all the videos that I am uploading if you haven't subscribed to my channel yet please go ahead and subscribe today's problem is diagonal travels given a list of integers noms returned all the elements of noms in diagonal order are shown in the below images so we are given with a list of integers right so it's not a single list but it is a list of Lists maybe you can imagine it as a 2-dimensional grid but imagine it as a 2-dimensional grid but imagine it as a 2-dimensional grid but as you see in the example to write so even though it's a 2-dimensional grid even though it's a 2-dimensional grid even though it's a 2-dimensional grid right so the grid hat doesn't have all the basically cells in it so these are not actually M by n or n by n matrix or grid but these are something known as Jagd arrays right so let me write that down here so they are called Jagd arrays right so they are called Jack arrays so Jack Terrace is nothing but so you have a list of lists but each list has variable number of elements in it so that's what should be addressed from the example 2 because that is a real depiction of the problem so example 1 it's actually n by n right 3 by 3 matrix right so that's probably not what the description we want to really convey but example 2 is what the description won't really convey because it is saying a list of lists but it doesn't say how many number of elements are there in each list so in each list and the number of elements are variable right so that's the reason why example 2 is making more better than this better justification to the description there an example 1 so our frog our problem is we have to return all the elements in the list of lists in a diagonal order so let's try to understand the example 1 right so that in order is 1 four to seven five three eight six and nine so that's what we are going to read on in the output so if you come to the example to write so there are elements missing in those diagonals right so we don't have we don't really care about the missing things but barring the missing things written the rest of the items right so 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 so there are like 16 elements in the list of lists totally right we have to pass through the diagonal and give them back as the answer so in this case there are so many diagonals 1 2 3 4 5 6 7 8 9 right so there are totally 9 diagonals in this even though not all diagonals have all elements so some diagonals have one element some diagonals have two some diamonds have three like that right so wherever you don't have the element you just don't consider but still try to return whatever the elements that you have in the particular array so let's go ahead and try to understand what strategy that we are going to use right so these are Jack there if I would like to repeat the name right so Jack the arrays so these are there are n list let's say right so there are n number of Phyllis and each list has a variable number of elements so that is our problem and if you were to represent these lists in a grid fashion right in a grid fashion where some of the cells are not enabled that means the in some of the cells the elements are not present so that's what it is so what is the strategy that we are going to use now right so what we are going to use this we are going to create a map right so map it will have an integer as a key and a list of integer as values so this is what my map structure is going to look Kisa cake is the index right and values are the elements which satisfy the index that is the key right so we are going to see what is actually index what that we are going to put and what is the values that we are going to put so values are typically the values that we are given in the list of lists but what is the index the key that we are going to use that's what is a logic here right so let's say it-- list right here right so let's say it-- list right here right so let's say it-- list right at least has let me put a - so that it's at least has let me put a - so that it's at least has let me put a - so that it's better so itíll estas em elements so let's say you have I either list it has M number of elements so starting from 0 to M minus 1 right so the key will be I plus index of the element in the list right so you have I plus the index of the element in the ith list so what for this thing right so what do you have the indexes are I plus 0 I plus 1 so on I plus M minus 1 so those are the indexes right and the values are their corresponding elements in the particular list in the ID list basically so the keys are I plus 0 I plus 1 I plus 2 I plus 3 I plus M minus 1 and the values are the corresponding elements in that particular I to list right so just to depict more understanding right so I took the example 1 2 3 4 5 6 7 8 10 so this is what the representation is for this I have in the first list I have three elements so I have just to give better understanding right so this is the 0th list right 0th list so 0 list so this is first list right first list and this is second list right second list so in that case this is I am calling as I and this is the 0 to M so if you see this is same 0 right certain the number of elements are 0 to M minus 1 that's what we said it 0 1 2 and first list this is 1 will be the prefix here right and 0 1 2 so second list to go with prefix 1 2 right so like that so these are the I plus whatever the value that you want to call it as right I plus the index of the element an idea so that's what we are going to have so that is the index so essentially for this it is 0 plus 0 for this it is 0 plus 1 for this it is 0 plus 2 1 plus 0 1 plus 2 plus 0 2 plus 1/2 1 plus 2 plus 0 2 plus 1/2 1 plus 2 plus 0 2 plus 1/2 Bristow so those are the indices right that we are going to create that means the keys right so we are going to use those keys in our map so essentially the map will have 0 plus 0 that is a map 0 plus 1 and 1 plus 0 so that will have the key is 1 so 1 + 2 + 0 1 + 1 0 + 2 the key is 1 so 1 + 2 + 0 1 + 1 0 + 2 the key is 1 so 1 + 2 + 0 1 + 1 0 + 2 that will have 2 + 2 + 1 plus 2 that will have 2 + 2 + 1 plus 2 that will have 2 + 2 + 1 plus 2 that will be 3 + 2 + 2 that is 4 right so will be 3 + 2 + 2 that is 4 right so will be 3 + 2 + 2 that is 4 right so these are the India keys and the corresponding list a corresponding values 0 will have only 0 + 1 will have values 0 will have only 0 + 1 will have values 0 will have only 0 + 1 will have 4 + 2 so 0 1 that means 0 at least first 4 + 2 so 0 1 that means 0 at least first 4 + 2 so 0 1 that means 0 at least first element and first list zeroth element both will have the key as 1 that's why we took 4 + 2 and if you look at the we took 4 + 2 and if you look at the we took 4 + 2 and if you look at the map has to write the index 2 the key is to write in that case 2 0 2 Plus 0 is 2 1 plus 1 is also 2 + 0 plus 3 is also 2 1 plus 1 is also 2 + 0 plus 3 is also 2 1 plus 1 is also 2 + 0 plus 3 is also 2 so in that case we have three elements so we grab those three elements 7 5 3 and put it into the map so once we have this kind of that map built up right then we will merge all the values so the keys are 0 1 2 4 right 2 3 4 0 1 2 3 4 but we don't care about the keys we only care about the values so we merge all the values and written as the output so if you merge the values right what will become 0 is actually it's wrong ok so if you mark the Mazda values what it'll become 1 4 2 7 5 3 8 6 9 so that's what you want to return it 1 4 2 7 5 3 8 6 9 that's what we want to return so that's the basic logic ok so what if some of the elements are missing here let's say all right let's put it this way right so this is what it's going to look so what we will miss something right so 2 1 is there but 1 2 is not there so the three third element so this is not going to be there in a map so that's the adjustment that we need to make as part of the code as long as it satisfies right so you will have all the things in here let's say this doesn't even have all this right let's say all right in that case let's say this is only the metric in that case what we are going to have so just let me get back yeah no so 0 is one element and 1 0 is also a single element right so 4 2 so 4 is not there and 2-0 will have only two not there and 2-0 will have only two not there and 2-0 will have only two elements excited right so it will not have 3 7 & 5 & 3 will have only one have 3 7 & 5 & 3 will have only one have 3 7 & 5 & 3 will have only one element 4 really have only one element so that's how it's going to look so our answer will be 1 4 7 5 8 9 so that'll be the answer right so we'll have to work through the given list of lists in this fashion so all we are trying to do here is convert the list of lists into a map and take the output from take the values from the map and leave the keys alone and return the margin list what I'm calling so all these are less right in the in a map so this is a list is this a list so they are all the lists so merge all of them and antennae bigger list that's it that'll be the answer for our question let's go ahead and look at the code for this right so it's the same idea that they're going to use so these are okay let's go yes here succour so for fine diagonal order we are fast with the list of lists and we cover calling us now so as I said we are going to declare a map right so it will map has an integer and a list of integers so just like what it described here right it'll have just two things and then we are get trying to get the number of Lists that is n so what we are doing isn't really here is we are going from the last list right so in my example I showed you from zero at least but here in the code wise because we want to written in the order that we want it right so we want one to be first for second 75 like that right so this is how I'm going to do it right so we are going from the last list to first list so it will be going from last list to first list n minus 1 the list to 0 that list right and in the each in each list right we parse through 0 to M right so 0 in my example I said M minus 1 right so that is what number five count minus 1 that is a list count right number five is a list right nums is a list of lists and I'm so why is a single list so we go through that and now what we are trying to do is we are trying to create a key I plus Z right so what I am calling J is I plus index of the element I in the list so 0 to whatever the counter it so I plus J so that is what I'm going to create a key so if it is not there in the key we are going to create a new map a new entry for that once it is created we are going to add the corresponding element into that particular list so basically what we are trying to do here is we are doing this map ok map of all the elements and corresponding map with all indexes or the keys and corresponding elements right so once you have that map in place right so you are going to get the each individual list and merge into a big list right so now with this for loop we are doing the mapping and now once a map is available what we are going to do is so create an answer list that we want to do and we could do what for I is equal to zero I is less than map dot count so we know how many number of map entries are available right so map dot count ad right for each for zero with our go to add one the zeroed list firstly secondly stir list for a list to the answer now right so answerless sorry so answer list so that's what we are going to do so basically we will be keeping a bigger list here right one and four seven five eight nine so this is a bigger list so this is our answer list so this is finally we are going to return right by converting to our because it is expecting that right so if you don't want to create a basically list and convert into array right so you keep track of the number of elements that you are adding here right and then simply create an array of that length and add elements into that array and you're good to go so anything it will work so basically instead of creating array and creating a list and finally converting it to an array before returning so that's how the code is going to work let's go ahead and look at the time complexity for this algorithm right so basically since we don't know let's make an assumption right make an assumption you have n lists right and on an average on average you have M elements in the list right M elements in the list since we don't know right so we are say saying on average we have M elements in the list so in this case what we are going to do here is so this is going with order of M into n right so this for loop is going through order of M into M right so the time complexity will be order of M into and where m is the number of average number of Lists amaura average number of elements in the list n is an so that's the this is what is using to create a map right so once the map is created right we go through the map and try to prepare the hamster for it so the map will have how many entries at the max it will have maximum of two into and right that's the number of elements it's possible but there are constraints that are given let's go ahead and look at the constraints right so the constraints are 10 power 5 so the number of lengths so the list number of lists could be 10 power 5 and each list could contain 10 power 5 right and each number is 10 power 9 but we are saying we are certain we are given an another thing is there could be maximum of 10 power 5 elements in the list of the numbers right so the maximum elements could be only 10 power 5 that means if there are 10 power 5 lists that means there are only 1 element in each list but if there are less than that there in some lists there are more elements in some list there are less elements so that lists are not homogeneous but they're heterogeneous that's why we are saying average number of elements in the list are M so the time complexity for this will be order of M into n over all right so that's the time complexity and the space complexity for this right so how many what space we are using actually right so the map that is 1 and this is answer away that we are going to written so the answer array will have the same number of elements as the list of lists right so that means a space that we are creating here is order of MN right because we need to have that minimum right so order of M into n is the space that we are going to create for the answer array so that's one thing and how much we are going to you create for the map also so the map also will have typically order of M into n elements in the list so the basically here right so here so if you look at this map right so this will the right side the values will have 1 4 2 7 5 8 9 how many are there basically 3 plus 2 1 3 plus 2 plus 1 6 elements right so 6 elements are there in the map as well right so that will be also storing em into them right Plus this element right M into n plus the elements onto the website right so but these are more than this right the worst case this could be also M into n right so the on the whole the space complexity will be order of M into n from this particular algorithm if you still have any questions please post them in the comment section below the video I will get back to you as soon as I can just to want to remind to again mi again if you haven't subscribed to my channel please go ahead and subscribe I will and all go you'll also get notifications if you click the bell icon for all my future videos also please share among your friends I'll be back with another video very soon till then good bye
|
Diagonal Traverse II
|
maximum-candies-you-can-get-from-boxes
|
Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Output:** \[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16\]
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i].length <= 105`
* `1 <= sum(nums[i].length) <= 105`
* `1 <= nums[i][j] <= 105`
|
Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys.
|
Array,Breadth-First Search
|
Hard
| null |
1,423 |
That a hello everyone welcome to day life and asked questions maximum points content from girls without much electronic media subscribe servi element every time subscribe our channel subscribe yes all good give what do we news lighting up to the minute Problem Unlimited Subscribe Element subscribe to subscribe our we will provide you number from this sliding window and wever will reduce 25th 800 to 1000 subscribe updated on the heat of an alarm set and the game will reduce the famous mountain increment the mid point of that parts time will delete 422 - 118 plus that parts time will delete 422 - 118 plus that parts time will delete 422 - 118 plus one is not listening to me because probably witnesses were present in the professional this free will reduce 390 three layer 69 subscribe 5 to connect with this ftu 200 will reduce 225 the best wishes to unmute last will the knowledge more Product And Reduce Minus Plus 3 A Bright Most Shifted To Live With Which - Stand Shift Plus Three 500 Which - Stand Shift Plus Three 500 Which - Stand Shift Plus Three 500 600 Subscribe Our Loop Swapna Dosh Subscribe To That Boat Lets Move Wedding Point For Central Government To Give Its Elements In The final of the elements to subscribe to that potato white stain pimple entertainment shoulder length of cut points' twist and from shoulder length of cut points' twist and from shoulder length of cut points' twist and from inside the plank the final result musam Video subscribe but you have been appointed president the elements of sexual intercourse also meet updated and will reduce belly fat the last point Undhe Something Like That Point - Verb - A Point - Verb - A Point - Verb - A Hai White Saree Minus One And Will Not The Video - - 1 Ka Video - - 1 Ka Video - - 1 Ka Yaad Of Contract Updated Walia Elements Of Sex To Welcome A Good Marks In Love With U Hai Na Sambhav Sexo Ke Limits In This Immediately Left Side reaction in veer and subscribe to a whatsapp text looks great time complexity of this approach her daughter of that inside space complexities place and not using in raw one calls subscribe Video subscribe to hua hai
|
Maximum Points You Can Obtain from Cards
|
maximum-number-of-occurrences-of-a-substring
|
There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain.
**Example 1:**
**Input:** cardPoints = \[1,2,3,4,5,6,1\], k = 3
**Output:** 12
**Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
**Example 2:**
**Input:** cardPoints = \[2,2,2\], k = 2
**Output:** 4
**Explanation:** Regardless of which two cards you take, your score will always be 4.
**Example 3:**
**Input:** cardPoints = \[9,7,7,9,7,7,9\], k = 7
**Output:** 55
**Explanation:** You have to take all the cards. Your score is the sum of points of all cards.
**Constraints:**
* `1 <= cardPoints.length <= 105`
* `1 <= cardPoints[i] <= 104`
* `1 <= k <= cardPoints.length`
1\. The number of unique characters in the substring must not exceed k. 2. The substring must not contain more than one instance of the same character. 3. The length of the substring must not exceed the length of the original string.
|
Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce.
|
Hash Table,String,Sliding Window
|
Medium
| null |
146 |
hey guys yeah so welcome to my little sony session i hope you guys subscribe to my channel yeah so this problem is called lru cache uh this problem is very difficult but if you use python then there is a shortcut that you can solve this so let's do it so uh lru cache basically uh initialize the lru cache with uh yeah so this is called list reason used okay so very technical so you have a cache and a capacity so that means this capacitance can only it's the upper bound and you have get key return value of key if the key exists otherwise return -1 if the key exists otherwise return -1 if the key exists otherwise return -1 uh and you can put key and the value if the value exists if the key is that you need to update uh otherwise that uh and if it sees the capacity then you just you need to delete these at least the use so this is very uh difficult okay so in a round o one in average case okay so for example uh yeah this is an example so you initialize and the two is the capacity and you put one and then you put two and you get so once you get you will get one right so uh so key is one you get one so now uh two will so not to be the least used right okay so now this is a key point right because uh because that's the let's see right so uh remember that uh so in the beginning one wise in the between uh in the first step and the second and then you get one right so once you get one and one becomes the uh like uh okay so let me just put this array so this is the least use right this is the reason used okay so one won't become reason use okay and then you put so now you put three right and then you already you get three right but you already so you get 3 which let me just push here but the 3 is already larger than the capacity so all you need so you need to delete the 2 okay now you get and uh you put two uh sorry honestly you get uh you get two uh you get to become minus one right because two already delete and you put four uh right you put four so you want to put four here you do four here right but now you already have three elements so one get delete okay so once you get one minus one return okay so uh the problem is that you need all what right so the idea uh what we're gonna to use is there's a thing called order or a dictionary in python so the only difference in the usual dictionary of the dictionary that this order dictionary will remember the order of the key so when you add key then you will maintain order and the e has two property that the first is pop item so the pop item will uh if you do not do anything then it will return the last the so that's in first out so you will return the last element okay and if you return to them will kill the first app so basically it's like the order dictionary right which your dictionary has sorted and you can use these uh pop items to delete the first or second so this is exactly what we're going to use okay and then there's a guy called move to end right so which is very powerful that so move to ends that you can move at least this key to the end okay so this which is a dictionary by the order okay so let's uh capacity just initialize and define cache to be ordered dictionary let's say get so if key i mean if key is not in cache then written minus one right this is trivial if key is in cache then you should return a key right but uh you need to remember you need to toy to be the reason used so you need to put to the end let's say the end is a reason used so you need to sell cash move to the end okay and you put uh you just update the value and uh and you need to move this key to the end right because now it becomes the region used and then greater than the capacity you need to kill the first guy right kill the first guy use the pipe item and the last force with all this is the killer uh so it should be evit the least reason uh used right so this is very simple that if you know the order list you can yeah i mean if you do not use python line you need to use a dictionary and a link list and combine everything good okay so yeah see you guys next videos
|
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
|
198 |
what's up guys this is liq old 198 house robber you are a professional robber planning to rob houses along a street each house has a certain amount of money stashed the only constraint is stopping you from hobby each of them is that Asian sent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night given a list of non negative integer it's representing the amount of money of each house determine the maximum amount of money you can rub tonight without alerting the police so example one this is the amount of money that is in the house and we need to come to calculate how a winch hopefully the most amount of money we can rob tonight without alerting the police so we need take care because we cannot rob these two here because they are adjacent houses but we can rob these two here and let me see this one here at the same example but in this case I think it is so seven ten or nine plus 110 plus Church okay plus 2 12 yes and I know this problem the most effective solution to solve this problem is using dynamic programming and it's not a it's not an easy subject to understand in my opinion and I think the only way to understand dynamic programming is to first you need to know what is dynamic programming and you can search on the internet you can Google what dynamic programming is and after that you can understand some approaches you can use to apply dynamic programming you can use matrix you can use arrays and you can use hash maps and other things I think that the base knowledge of dynamic programming is that you can save and you can save prettiest computation to use in the future I think that's the base of dynamic programming but it's not easy to match this solution using dynamic programming with an exercise and I think to get this knowledge you have as I said before to understand you need to understand first what is dynamic programming and after that you need to practice you can come to litical and filter the questions by the dynamic programming tag and start to practice and yes you will probably yes I think you will not get it in the first time you need to practice a lot and after you practice a lot to you I think we'll start to understand what dynamic programming is and when you see an exercise you will start to match the solution using dynamic programming with the exercise itself so we will solve this exercise using dynamic programming in within a range to the soul to save previous computation and after that we will so also using just two variables because that's the purpose we actually need so I will explain the exercise when we straight I will explain the solution when we to write some code because I think will be more clear to see the code instead of them explaining here okay so let's try it write some code so as I said before we'll try to explain the idea the base idea or this solution let's try to use this example here and I think that we can start by thinking that we have to come to know the people to know what is the maximum amount of money we can get here the only way we can do that is by it is by trying every possible solution here so we have to try this combination so this is the only way we can find the solution then what is the most amount of money we can get here and we can do that I think in a lot of ways maybe there are a solution that maybe there is a solution that we can use multiple for loops to try different combinations and we can also use as I said when I was reading the description that we came with dynamic programming so the thing here is to try every possible combination we have to try what the exercise is as pians we have to try and two houses that are not adjacent houses to get the most profit into these houses to get the most amount of money we can do that by declaring another integer array these integer we will have a link later than this one we can't expect this I really like I think liked it so lemme lots more so we have one index more compared to the input array and why we need it that because we need a helper value here which will be the first value why we need this because if you want to compare the first pathway with the previous rounds the de previous house that we are allowed to combine the amount of money here in the nonce array we do not have and we don't have any number here and produced 1 so this 0 here is we are simulating this number because NY is 0 because we will not interfere into the result because if you are doing a calculation by if you are doing a sum with two numbers the result will be the number that is not 0 in this case and here we will start to do our checks so we will start to check if the current number in the in this DP array is greater then the current number in the month are very balanced the previous number that we are allowing to make this calculation in number that is not adjacent with the other one so this is why we are using the this DP array and this is why we are starting these array with the value is 0 okay so let's start by checking if the input is valid so if the input is valid if you the input is not valid you can just return zero after that we can set the first index of the de Pury to zero and we can also set the second index to be the first number of the numbers array after that we can start our for loop and for loop we start at the index one because we start to check if the current number in the GPRA is greater than the calculation that I said before a wild start line my eyes is like Linda Mullane and I plus closed so yes I don't think we even need the practice here because we need this we did only one line of code here because we will set to the current index of dipti it's actually not a clean we will set the next index of TP because as you are seeing here we already set it the decrement index of TP and we will set the next one because we will compare if the current index is the much is the most amount of money that we will get here indeed to house of these two houses that are adjacent houses so the calculation here with the new method max to get the maximum value between two integers and I think the first one will be the current value in which it in this case the Quinta fell away in the first index in the noms array and we will compare it with the nouns of I close the GP de Pury oh I minus one so here we are doing exactly they think the thing that eyes that I showed before when I was explaining the direction now into this solution okay so when we get all of this for loop the last index of the DPR a will contain the result for this exercise so we just need to return the DP and if we do not have any typo I think this is the solution yes and it's example let's try to hit submit yes that's it so as I said before we can first thing the detect complexity here is Big O of n where n is the length of nuns and the memory complexity is also Big O of n because we are allocating the same amount of money the input so if the input gets bigger the allocation will also gets bigger but we can change this solution because if you see here we are just using the one bot last and the last element of this array and we can change these to use just two variables and to do that we can declare here a firm hold one to the list and also a verbal list here we can't in now we will practice because we need to try some we need to do some if statement here we only in here then let me see so we will need an axial parable because we will probably change the pelo a switch may want to the last and the last forever so until you're purple to get the last bellowing so we can check if the last is less than this calculation here so let's get the use here and if last it's less than nonce plus DP of I we can swap the pelvis so we can get here we can put this inside the bit statement and let me see you can put into the last parable the result of I was DP of I and minus one and yes we can put into the one to the last verbal and here that's it otherwise we can just set the one to the last parable the last this else here is in the case that the last parable the amount of money that is in the last variable is greater than this calculation here so which means that we are we just need to put the current value of the less verbal into and if we were using array their resolution into the next index so when we get all out of these for low you can just return the last verbal so we will not have the array anymore so here is the one to the last verbal and also here let's try to run again notes so it last is less than months of I plus 1 to the last here we are saving last it's supposed to close one to the lives on to the letter T close to last I'm not sure where you instead ever let's try to see again so we are putting the right families here we are to meet the check if last it's less then ten months of I plus the one to the last and if it is we have to set the result of this population to the last purple and this is not last this is out here yet because you're needing it we are doing a swap of the fellow is here yes fine difference excellent phone ok that's right to hit submit nice so time complexity here is it still we go and or n is the length of months the array of nuns and memory complexity different from the trivial solution here is constant because it doesn't matter how big your noms get we will always be allocating just these two variables here also three variables because we have these two controlling the index but I think it's a better solution if you compare with the previous one that's it guys thanks for watching
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
1,525 |
uh hey everybody this is larry this is q3 of the reason the code contest uh cool number of good races for the string uh yeah so the idea here for me is just uh well you can actually i think to in retrospect to be honest i could have done this a little bit better i would have just kept it set um uh so i did it so in code i did it one way and i'll go over it but the way that i would do it is just going scanning from left to right keep a set um and any time you insert a new element in the set well then there's a plus one from the previous thing and now you have a prefix right and basically you have a concept of keeping track of uh all the counts from left to right meaning it comes up what's up meaning okay now you know you process the first a g hmm this is a little bit weird my computer's a little weird sorry yeah if you process the first okay i just copy and paste this string then uh you process the first a uh you have one unique character two kind of characters two connect three and so forth so it's monotonically increasing and it can only increase by one right so then you construct this left camera right uh and then you do the same thing for the right just going from right to left uh so now you have one now you have two you have one oh sorry you have two you now you have three and so forth right so now that you construct the left count and the right count uh you just have to do one final pass to see uh okay if the left count is you go to the right count then we just increment counts to go to one and that's all there is to it um i did this with bit mask uh see if you can understand it but it's not a big deal knowing how i did it now um i probably have just did a set and then just go for from right to left and left to right and then check it one final time uh cool so this is linear time and linear space uh yeah that's all i have for this one uh let me know what you think and watch me do it live right about now that was too slow people already done another poem okay hmm you this hmm let's see hmm just hold by one um why it happened off by one hmm oh this is not c this is okay
|
Number of Good Ways to Split a String
|
queries-on-a-permutation-with-key
|
You are given a string `s`.
A split is called **good** if you can split `s` into two non-empty strings `sleft` and `sright` where their concatenation is equal to `s` (i.e., `sleft + sright = s`) and the number of distinct letters in `sleft` and `sright` is the same.
Return _the number of **good splits** you can make in `s`_.
**Example 1:**
**Input:** s = "aacaba "
**Output:** 2
**Explanation:** There are 5 ways to split ` "aacaba "` and 2 of them are good.
( "a ", "acaba ") Left string and right string contains 1 and 3 different letters respectively.
( "aa ", "caba ") Left string and right string contains 1 and 3 different letters respectively.
( "aac ", "aba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aaca ", "ba ") Left string and right string contains 2 and 2 different letters respectively (good split).
( "aacab ", "a ") Left string and right string contains 3 and 1 different letters respectively.
**Example 2:**
**Input:** s = "abcd "
**Output:** 1
**Explanation:** Split the string as follows ( "ab ", "cd ").
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only lowercase English letters.
|
Create the permutation P=[1,2,...,m], it could be a list for example. For each i, find the position of queries[i] with a simple scan over P and then move this to the beginning.
|
Array,Binary Indexed Tree,Simulation
|
Medium
| null |
203 |
hi welcome to data structure and algorithm series by coding ally is a non-profit organization where ally is a non-profit organization where ally is a non-profit organization where we believe women and gender minority should have a safe space and support system when they can foster their skills and careers in tech i'm your host sue today we are solving this legal problem 203 remove linked list elements this is the agenda first i will read the problem statement then i'll go through the thought process followed by step implementation of the thought process in both javascript and java i will read the problem statement given the head of a linked list and an integer file remove all the nodes of a linked list that has node file equal to val and return the new head let's have a look at the example one in here we have got this linked list one two six three four five six from visual observation we can see that these are the two notes that we need to remove so after removing it this is the linked list that we have and the head is still 1 but we have removed 6. so in this example 2 there is no element in the linked list so the output is the empty linked list this example give us an edge case to consider what if there is no head in this case we just simply return the empty link list next let's in example 3 all the linked list note have the value 7 which is the value that we need to delete so in this case we just simply return the empty linked list so for the constraint the number of the notes in the linked list is the range it's in the range between 0 and 10 to the power 4. and note value it's between 1 and 50 inclusive the value itself the value that we need to delete the value range is inclusive 1 and 50. there are two approaches that we can use to solve this problem in this video recursion and iterative using sentinel or dummy node in this video i will focus only on the iterative approach before we start let's think about how linked list is stored in the heap memory this is the memory allocation diagram in here you can see the stack memory is smaller compared to heap memory and it is fixed size stack memory is used for storing the variable recursion and control jam linked list here this is it is a dynamically expanding data structure and it is not conta it is not stored contiguously in the memory and this is the one this is one of the key advantages of linked list over array so in here we can see that so this is the linked list example given but how this is actually how the linked list is stored in the memory address so we've got six and three will not be right next to six because it is not stored contiguously 6 has got the pointer or address that points to the that store the address space that from that address space from that address we know that 6 is now six is pointing to three so this is how uh linked list is stored in the heap memory next the concept that i want to introduce is uh two things sentinel note and dummy note as per wikipedia this is the wikipedia definition about the sentinel note as per the wikipedia definition in computer programming a sentinel note is a specifically note a design node used with linked list and tree as a traversal path terminator in this type of node does not hold or reference any data managed by the data structure dummy node it goes to at the front of a linked list the node is there only to reduce the need for a special case code in that linked list operation so what does that mean dummy note so what why do we need dummy note we need it to pass the head of the linked list in the function if you keep changing the position of the head node and you need to return the new head node the problem the thing that you need to consider is how are you going to return that new head node so therefore you need to create a dummy node and make it point to the head and move only domino not the head node i'll go through the example in detail so that you understand this concept so in here we are using the iterative approach let's think about generic approach using their uh generic approach one solving this linked list problem things to keep in mind there are two things that we have to keep in mind first use the domino to keep the head value if you can this will help us with that corner case second think one breaking the connections let's say you want to break the connections between six and three and how you are going to store the value the note value so let's start with step one in this step if head node head is not null and head doorbell is equal to bell then we have to move the head to head.next we have to move the head to head.next we have to move the head to head.next this step is to ensure that we are at the value that is not equal to the given value if you have a look at this example it will be clearer example three example one six is the head node six is equal to six this is the value that we need to delete so we will move there head to head down next in here example two all the values are equal to the value that we need to delete so at the end the head will be pointing to null so this is step one step two we step two in two step initialize the dummy node and make it point to head like in here and we will use two pointer we will initialize two pointer previous and current assign dummy to the previous assign head to the current so starting point the head is pointing to this current note 6 here so in here step in the step 3 we will check current while current is not null pointer means we are going to go through every single node until the end and we are going to compare if the value current or val is equal to well if they are the same we need to delete it so how do we delete the note in the linked list we need to skip it so we will move the previous to there we will make the previous point to the current or next so this we are skipping and then after that we have to move current to current on next so this is how it's done in here the value that we want to delete is 6 so 6 and 60 are equal so we make previous make it point to current or next and then we will move the current to current on next so in here three and six they are not the same so we move both uh previous and the current so after we move this is where we are now so we will check four and six they are not the same again we will move both pointer and currently pointer is at six head at six so six and six they are the same so again we will skip it so now finally current is at now so we are at the end of the linked list and we will return it this is the step four okay let's go through there code line by line let's implement step one in step one we have to keep going until the head value is not equal to the value that we need to remove so this is the while loop this is what it's doing while head is not equal to null and head to eval it's equal to well we will move the head equal to head.next equal to head.next equal to head.next step two we'll first initialize the dominoed and we will create the dummy node and we will make this domino dummy.next make it will make this domino dummy.next make it will make this domino dummy.next make it point to head and then we will create another two pointer previous and current make it assign dummy to previous assign head to the current and then we will implement step three in this step we are checking every single note in the linked list and we compare while we are going through that when we compare if the value are the same we will make the previous donate point to their current on x this way we will skip otherwise we will move there previous to the current pointer because we don't need to skip it by the end of and then once we finish if and else block we will move the current to current or next so the reason we have to move the current regardless of if an else condition is that we have to check every single node so therefore we have to we bring this current equal to current on x here like so here so step four we are returning the head so let's discuss time and space complexity the space complexity we have in here as you have seen we only create the dummy node and then we use the two pointer they are all they all take up constant space so in terms of space complexity o of one in terms of time complexity we go through every single note in the linked list so the time complexity is of n and this is the java code concept is also exactly the same so i won't go much in detail first is step one we will check for the head it's not now and head draw value if the value is the same we will simply move the head node this is step one this part is step two we will initialize the domino make the domino point to the head we will use two pointer previous and the current this node previous assign dummy to previous assign head to the current step three we check through we check every single note in the linked list if the value are equal we make the previous point to the previous donate point to the current next we skip otherwise we move previous to the current space current and node and then we will after that we will move the current node and then this is step four we will return the head so let's summarize what we have learned so far three things that we have learned first memory allocation stack and key space how linked list is stored in the heap memory two what is the sentinel node dummy node the importance of them and then step by step approach of the step-by-step approach step-by-step approach step-by-step approach iterative approach to solve this particular problem so thanks for watching please make sure to subscribe and press the like button if you find this video useful join our weekly and fortnightly wednesday data structure and algorithm night where we organize peer-to-peer night where we organize peer-to-peer night where we organize peer-to-peer coding interview you can find the event details in our facebook page thank you
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
105 |
a we're looking at lead code number 105 it's construct a binary tree from pre-order and in pre-order and in pre-order and in order traversal and so here we're going to get two integer arrays a pre-order and in two integer arrays a pre-order and in two integer arrays a pre-order and in order where the pre-order where the pre-order where the pre-order is the pre-order traversal of a binary is the pre-order traversal of a binary is the pre-order traversal of a binary tree and the in order is the in-order traversal of that order is the in-order traversal of that order is the in-order traversal of that same tree and we want to construct and return the binary tree okay so here are pre-orders 3 9 20 15 okay so here are pre-orders 3 9 20 15 okay so here are pre-orders 3 9 20 15 and 7. in order is 9 3 15 20 and 7 and we construct this binary tree here okay so let's jump in the conceptual this is a tricky one to get your head around if it's your first time seeing it but the main thing to keep in mind here is that we want to look at the definition of pre-order and in order the definition of pre-order and in order the definition of pre-order and in order and how do we get the ordering of this tree so pre-order so pre-order so pre-order is going to be starting at the root okay it then it's going to go let me make this clear here so it's going to start at the root and then it goes to left and then it goes to right okay and in order is going to start at left it's going to go to the root and then go to right so we know here in the pre-order this 3 so we know here in the pre-order this 3 so we know here in the pre-order this 3 right here is going to be our root okay and so what we want to do is we want to in our main function we want to go ahead and get that value at the zeroth index and set that as our root then what we want to do is we know that the root is going to be we know what the value is for the root here we just want to find the index in order so here the index is at one okay and now what we know is that everything left of this in order is going to be the left subtree and everything right of this index is going to be the right subtree and that's what we want to recursively call throughout through our function and just let it recursively build out that tree okay so that's the idea behind it i'm going to jump in the code because i feel this one is a is much clearer once we actually code it out than trying to figure it out in the conceptual so what we want to do here is first we want to set a base case so if pre-order so if pre-order so if pre-order and in or in order is empty we want to just return null okay or in order we just want to return null okay so now what we want to do is we know that the zeroth index at pre-order is going to be zeroth index at pre-order is going to be zeroth index at pre-order is going to be our root so let's go and set our root is going to be um we'll go ahead and instantiate a new tree node with pre-order at the zeroth index okay and now we want to go ahead and get our mid index on in order okay and so all we have to do here is we just say let mid equal in order index of and then we can just do root.val okay so this will give us the index of where our root is in the inorder array now we just want to build up on our root recursively so we just want to do root dot left which is going to be build tree okay and we want to do pre-order okay and we want to do pre-order okay and we want to do pre-order dot slice and we want to start it at one and go to mid plus one okay we're going to start it at 1 because we have already accounted for this 3 here and then we just want to get everything on the left side of the tree okay so we'll do mid plus 1. and now we can do in order and slice here and we are just going to do 0 to mid so that will get us our left tree now we just want to get our right tree so we do root dot write and then here we do preorder and we just want to do mid plus one because everything on the right tree is going to be right over here okay so we know we have our mid and we just want to get our pre-order and we just want to get our pre-order and we just want to get our pre-order plus one and our um our pre-order at mid plus one and our um our pre-order at mid plus one and our um our pre-order at mid plus one and are in order at mid plus one as well and then once we have got our left and our right recursively we just return our root okay let's see here oh mid index we'll just change this to mid okay and there we go now a challenge that you can try is instead of slicing these arrays could you do it with the indices we could get much better time and space complexity if we use indices instead of slicing the array so we just use the same pre-order and inorder array maybe set a pre-order and inorder array maybe set a pre-order and inorder array maybe set a left and right counter and then see if we can just use the indices instead of slicing but that's a way we can get better time and space complexity okay so that is leap code 105 construct a binary tree from pre-order in-order a binary tree from pre-order in-order a binary tree from pre-order in-order traversal hope you enjoyed it and i will see you on the next one
|
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
|
399 |
Hello gas I am Lalita Aggarwal welcome problem what are you saying ok before going you WhatsApp problem no 1 minute on registration two signs are one problem I have understood well which are some to try once, there are six questions, see these questions. It is literally a very edgy question, there is nothing to be stressed about, just what is the most important thing that you care about here? 2.0 Whose value was this, 2.0 Whose value was this, sorry A/B Apne Ko Value Jivan Thi 2.0 sorry A/B Apne Ko Value Jivan Thi 2.0 sorry A/B Apne Ko Value Jivan Thi 2.0 Okay, absolutely correct, now if I say at this point of time, the value of B / B is 2.0, then what will be the value of B divided by A? value of B / B is 2.0, then what will be the value of B divided by A? value of B / B is 2.0, then what will be the value of B divided by A? One on 2.0 1 / 2.0 One on 2.0 1 / 2.0 One on 2.0 1 / 2.0 Just need to have clarity, rest so what has happened here. Multiplication will happen. Multiplication has been done. It will become very easy. Think a little bit about it and then I am going to open it in the video if you are facing problem. They did not understand the problem. There is no need to take tension. First of all. You are going to understand very easily that what is the question of saying six, after that we will make the next approach and finally give the bill move towards its implementation. Let him understand that the question of saying six was the next question. I told myself that this was the Eric one and said absolutely. That's right, one is this and one is this region, these are three different areas. Now, first of all, it is good to say that in the first area of Ram ji, what should I first area of Ram ji, what should I first area of Ram ji, what should I say? First of all, it is important to say that in this area some of my own. Pass different areas are given, meaning these are the arrays, I said ok, there is no problem, so what was the second one in this, what is A/B in this, so what was the second one in this, what is A/B in this, so what was the second one in this, what is A/B in this, so what is the meaning of A/V, so what is the meaning of A/V, so what is the meaning of A/V, what is the value of A/B? Value is the what is the value of A/B? Value is the what is the value of A/B? Value is the first one. Okay, so 2.2. If you understand, first one. Okay, so 2.2. If you understand, first one. Okay, so 2.2. If you understand, then you can also say 2.0. You have then you can also say 2.0. You have then you can also say 2.0. You have double value, basically, there is nothing else. Okay, what is the meaning of B by C? What is the value given in B/C? What is the value given in B/C? What is the value given in B/C? 3.3 Okay, now at this point of time, 3.3 Okay, now at this point of time, 3.3 Okay, now at this point of time, tell me how to get it, I don't have a simple calculator, right, you reduce one, then what will happen here is simple, that B and B will go, then the value of your pass will be A and in the bicycle understand. Now if you understand the point here, then you have already understood that what is your life in the equations, this equation said it is ok and what did I do in Waluj, I told myself its result, this one said it is absolutely ok. It is right, now what life do you have in Varij that you have given this condition, you did not tell yourself what will be the A/C, will it be not tell yourself what will be the A/C, will it be not tell yourself what will be the A/C, will it be like that, have you calculated, said yes brother, what have you calculated, six, so this is It's sexy. Now why did zero come here? Because it was to return one's up in double. There should be no doubt. Now tell me, what will be the value of V/A? no doubt. Now tell me, what will be the value of V/A? no doubt. Now tell me, what will be the value of V/A? What will be the value of B by A? So A/B's own life was that. So A/B's own life was that. So A/B's own life was that. So what will you do in your view, its opposite is first. What will happen if you do its opposite? 1 / 2.0 There should be no problem. / 2.0 There should be no problem. / 2.0 There should be no problem. 5 will come. It is absolutely correct. Then tell me what will be the value of A by 1. Tell me immediately. Brother, the value of A has to be calculated here because the value of A was not available on the story. You could have calculated it by doing anything and applying any formula, but the D value of C was not available, so it was said where there are such conditions. Hey, go where you do n't value life at all, there you will adopt - 1 n't value life at all, there you will adopt - 1 n't value life at all, there you will adopt - 1 is simple, 100 brother, it is simple, now what will be the value of A / A, I is simple, 100 brother, it is simple, now what will be the value of A / A, I is simple, 100 brother, it is simple, now what will be the value of A / A, I said to you, brother, this brother, the value of A will be one, it is completely fine, then X / What will be the value of The then X / What will be the value of The important thing is that how much will you give the value of It is important to have an understanding and still give the pulse, now how will we do it, tell us the method of approaching it, that is, A/value of A/B is the value of you, that is, A/value of A/B is the value of you, that is, A/value of A/B is the value of you, then one is the value of B by A, what will we say by playing one by, it should not be so clear. Must be that today this much is clear, okay then what was the value of a5 given to you, whatever is the meaning of which you said, the value of V is life, you have one of the value of C, whose meaning is one, what are you saying? That you have the value of C/A saying? That you have the value of C/A saying? That you have the value of C/A is also life, meaning the tax value can be there many times. Here we will apply the method of graph. The method of graph will be applied in this, once in a while, a little bit, friends, in 5 to 10 minutes video, if your Now, if we discuss how we are going to apply our graph here, then we will come back to simple calculations, what will we say, first of all, okay, with whom is A's connection being made? What is the point of saying that A's connection with B can be military? Direction, with whom is it happening? What is the value? Are you understanding? If you are understanding, then how do you make the connection of Apna Graphite? Normally, Apna Graphite connection is a simple thing. Apna ke liye said yes. Yes brother, now let's make it up as to which ones we have this, we have B and we have simple. Yes, tell us where from A you can go to BP. How much value will you give for your life, you have value, there should not be any doubt and what is my value for BP life, there should not be one by doubt, you should have clear brother, now you have made it complete, after this your What has to be done? You have to see that there is a connection between life from I came to B, okay, tell me where can I go, then he said, one, I could go from B to C and one could go to A. Bullet, that's right, now where am I from A, I have been from A to A. So I am the first thing, I will not go to A, if the quality of life is fine, then I can go to you with 20. I said okay, so whatever I sip, is this my destination? Yes, brother. Whatever return I have received till now, I have to multiply it, now how will I return, let's check our connection now, first let's see how we will fit his connection, it is a simple thing. Now, from here to B, this love Na said to Apna, okay, so Apna here, where can I go directly from B, you mean right now it is not even on time, I said, this is absolutely right, so now if I see Apna, then this Apna here is this one. So what went wrong? Can you go back and forth from your C? Is this your destination? Your destination is tired. Similarly, then you sent these more emails, now you went to reply K. Is it okay if you get an email from A? So you came to camera A and saw that Now I can go back, it is ready, you can go to B, again you saw, he said, this and C can be drunk, I will not go to A, I can't go, he said, okay, now where can you go, he said, it can be drunk, but What already happened, so now I am not going to go ahead of it, so where it becomes possible, what will we do there, one return of mines is simple, it is absolutely right, so for this, we will have to give a separate condition to ourselves. Pay attention to this, that is why I have done all the trades and shown that it is clear, then what will happen here, if you pay We will directly return mines one. Okay, now as soon as we were here at C, what did we do? As we were at A, we tried to come from A to B, so we kept this here. Gave this, then I went from B to C, as soon as I got the destination, I saw that K means what is the cost and said ok, what is the cost of coming back BP means I returned here six, there should be no doubt, you are in these. Let's look at its paper, this was a function in Apna which was to be built, here I have come, what did Apna say? First of all, there should not be any doubt about its size. Well, this is a question, Apna Yaar, this equation or okay then Apna first. On the element and on the first element, you will also get the string or you said, ok, it is clear, yes, it is clear, there was no doubt till now, then what did you do by giving a double name, created a variable named value and in it you And took its value, okay, so what is the value of life from A to B? It is 2, that is, 2.0, then what did you say after that, if you push it inside any graph, then what did you say? In the graph, if you say the path of life from A to P, then what did you do, that is, you pushed the value inside A, there is no problem, but when you push one more along with 20, then what will you do? One bye, this is your good. There should be no doubt in this, here our graph has been made, our half has been reduced here, what will we do in its bigger form, we will give a simple name. It is simple, now here a widget has been created for this, we will create separate widgets for everyone and it is absolutely correct, why did we create a widget, so that if you have gone beyond A once, then you should never go back to this again, otherwise. He will just keep going round in the same look, there will be no sensor left, there will be an area. Okay, so what have you done here within your direct result, this is a function. Now what is this function? Understand carefully what all are you passing on in this function. What will be the zero of the query then what will be the zero of the curry? This is the a² of the query. I have passed my string and said, OK, so what did you check first? Does the source also exist or not? If you are the first one, then tell me that if it does not interest you, then end out discussion is done as to why you have created it or did you have to create PAN here for X because it is X only? If Apna did not exist, then what was Apna there? 1 call of mines. Okay, so here Apna has done this, then Apna has added another condition that if Apna's source and destination are Apna, then return it and Apna has become it. For whom has it been made or has Paneer been made for this condition because we have discussed it, there should be no doubt, he said yes, whatever is clear, then what have we done, we have given a new condition, so what have we done, so reset the source. I did that brother, this is my A, it is clear, then what did you say in your loop, reduce one, in your loop, what did you say in your loop, reduce one, tell me where I can go to the source code, he said, okay, so from A, you can go wherever you want. He will go on his road to What did you say? First of all, tell me, had I already done it? Well, one thing is important, what is your mood? B has come, I just said, no, brother, I am in the mode, I will wait, are you okay? Yes, then what will I do? Its first value. If I access then what is the first value? Call me also. Okay, so now first of all I have checked whether I have already been rejected. Said no brother, you have not visited yet, so now what did I do here with double name. I have made an over rest and during rest I have done office and what I said in this function, if you give this function then what will it do in my chapter that this story is not my destination and if it is not then from here onwards till the destination of my life. Is there any way, is it a simple thing, so it went back here, went back and checked whether my solar system is present, if it is not current, then what is being checked now, then basically the destination is being checked, has it been checked? My definition has become equal, so if I had to come from A to B, then it becomes equal to me here, it is a simple thing, so it is not equal yet, thing, it is a simple thing, so it is not equal yet, first, sorry, this has not happened yet, first. It's a simple thing, then I said, please insert my BP and brother, it went from A to B, there is no connection, okay, there is a connection, I have seen that it continues, okay, so what about yours? If Sita's own person is no longer there then what will he do now? He will say that this is our own BF connection, it will be repeated, we will get our own connection, we will do a second on the story, note dot, what is your own in second? You must have understood it well. Still, any doubt would have gone. Comment box and yours and beer. Tell me its space complexity of the city. Look once, the cement has been made comfortably, what will be the flexibility from space? First of all, we come here, we discuss our body, see what we do here. First of all, have you created another variable here, then leave it as a constant, then did you trade with four people? What did you do here, what would you have done, were you storing them? Said, it is absolutely correct, your notes. Had you stored it would have become time to store it on notes. Just said, yes, whenever you store two connections between you and yours, then the meaning of life from A to B is absolutely correct, which is that your life is this by B. But Apna Ne B by Ek Yeh Bhi Edge Jo Hai So Kitna Ho Gaya V Plus Tu Hi Kya Hai Ha Means Apni Number Of Ha How Much If You Have Died It Will Remain So Apna Kya Hai Plus Ok So Apni Space What Will Be The Graph Of V2? It's a simple formula, it's a simple matter, is there any doubt in it, okay yes, thank you
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
927 |
Hello Everyone Welcome To Do 7th July Liquid Liner Producer Equal Parts In Distress In The Given RS Winters Veeravansh Me Too Died Due All Into Three Parts Diner Dash Lottery Number 200 Blouse Strong Network Gives Two Presentations Back Parts In 10 On Twitter Lead 987 Which Makes Heart Patient Dance Light Difficult To Understand So Let's You Step By Step Will Understand The Question Blouse Inputs And From That Question And You Will Come Up To Not Elaborate Let's Get Started List Friends Equation Considered Only 30 Months Video Tarzan Shift Subscribe Number That this division is possible Neetu Don Dawood Indexes Werver Otherwise return you - Indexes Werver Otherwise return you - Indexes Werver Otherwise return you - 151 - Not Possible to Be Responsible and It's 151 - Not Possible to Be Responsible and It's 151 - Not Possible to Be Responsible and It's Not Possible and 1628 Divine Example Doing What Are the Given to See The Question is Way and Middle and Subscribe the Channel Numbers Off hua hai to water three numbers unlisted phone numbers this lineage distracted number one third number one that also adversely brightness question donation number configuration enter white chief artificial number will start from zero now school number one plus one april - subscribe third number from j&k that suji included as part of the third number 90 number two that just remember just point play list randstand one another example do then late important without something latest in this 0 size us loud liquid difficult after 10 comes with a e want such contest will meet after 10 Second Officer James To Remember E Part Third Number One Officer Dr The Software Mig But After Vansh But Will Return Gift To Cash Requested Number Two To Visit Slated To Understand 100 Whose Point Is In Egg Strike Your Numbers Office Number One Number Valve And Third Number This year 2009 which hair input are this side belongs to the departed for old of the question is v0 total length of this website before but after acid attack electronic number 102 the fifth pure number on we size gain 101 that second torch start is 131 the five And third part valve against 05 hai so day why reddy code word from depression and left right to right second number one step in the total subscribe not divided into three parts of - - - 1 parts of - - - 1 parts of - - - 1 hai laptop board the second hand when everyone meeting and Depression Leading Videos Don't Remedy Number So Let's You Mother Biraul Delhi-01 Tribute To The Number One Vid Oo Hai Laptop Keyboard Second K Cross Breeding 1122 If Rambir And Also Android Phone Number 100 Number 66 A Symbolic Hotspot Ko Also Adding Another Hand This Indicate The Number of Students from 4th Grade One This Book Reads Way Leads to Starting with the Number This is the Meaning of the Number Subscribe Share and Subscribe Let's Move Ahead with Alarm Play List Try News Head to Come Up with Solution And forests and bodies to counter total number of verses in the same for example this show has a number one in directions reader number 123 456 subscribe k arnav list festival decoration of post one inch on dashami that now i want all indexes of but looking For the first index gift dance for the second part that today independence after flood water so let's go inside or sentences that Bigg Boss vanita karenge it's an Third One By Four Sid Army Force One Part Mein Likh Mode Tattoo Hai What Will Guide You Will Get Rid Of Crosby Sports On YouTube 500 To 1000 Elements Vidmate subscribe and subscribe the Video then subscribe to The Amazing spider-man 2 That Undergone Bill Check The Volume Is Equal And Not Eligible 2018 A Director In Three Parts Updated Today's Temperature In Second Part Get Updated With A Steady Returns For Dates And Actor Anonymous That Yugalpeeth Dedicated Balance Pendant Break And You Can Eventually Over Had So What To Do That A Unit Breakup Research A Few Can Fully Absorbed In Busy Died In Taxes Were Me To Make Electronic Items In Partially Entered Into Being Made After 80 Remembered Uble Maybe And Subscribe Is You Carefully Abused An You Will Understand What Is The Number But Were Trying To Match Up To It Is Nothing But Number 10 Starting From Most Of The Length Of The Day That Art Words What Should Be Extra Where May Be Coming Leading Videos In Its Part Good Luck Not Concerned About That Which Is Leading Videos Do Not Contribute To The Number Dial Number One Right From Internal Parts Of The Match Subscribe Button More So I Hop Logic So To You Know It Is Not Don't Worry El Explain Everything In The World In Section If Suggestion Section Time For This Order Of Infiltration Bid Solution That Bigg Boss Singhpur Answer in Define RS and Fixed Deposit K 851 Acid Number of Account Number One Shutter in the Middle of Do Not Expressly Check the Number Not Required Hu is the Number of Vansh Stones 120 B Coming at 8051 Index and at Least One Shroff Hero Command2ne Search Man Adhir What is the Number of Waves Not Divisible by Subscribe Now in Knowledge Move Ahead and List Triangle Credit The Number of Vs Page Number of Waves Subscribe in 504 Posts 121 This Number is Equal to One Adhikari Subscribe To Ki Aunty This Number is Equal to One To The Number Of V In Which Part Plus One That Debit The Index Of Force One Part V Roman Number Of 152 To * Number One Roman Number Of 152 To * Number One Roman Number Of 152 To * Number One Subscribe David Number Of Posts In Points Is 152 Is My Number Of Vansh Is Equal To One But With Index Of Force 1.05 One Million With Index Of Force 1.05 One Million With Index Of Force 1.05 One Million Residents of Wave in Egypt That Is Human Be Successful in Identifying the Position of Force One is Part Glue Group Pointers Across the Parts of the Time Inductive 1.2 Dowry The Length of But Subscribe Points 208 E Want in Case with Mismatch in This Imbalance Between what is the president - 9 - 1898 Between what is the president - 9 - 1898 Between what is the president - 9 - 1898 that in the end simply return donation service nothing but index of forest 1.0 - way nothing but index of forest 1.0 - way nothing but index of forest 1.0 - way index look post one part one that hindi presentation is roorkee now don't in difficult straight difficult part one plus one servi 120 days Have I hope this creative and let's talk time complexity of this prompted of endless complexity response pain and I hope you liked David please don't forget to like share and subscribe to the channel thank you all subscribe updated on
|
Three Equal Parts
|
sum-of-subsequence-widths
|
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and
* `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part.
* All three parts have equal binary values.
If it is not possible, return `[-1, -1]`.
Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value.
**Example 1:**
**Input:** arr = \[1,0,1,0,1\]
**Output:** \[0,3\]
**Example 2:**
**Input:** arr = \[1,1,0,1,1\]
**Output:** \[-1,-1\]
**Example 3:**
**Input:** arr = \[1,1,0,0,1\]
**Output:** \[0,2\]
**Constraints:**
* `3 <= arr.length <= 3 * 104`
* `arr[i]` is `0` or `1`
| null |
Array,Math,Sorting
|
Hard
| null |
783 |
okay so today's daily challenge is minimum distance between VST numbers so basically we want to find uh in bsta we want to find the minimum distance between the values of any two different nodes in the tree so basically if we want to find let's say the tree looks something like this because this is binary search tree it has to follow these rules here let's say in this case basically the minimum difference is 89 and 90. so it's going to be one so if we want to find this basically the basic idea here is that if we do DFS on India or in order Travers are here so basically it's going to visit 21st because it's in order DFS it's going to visit the node itself 10 seconds and then with the last note third so doing in order TFS will basically give us ordered uh list of nodes right so let's see if we can build up this kind of array where you store order released then you can only compare the number right next to you so you can if you are starting from 20 you can compare with the 40 or if you are starting in index one you can keep up updating the minimum right so initially 40 minus 20 is 20 but then there's 89 minus 40 49 so this is not minimum but there is 90 minus 89 which is one so it's going to update this minimum to one so this is going to be the answer okay um so this the time complexity will be of let's say of n because we are pretty much visiting every single node so time will be over n but also there is a space complexity of n as well because we are utilizing this array um to store n number of nodes maybe we can do better with the space complexity uh we cannot really be better than the oven if we want to do better than oven it's gonna be some error around like either of log n or of one but of one doesn't really make sense because you have to compare at least each node so log n same reasoning you cannot really get the difference just by visiting a certain number of nodes so you have to visit every single nose so I think time complexity of n is the best effort best we can get maybe we don't need this array if we basically store the previous value because here when we iterate from here to here we are just basically keeping track of what number the previous one was which is 20. and then comparing that with the current number which is 40. so if we can keep track of like uh previous node somehow in this in order traverser then we should be able to calculate so the logic will be in our DFS logic um so visit so DFS on the left node okay and then we need to calculate the difference of the current node that's what's in order traverser is doing so basically we are using this current and then um basically comparing whatever we got from the left so basically this left should return 20. and then as a previous note so at some point we have to set previous node to be current node so that when we return back to the parent they can actually use previous node as the left node or left node as a previous note and then here the previous node will can be empty if you're visiting for the first time on the left chat but most child so we need to check for a previous node is there then um calculate the difference so a previous node will always be less than the current node so um mean will be the minimum of uh previous node and then the current node okay and then lastly we need to do the same for the right so what's going to happen to the right node is once it once this finishes the 40 will be set as previous node and then we're going to visit the right node so it's gonna try to subtract and then it's going to if it has left node it's going to visit left node if it doesn't then it's going to use this 40 to calculate the difference between 89 and 40. and then visit right doesn't have right so it's going to return so previous parent will just return and then 90 will now so this returns for the as a previous node so 90 will now be the current node so 90 minus 40 will be calculated okay um yeah so once this is all done um we can simply return the mean Min value okay so let's try coding this up okay so let's bring up keyboard okay so in here actually I'm gonna bring my good note over here so my DFS logic will be deaf um DFS now I need to be receiving the node itself and then we first need to check if a node is not no don't know if it's no we just return because there is nothing to do okay otherwise what we're going to do is this difficult logic so we're going to call DFS on the left node and then checking if there is a previous node in that case oh we didn't Define the mean value here so in div will be um okay I mean diff will be currently I'm gonna set it to Max for now because it will eventually be um set to some number okay so mean div and then um when previous node is there we're going to calculate the wind diff so it's going to be I mean of wind if and then um what else the actual uh calculation so node .org minus Brave node .org .org .org okay so this is going to be the main diff once we're done we need to set previous node to be the node itself and then do the same on the right tree so once this is all done we can just simply return Min div okay let's see so we're checking for null node um is there going to be any empty tree no there will always be at least two no's so this is good okay so mind if I might actually declare non-local here non-local here non-local here because it's not a reference so there's node the previous node is initially null so I'm actually going to declare it as known as well um I think because previous known is known previous node is none I might need to deter them local as well okay so let's try the right how do I keyboard okay running so nth is not value for the expected return time integer so they are expecting integer oh it's because we are not actually running so I didn't call DFS on the root node that's why okay let's see okay so running case one and two works if we submit yep
|
Minimum Distance Between BST Nodes
|
search-in-a-binary-search-tree
|
Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_.
**Example 1:**
**Input:** root = \[4,2,6,1,3\]
**Output:** 1
**Example 2:**
**Input:** root = \[1,0,48,null,null,12,49\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `0 <= Node.val <= 105`
**Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)
| null |
Tree,Binary Search Tree,Binary Tree
|
Easy
|
270,784
|
1,358 |
welcome back food and we're discussing today this problem number of suffering contain all three characters let me read the problem so the problems is we are given a stream consisting only those characters a big n Z and we need to return the number of sub string containing at least one occurrence of all these characters BBM's yoo-hoo we all these characters BBM's yoo-hoo we all these characters BBM's yoo-hoo we need to count the number of such name not to contain at least one time that means there will be at least one a ring of all these characters who let's do that name so then put here is ABC I'm gonna put is 10 now let's move over and look at explanation baby see this is the string here and then maybe see a which is this a b c AP each of this ABC this then bc a which it is not busy AP as you can see that for this beijing a we have found that operands of B is 1 C 1 is 1 and we include the next B and it will only increment the count of B and on ABC will be more than 0 we can see they rattling at least one time then we will include this you also know they are going for c AP and then we also this C ABC if you observe here we can use to all loop for this problem and like we can declare three variables the for loop picking you later sorry our G will start from I can go and this will be my count variable and now we'll check if this position is object if it is even given T and so it is B then we increment amount of B and meaning given the counter C now we need to check if the count of these three variables are greater than zero means they have offered for a single time 10 million remain Collings this is a valid for frame which contain at least one again of all these varied characters now what we need to do is return these PMT down and this variable will be having on the count of substring having occurrence of all these three characters at these poles but if we look at the constrain here this 5 into 10 to the power 4 and we need to perform it in once again we will not be able to do because the time complexity of this would is chemic square beauty take a closer look it is n square flip if we say the lengths of spaces in the maximum length 5 into 10 to the power 4 then it would result in more than 10 to the power 8 operations so it will know you will be giving hitting time limit X key check here so making a little bit of time oh yeah it's going time limit exceed if you are going for and school so let's move back and have a community to this solution so taking the first example you'll see here the first option they have given in a bee sting are talking something do we need to check on this event because we won a first one Taylor we have the count we have all the three appearances at least one now what we're doing after this how many suffering will found in the head let's give them the thing if you look first if we go for ABC for that cause you know when to when after we have encountered a will be having all this will be if we can do it will be counted as a substring valid something we wanted if we are if we found all this an enum any element present after this whether it is maybe P or C it will be added to our answer means once we have encounter all these three the characters coming after this position means after this position will be hiding it in the handsome so what this means is let's assume you think about my family so what we're doing in the last occurring means for the loss of things between these three means if we like rendered 0 then we are we looking the last occurrence well we can see the first I don't know we'll be right the same first of ABC so E is at 0 being that one either - 2 will be finding the maximum life - 2 will be finding the maximum life - 2 will be finding the maximum life event like composition the maximum position here would be 2 and we'll be adding this by subtracting with the length of the string what is the length of the string we were in that's a new many the length of the string here and we'll be sick and you can see and it sticks the long distance here for where we are pending sales to so usually it would 0 now it could become you know please wait - what could become you know please wait - what could become you know please wait - what is the pollution all still here but it is two hours I'm going to come through and if you see explanation after encounter in the first a busy and the string from with this ABC there will be fortune called the taste possibility busy everything that we busy lately maybe thinking we'll see don't have anything like this now what we'll be doing now we on air pollution one normal we move to position okay for this there will encountering the funds being encountered act when we are at position one and standing at one the first thing we are being counted today exact to the first a mean countered after position one in three for the maximum between these three which is three so what we'll be doing these now that is plus maximum between maximum position six - the maximum position six - the maximum position six - the maximum punishment 3 now it would be v - V 3 punishment 3 now it would be v - V 3 punishment 3 now it would be v - V 3 hold this please and if you feel good take a look this might be the first ring be stick a then it would be C a B then it would be basically a B and you can also know take a living the explanation basically busy helping behavior field following with this position one if you're angry making font resourceful so this is right now move forward maybe on our position to standing head position to those ones encountered at three the first be encountered for the first is encountered add to having a traditional tool now over at our answer would be 7 plus sorry n - Mort would be 7 plus sorry n - Mort would be 7 plus sorry n - Mort International between these available it is 4 so report and this is - you know is 4 so report and this is - you know is 4 so report and this is - you know we're starting our - just look how - we're starting our - just look how - we're starting our - just look how - when you can both see a being is it up a string and then sing everything don't even only for now let's move at position 3 so standing at position 3 the first occurrence of people not really thinking that for energy it is not 5 so let's go ahead and add this over answer no 6 - oh ahead and add this over answer no 6 - oh ahead and add this over answer no 6 - oh let me do some Christian dynamic 6 - let me do some Christian dynamic 6 - let me do some Christian dynamic 6 - like an opposition between everything you three four five thousand is now suspect now given our three now we'll move to 4 I would say we can find a handing out so great if we can look at right if we can find anything we can not so easy row means there would be nothing there will no stream now which will contain point in between so this is the base condition where we'll be terminating I hope you have understand this logic it's not you can go for some testing now as we will be really need to do some pre-processing be really need to do some pre-processing be really need to do some pre-processing for finding the position of ABC so I'll be using to come in three different you here for ABC there are only three characters in the string while being with this now I'll be looping and let's go I've been looking once if this character is a then what I will do if it is this a then I'll push its position as if it is a bit I'll push this position on the penalty pitilessly I'll push it on say now we have all these positions like we can say for a we'll be having a newcomer to be in front of that wonderful things when I 25 so this will be our ABC queue you know as I have already discussed the condition for terminating for is when any gaping shield is zero so what we'll do is you know what t-thanks will be do is you know what t-thanks will be do is you know what t-thanks will be checking if any of the queue is not empty there is a yeah exists on at least one against call will be taking account variable which will count the number of substring okay now we will also need to take I which will point to the position we are real understanding now this character will point to the I position means the position breathe standing and we are signing positions in so we need to check if this is a angry - so we need to check if this is a angry - so we need to check if this is a angry - little they know what effect also and then we need to find the maximum is that you know that we need to find the first occurrence of B and C so what we do is we look at B dot ring and still not front and we will remove we will pop this index mean as we have already a present a 0 B manner that one see you present a - so moving forward and present a - so moving forward and present a - so moving forward and copping this Bob popularly now we need to go for B if this character was B then we need to find that you can see here this is when we will be add one will be checking for seconds ago seeing ok because that one will be having this maximum attractions maximum cohesion and thing ok will again focus on this what you write here now bring coffee because in moving forward and for tasting we will compare the position added which will find a little bit and we'll copy now will bring using this formula so that's our Z plus and minus three and don't forget to increment I now we'll be returning and so let me free drums at face value or not is it does it in the schedule oh yes just so you can see that on time what it means and also so if you look at this the complex 18 this room is going for 10 times it is all my turn for 8 times in both case we can see even on string with me and we'll be right I don't think so it would be but we assumed that it would be going for n minus negative and minus 3 I think for the case here 2n minus 3 so n plus n minus 3 it would be 2 n minus 2 it will be a little we'll call and so this code will be then learning people and we can say so thank you don't forget to hit the like and subscribe button if you like this video and
|
Number of Substrings Containing All Three Characters
|
find-positive-integer-solution-for-a-given-equation
|
Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._
**Example 2:**
**Input:** s = "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._
**Example 3:**
**Input:** s = "abc "
**Output:** 1
**Constraints:**
* `3 <= s.length <= 5 x 10^4`
* `s` only consists of _a_, _b_ or _c_ characters.
|
Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z.
|
Math,Two Pointers,Binary Search,Interactive
|
Medium
| null |
1 |
hello and welcome today we are doing a question from leak code called sum of two integers it is a medium we are going to jump right into it given two integers A and B return the sum of the two integers without using the operators plus and minus example one we have a being one and B being two we output three and example two we have two and three and so we output five so we want to add a and b without using either the Plus or the minus now this question is pretty open-ended so we this question is pretty open-ended so we this question is pretty open-ended so we have a lot of freedom with how we want to approach this we could theoretically add a and b to a list and simply return that sum so I could just run this and of course I would get the expected output um another thing I could do is just do math. exponent of a multiply that with math. exponent of B so if I'm multiplying with the same bases that means the exponents are being added and then what I have to do is take math.log of that entire thing and wrap math.log of that entire thing and wrap math.log of that entire thing and wrap it as an INT and of course once I take care of the zero conditions for A and B I could also get a correct answer by doing this and neither approach really uses the plus and minus so I think it is perfectly acceptable however this question does want us to use bits and bitwise oper ators so switching over to Binary how would we add say we had example with a being 2 B being 3 so say I wanted to add two and three how would that look like in binary two is represented with a 1 Zer and three is represented with a 1 one okay so if I have this following bit representation how would I do addition it's just like regular addition right we look at that first digit zero and one that added together is just one then we have 1 one that is 1 Z so we write down the zero and we carry over the one then one with nothing is just one like this and this makes sense because this is equivalent to 5 and 2 + because this is equivalent to 5 and 2 + because this is equivalent to 5 and 2 + 3 is 5 now the only problem here is we can't use addition so what can we use instead well there is a pattern on how this is being added if I had zero and one I would output one if I had one and zero I would output one if I had zero and zero I would output zero and if I had one and one I would output zero with a one as carry so what does this truth table remind us of this is an X or an exclusive or where we output a one if the digits are different if they're the same if we have 0 or 1 one we would output a zero so that takes care of the output we would have without the carry now what about the carry the only time we would actually have a carry is if we have the one condition otherwise everything else is just zero if we have a one then our carry would be one otherwise we have no carry and this is the logical and 0 and 1 is 0 1 and 0 is0 0 and 0 is z and one is the only time we would actually output one so what we're going to do is break this up into two parts I'm going to have the sum without carry being a X or B and my carry is just going to be a and b now what do I do with this carry that I get right once I get the carry I want to shift it over one to the left and then continue my summation so what I'm going to do to this carry is actually shift it left by one and then I want to repeat this addition so I'm going to do the sum without carry and carry again and combine that to make this clearer let's actually look at base 10 again okay say I had the following integers that I wanted to add up how would I do it well 9 + 4 is 13 so I would write three over 9 + 4 is 13 so I would write three over 9 + 4 is 13 so I would write three over here and I would carry the one so right now this is my sum without carry and this up here is my carry now 8 + 6 and this up here is my carry now 8 + 6 and this up here is my carry now 8 + 6 and we're going to ignore the carry right now is 14 so I'm going to write a four over here and carry the one and again we ignore the carry so 7 + 8 is 15 and we ignore the carry so 7 + 8 is 15 and we ignore the carry so 7 + 8 is 15 and we carry the one so now we have a sum without carry and a carry but remember we wanted to add the carries to the sum we would have had otherwise so what we're going to do is add the carry and sum without carry together so what I'm going to do is I'm going to add 543 with 1 except this needs to be shifted over by one right so it's going to be something like this and this is just going to be a zero over here we have 1 0 plus 543 and we're going to repeat the same thing again so I want to add this up and again I'm going to have this over here be sum without carry and up here is going to be my carry now 3 + up here is going to be my carry now 3 + up here is going to be my carry now 3 + 0 is 3 4 + 1 is 5 + 1 is 6 and 1 + 0 is 3 4 + 1 is 5 + 1 is 6 and 1 + 0 is 3 4 + 1 is 5 + 1 is 6 and 1 + 0 is just 1 so now I have a sum without carry being 1653 and I have nothing in my carry this means I'm actually done with my addition and my final output is 1653 for this original addition right here so we're going to do the same thing in binary and I'm actually going to assign sum without carry to be a and my carry I'm going to set to be B this means that while be greater than zero while we still have carries that need processing we're going to set a to be the sum without carries so that's a X or B and we're going to set B to be the carry so that is a anded with b and then left shifted by one like this and finally we have to return a so I'm going to go ahead and remove everything else and we can go ahead and run this code and it is accepted now before submitting there is one small caveat the problem is overflow with python specifically we're not actually bound with 32 bits so say I had the following test case I had -2 and three if I were test case I had -2 and three if I were test case I had -2 and three if I were to go ahead and run this we would actually time out and we can see that it has timed out time limit exceeded why is that well let's take a look at -2 and three and let's take a look at -2 and three and let's take a look at -2 and three and see exactly what is happening so three how would I write that in bit form that is going to be 0 1 and say I have eight bits so that's going to be 0 so this over here is three now how do I write -2 negative numbers are written I write -2 negative numbers are written I write -2 negative numbers are written in two's complement what that means is we take the original number we invert the bits and then we add one so two originally would look something like this in 8 bit form like this now if I were to go ahead and invert every single digit I would flip the zeros to be ones and the one to be a zero so now I have this and finally I just have to go ahead and add one so 1 + 1 is zero and I carry over one so 1 + 1 is zero and I carry over one so 1 + 1 is zero and I carry over the one so 1 + 0 is 1 and the rest are the one so 1 + 0 is 1 and the rest are the one so 1 + 0 is 1 and the rest are all just going to be ones so this is -2 all just going to be ones so this is -2 all just going to be ones so this is -2 and a quick check over here right how to tell what our numbers are the most significant bit the leftmost bit represents our sign so if it's zero that means it's positive and if it's one that means we have a negative integer and feel free to read more up on this online but this is what we are going to do we're going to add 3 and -2 over here we're going to add 3 and -2 over here we're going to add 3 and -2 over here but say to make this even simpler instead of using eight bits say I'm only using three so I'm just going to use this and this what would that look like I would basically be doing 0 1 which is three + 1 0 which is -2 now if I is three + 1 0 which is -2 now if I is three + 1 0 which is -2 now if I were to go ahead and add this up I would have one over here then 1 + 1 is 1 Z have one over here then 1 + 1 is 1 Z have one over here then 1 + 1 is 1 Z with one being the carry so I have one over here as carry and then one and one again so that's zero with one being the carry now remember I have three bits so I'm sort of truncating my answer to only be 0 1 and that makes sense right 3 + be 0 1 and that makes sense right 3 + be 0 1 and that makes sense right 3 + -2 is just 1 and we have one over here -2 is just 1 and we have one over here -2 is just 1 and we have one over here now the problem is if this was not truncated to be three bits we would actually continue adding this up right we would have all these ones for this -2 we would have all these ones for this -2 we would have all these ones for this -2 and we would keep carrying over the one on and that's sort of what python does it's not bound by three or eight or even 32 bits which is why this example timed out so how do we fix this we have to go ahead and truncate it our sves which means we're going to bound it by a 32bit integer I'm going to assign a 32bit value of all ones to a variable called mask now instead of writing out 132 times I'm just going to represent this in heximal form so that is going to be the following like this so instead of checking while B greater than zero because we could theoretically keep carrying on right what I'm going to do is check mask and B so the first 32 bits of B if that is greater than zero then we continue if not then I know we're just overflowing and I'm going to stop my while condition and the same applies for the return right if B is greater than zero then I want to return mask anded with a what this does is it takes the first 32 bits of a because any anything anded with something else of all ones is just going to keep its own value for example if I had 110 and I was anding that with all ones I would get 1 one zero right because only if both of these are ones would I get a one if any is a01 I would get zero so what this means is I'm just keeping that first 32bit value of a and same for B that's all I'm checking and if this is not greater than zero else we can just return a so now if we go ahead and run this it should work and it's accepted so now we can go ahead and submit this and it is accepted as well so before leaving let's run through an example okay for our example let's use 1 and -1 and see how it goes line by line and -1 and see how it goes line by line and -1 and see how it goes line by line so a is going to be one and for Simplicity purposes I'm just going to only use three bits that way we don't have to keep writing things out so one in three bits is going to be 00 one and B is going to be again 0 1 we go ahead and invert this so it's 1 0 and then we add one and we get 1 so that means this is1 and this is positive one up here now I want to go ahead and add this up so I go into this function and mask again for Simplicity purposes let's just say it is a 3 bit integer made up of all ones so while mask ended with B greater than zero and that is true this is greater than zero it's all ones right now we are going to find our new A and B so a is going to be our sum without the carry so that's just going to be a b x or so that means a is now going to be 1 0 and our new B value is going to be a ended with B so that is 0 1 and then we shift to the left so this is now something like this and let's get rid of this over here so this is our new B value now we go back into this y Loop and B is greater than zero so we have our new A and B values so I'm going to write out my new a value which is 11 1 0 and my new B value which is 0 1 0 now I want to go ahead and find the exor and the carry again so a exor with B is going to be 1 0 and B is going to be a and b so that is going to be 0 1 0 left shifted by one so this is going to look something like this now we go back into this y Loop B is still greater than zero so we do the same thing again our new a is 1 0 and our new B is 1 0 so what is a xord with B that's 0 and what is B equivalent to now so that's a and b which means it is 1 0 and then we left shift by one so that is something like this however now when we go back into our y loop we're going to mask it and we're assuming this is a 3 bit integer that means we only care about these digits here this is no longer greater than zero so we are going to actually return and we're going to return mask and a because B is actually greater than zero so we're going to mask a and our output is going to be zero now I've added some print statements to also see how this would play out with all 32 bits but this is how we're going to be doing this and I'm actually going to adjust this print statement a little bit just so we can also see what mask and a are so mask and a and I'm going to take the binary of that and just for fun we're also going to see what A and B are without the binary also going to add in bin of b of mask and B and also mask and B okay so let's go ahead and run this code and we can see all of this playing out right so when we go ahead and start carrying this all over we get 2 -2 44 carrying this all over we get 2 -2 44 carrying this all over we get 2 -2 44 we're basically adding all of this up until we hit that 32bit Mark once we finally do we actually have and we can see in this print St over here right the binary of B is actually greater than zero it's non zero so we have to go ahead and truncate it so this is what binary of B represents it's some random number and when we truncate it we add the mask it's finally zero but it was greater than zero so we have to return mask of a and what's mask of a is zero as well so that's how to do sum of two integers I know sometimes it can get a little confusing using bitwise operations and just binary in general so if you have any questions at all let me know down below otherwise I will see you next time
|
Two Sum
|
two-sum
|
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.
You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.
You can return the answer in any order.
**Example 1:**
**Input:** nums = \[2,7,11,15\], target = 9
**Output:** \[0,1\]
**Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\].
**Example 2:**
**Input:** nums = \[3,2,4\], target = 6
**Output:** \[1,2\]
**Example 3:**
**Input:** nums = \[3,3\], target = 6
**Output:** \[0,1\]
**Constraints:**
* `2 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109`
* **Only one valid answer exists.**
**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
|
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Hash Table
|
Easy
|
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
|
79 |
hey everyone welcome back and let's write some more neat code today so today let's look at word search this is a pretty good problem and it's definitely very popular so we're given a grid m by n with a bunch of characters or you could say it's a board and we're also given a target word and we want to look for this word inside of our board and if we can find the word we return true if we can't find the word then we return false and so within our grid the word can be constructed any way but it has to be either horizontally or vertically neighboring cells so basically what we're looking for let's say this is our board we're looking for a path inside of this board where we can move horizontally right we're moving to the right then we go down and then we go to the left so this is our path and we are looking for a word so we're looking for a path that can make this word down here you can see in the example they give us a target word a b c e d and that's the word we're looking for a path and we can find a path with exactly those characters therefore we can return true now the question you're wondering is how can we figure this out is there a really efficient algorithm to solve this problem the answer is no there's definitely not a super efficient one we just are going to go through the brute force solution and that brute force solution is going to be back tracking so basically this problem is actually pretty intuitive right how would you solve this problem in real life if you didn't have any code well you'd go brute force right looking let's start at every single cell so we'd go through every single cell right let's say this is an e right it does our word start with an e no it starts with an a now we have a c does our word start with a c nope does our word start with a b nope does our word start with an a yes it does so now let's look at all the neighbors of a and look for our next destination character our next target character is b right so let's look down we don't have a b over here this is an s let's look up there's nothing up left there's nothing left okay to the right we have a b gray now the next character we're looking for is a c are there any neighboring c's not up right what about to the left we can't reuse a character so we can't reuse this a but we wouldn't want to use it anyway but that's just another detail right we can't reuse any characters down here there's an f that's not what we're looking for but to the right there's a c right obviously we can see that and the next character we're looking for is a second c you know we could run through this but it's mainly just brute force right we're going through every single position looking at every single neighbor to see if it's even possible for us to make this target word in this case the answer is obviously yes we have an e and we have a d we can finish it up so in the code we're going to be doing backtracking so let me jump into that or rather we're going to be doing recursive backtracking so we're going to do this recursively or in other words we're going to do this with depth for search so let's dive right into it so one thing i like to do with these problems is just get the dimension so i'm going to get the number of rows and the number of columns so get the length of the board we get the number of rows and get the length of the first row and we get the number of columns also remember how i said we can't revisit the same character twice within our path therefore we're going to need a variable or a data structure for our path we're going to use a set to add all the current values from our board or positions in our board that are currently within our path to make sure that we don't revisit the same position twice within our path but other than that if you've seen any of my backtracking videos you know i like to follow a formula so i'm just going to be going through that right now so i like to create a nested debt for search function within the root or the regular function because then we don't have to pass in some of the variables like the board and the word because this is a nested function but we are gonna have to pass in the position of the board that we're at so two variables row column for that and we're gonna have to pass in a third variable i which is going to tell us the current character within our target word that we're looking for so if we ever reach the end of the word or if i ever equals the last position so if i if we ever finish the entire word therefore we know we found the word therefore we know we can return true right that's the good case the other case is what if we go out of bounds right out of bounds of the entire board what if row is less than zero or column is less than zero right or what if row is greater than or equal to the number of rows or if column is greater than or equal to the number of columns that's also out of bounds so or let's consider one more case what if the board what if the character that we're at in our word so word at position i is not equal to the character that we're at in our board so board at position row column so if this is the case if we're if basically we found the wrong character then we also want to return false and there's one last condition we have to check what if the character or what if the position we're at row column this tuple what if this row column position that we're at is inside of our path set what does that mean that means we're visiting the same position twice within our path we know all of these things that i've just listed all these conditions are basically invalid if any of these are true then we have to return false because you know if we're out of bounds we return false if we see the same character twice we return false if we see a character that we are not looking for we also return false okay but once we're done with that then we know okay we found a chara we found the character we're looking for right so what can we do we can take our path and add the current position to it so the current row column to our path because we found a character that we need so now we're going to be continuing our recursive depth first search and so we're going to be looking for the result of this depth first search so we're going to run depth for search right we're going to run it in all four adjacent positions so what i'm going to do is say row plus 1 leave the column the same and add 1 to i we're adding one to i because we found the character we are looking for now we're going to look for the next character right so now i'm just going to basically copy and paste this a few times so i copy and pasted it four times because we're going to look at all four of the adjacent positions so let me just fix this up so you probably see what i'm doing but basically i'm saying row plus one leave column the same row minus one leave column the same column plus one leave row the same and column minus one leave row the same so we're looking at all four horiz of all four adjacent positions we're running depth first search on all of them and if any of them return true then our result is gonna return true remember we only need to find our target word one single time so if we ever find that word then we know we can return true so i'm gonna go ahead and return that result but right before i return that result i'm going to do a little bit of cleaning up so i'm going to take our path variable and remove from it the position we just added to the path because we're no longer visiting that position right we're returning from this function called therefore we don't have to continue to visit that position inside of our path so this depth first search of recursive function is always the main part of the backtracking problems once we're done with this function the only thing left for us to do is actually brute force go through every single position in our grid and run this depth for search function on it so that's exactly what i'm going to do for every single position every single starting position in our board i'm gonna run that first search passing in the row column passing in zero for the position of i because we're always starting at the beginning of the word and if we ever return true if this differ search function ever returns true i can immediately return true from our function exists right i can just return true immediately i don't have to wait and if we never return true if this goes through every position in the board and we never return true then i'm gonna have to return false out here because that means we did not find the word that we were looking for so this is the entire function actually you can tell that it's definitely not very efficient right we're running through the entire board right so what's the time complexity of that running through the entire board is going to be n times m because those are the dimensions of our board and that's being multiplied by the debt first search function right because we're calling that debt for search function every single time for every position in the board so the question becomes what's the time complexity of the debt for search function well the call stack of that debt for search function is always going to be the length of the word right because the word can only be so long we can only go through so many characters for the word so that's going to be the call stack of it remember where though we have four different branches we're calling the depth first search for different times so it's really going to be 4 to the power of the length of the word that we are given so it's going to be something like 4 to the power of n where n is the length of the word so you can see this problem is not very efficient so let's just clean this up so this is going to be 4 to the power of n roughly right so it's not a very efficient solution this is the rough time complexity of the problem so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Word Search
|
word-search
|
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.
The word can 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.
**Example 1:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED "
**Output:** true
**Example 2:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE "
**Output:** true
**Example 3:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB "
**Output:** false
**Constraints:**
* `m == board.length`
* `n = board[i].length`
* `1 <= m, n <= 6`
* `1 <= word.length <= 15`
* `board` and `word` consists of only lowercase and uppercase English letters.
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
| null |
Array,Backtracking,Matrix
|
Medium
|
212
|
481 |
are you stuck on a coding challenge don't worry we've got your back let's dive in and solve the magical string problem together the problem is to construct a magical string of length n the magical string is a string s of digits consisting of a one followed by one or more occurrences of two and then one or more occurrences of one the solution is to initialize a magic string with the value 122 then use a while loop to repeatedly add characters to the string based on the current index in each iteration of the while loop it starts by determining the number of times to repeat the last character it does this by taking the difference of the ASCII value of the current index and ASCII value of 0 which is 48 using the code into repeat equals magic string index minus zero then it calculates the next character to add to the string by using zor operation with 3 using the code care next care equals magic string back zor3 finally it adds the next character to the string by creating a string of repeat times of next character using the code magic string plus a Cold Stone string repeat next care and increment the index by 1. at the end it counts the number of ones in the final magic string by using the count method of string let's consider an example where n equals six initialize the magic string with the value 122. string magic string equals 122. initialize a variable to keep track of the current index int index equals 2. start the while loop while magic string dot size smaller than length in the first iteration the current index is 2 and the value at the current index is 2 which has an ASCII value of 50. so the difference between the ASCII value of 2 and ASCII value of 0 is 2 which is the number of times we need to repeat the last character in this case 2. repeat equals magic string index minus 0. the last character in the magic string is 2 so we use saw operation with 3 to calculate the next character which is one care next care equals magic string back zor3 we add the next character one to the magic string by creating a string of repeat times two of next character one magic string plus a Cold Stone string repeat next care the magic string now becomes one two one the index is increment by one and the while loop continues in the second iteration the current index is three and the value at the current index is 1 which has an ASCII value of 49. so the difference between the ASCII value of 1 and ASCII value of 0 is 1 which is the number of times we need to repeat the last character in this case one intrepeat equals magic string index minus zero the last character in the magic string is one so we use xor operation with 3 to calculate the next character which is 2. care next care equals magic string dot back zor3 we add the next character 2 to the magic string by creating a string of repeat times one of next character two magic string plus equals string repeat next care the magic string now becomes one two the index is increment by one and the while loop continues the while loop ends when the magic string length is equal to the input value n at the end we count the number of ones in the final magic string by using the count method of string in this example the final magic string is one two and it has four occurrences of the character one so the function would return four it's important to note that this problem is a follow-up of another problem and is a follow-up of another problem and is a follow-up of another problem and the initial value of the magic string is based on the first problem solution the solution has a Time complexity of Big O N because the while loop runs n times and each iteration takes bigger one time the space complexity of the solution is Big O N because it creates a string of size n thanks for following along I appreciate your attention and I hope you found this explanation helpful if you found this video helpful make sure to hit the like button leave a comment and subscribe for more content like this
|
Magical String
|
magical-string
|
A magical string `s` consists of only `'1'` and `'2'` and obeys the following rules:
* The string s is magical because concatenating the number of contiguous occurrences of characters `'1'` and `'2'` generates the string `s` itself.
The first few elements of `s` is `s = "1221121221221121122...... "`. If we group the consecutive `1`'s and `2`'s in `s`, it will be `"1 22 11 2 1 22 1 22 11 2 11 22 ...... "` and the occurrences of `1`'s or `2`'s in each group are `"1 2 2 1 1 2 1 2 2 1 2 2 ...... "`. You can see that the occurrence sequence is `s` itself.
Given an integer `n`, return the number of `1`'s in the first `n` number in the magical string `s`.
**Example 1:**
**Input:** n = 6
**Output:** 3
**Explanation:** The first 6 elements of magical string s is "122112 " and it contains three 1's, so return 3.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 105`
| null |
Two Pointers,String
|
Medium
| null |
1,470 |
you guys are let's go over seven 1470 chef-owner a so the question says chef-owner a so the question says chef-owner a so the question says given the array of numbers consisting of two and elements in the form of this over here and if you noticed as this array is actually divided into two x and y return the array so we want our result in array in the form all over here and if you look at x1 y1 x2 y2 and so forth ok let's look at our first example so the answer has an da Missouri and it has an end of the 3 right so we had done to 5 1 3 4 7 and n is equal to 3 and this publish it looks harder than this problem is actually easier than what it looks like that's what I meant so you have n of 3 and we have 6 elements here right so we want to divide this array into two and this is gonna be X and this is gonna be Y and the first one here is going to be X 1 X 2 X 3 this one is y1 y2 and y3 and we want our output to be this right so how do we get that so result is equal to NR a so first number is gonna be this 1 X 1 2 3 which is our y1 + 5 or x2 y2 is our 4 X 3 is our y1 + 5 or x2 y2 is our 4 X 3 is our y1 + 5 or x2 y2 is our 4 X 3 is our one y3 is our 7 so 2 3 5 4 1 7 so it's correct this is how you get the result so now let's quote our solution so first thing we're gonna do is the clear function in shuffle which takes in two parameters nums and n and numbers is an array with numbers and n is a number and this is where we're going to cut the numbers array in half now what we're gonna do is we're gonna declare variable that X is equal to Nam's that's lights 0 to n so this is our first half of the array and Y is going to be our next half or second half if you want to see the array for X so first solution we have our two five one three four seven array and n is equal to e right so if you look at X V T we did a slice on noms array 0 comma n so that got first three numbers if you check why it gave us next three or the second half of the array okay it looks good and what we're gonna do is we're gonna take our variable that you solved is equal to an on theory and this is going to store our result unless we turn our result for later all right looks good now we're gonna we're going to do is go over well look through each element in the array so let's take let's make folder for that is equal to 0 historic index 0 is less than numb that length divided by 2 because the length of the array is half and we're gonna increment by 1 okay all right and I'm not just gonna make a variable CX for current x value and this is copy X index I alright and I'm gonna make another body lcy current Y value and this is gonna be Y index I now what we want to do is we want to alternate between x and y and put the current value into the result sorry so we're gonna do result dot push and we're gonna do critics first because what that's what the problem says and result that push current value of y okay so if you look at our result we got two three five four one seven for the first one let's check two three five four one seven okay looks good second example 1 4 2 3 2 4 1 looks good and the last one is 1 2 so there you know let's go for a code one more time the first thing we did was declare our function which takes in two primaries numbers and n numbers as an array and n is a number right and what I did next was I said splitting numbers array into two x and y so if you work with our second example which was on 1 2 3 4 3 2 1 and n was equal to 4 right it's our input so basically I'll half the array into two obviously and the first half means our X and this is our Y so here X is equal to 1 2 3 4 and Y is equal to array with four three two one ok and what I did next was the curve variable for result which is an empty array and we're returning that result over here now I'm gonna try to go to all the numbers in the array so I just made a followed and we start index 0 and we loop until num start length divided by 2 or you can do X dot length which is the same thing or Y dot length it's pretty up to you and we increased I by 1 so we want to go through every number in the array and I just made another variable to store current value of x and current value of y and now let's go to our result so I made those two variables and if you guys remember it's X 1 solution and y1 and x2 y2 and etc so we won't always push an X first and then Y that's why the result approach current value of x and then we saw that push value of y so let's go to our array so in the first run when I is equal to zero and I is equal to zero this is our result okay when I is equal to zero current value of x is 1 over here 1 and current value of y is 4 so we push in for indirect all right when I is equal to 1 we want to push in we had 1 & 4 so we want to push in we had 1 & 4 so we want to push in we had 1 & 4 so we want to push into 2 & 3 want to push into 2 & 3 want to push into 2 & 3 and now we're done when I is equal to 2 you want to push in 3 here and 2 here and you're dumb to look when I see is equal to 3 we want to push in 3 2 then to push in for here and then last one are 1 here and this is how we get our result which is this over here
|
Shuffle the Array
|
tweet-counts-per-frequency
|
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3`
| null |
Hash Table,Binary Search,Design,Sorting,Ordered Set
|
Medium
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.