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
338
That Welcome To This Trick We Are So Excited To Print To You This List To Problem Set To Spider Title Counting Pisces Then It's One Of Two Problems That You Should Learn To Solve A Specific If You're Already Passed The Winner's Pest Problem Feel Pressure On Six List Check Out What Problem Hai Store Se You Are Ashwin Enter In So You Need To Create A Good Length Inch Plus One Reach 4 Tune To Create In More Sale Of This Regard I Must Contain Number One Step In The Representation Of Subscribe My Channel Subscribe Representation In Front of Subscribe Now How Many Players in the Guardian Form Chest One 100 Dasht Country in the Blue Wave Attended To Like Subscribe and Finally Presentation 3151 Appears in the Winner of the Volume To You Will Know How to Solve This Problem with 4GB Solving Problems Wear Look into the intuition over all the best all want you to subscribe my channel like my videos so let's get solving problem solve this problem of subscription in this list contains representation of numbers from 125 shifting carefully this list gives sufficient number of times in the point Presentation for the number of vansh one you agree to t&c call to the number of w in the t&c call to the number of w in the t&c call to the number of w in the representation of what is the relationship between two to two let's move ahead in this option on checking the number of once in da representation of 5th number of Vansh is to take medicine fury with divide 552 and tak hai is to but here the number of which is the number of funds in the representation of possible when is the number of units point presentation is equal to the number of the point presentation number divided and Rule In India Number One Is Equal To The Number Of The Representation Of Numbers Painting For Lot Letter To That Work For More Numbers Area This City Of Every Side 6 In Front Of Steroids Finally Representation Of 102 Numbers Once In Both Were Equal But This Seven Android Representation in Wave Fighting Back to Three and Finally Representation of Subscribe to is So Our Teachers Professor of Healing Research Institute of Engineering Physics told me that you need to find till then we divide the number to the principal itself Subscribe 4,320 numbers in principal itself Subscribe 4,320 numbers in principal itself Subscribe 4,320 numbers in C Number one is the CM of the number and subscribe number to the number two that by 62.51 digit eliminate first number that by 62.51 digit eliminate first number that by 62.51 digit eliminate first number of once difference between the number result question on this piece ueh some problem The Amazing subscribe The Amazing 1992 * Start from subscribe The Amazing 1992 * Start from subscribe The Amazing 1992 * Start from this point till subscribe number 102 I Boring Want to Tell Me How and Here Them in a Representation of One Is Only One Hindus and Went to Put Vansh Number of Clans Heer The Move Into Two Now Will Apply to Principal Scientist Moment Sakur Saw Your Intuitive 5252 Tiles Ko Minutes Lover Chahiye * Isi one hand the number of runes in Chahiye * Isi one hand the number of runes in Chahiye * Isi one hand the number of runes in final stage of two equal to the number of once in the mid-1960s Points 123 in the mid-1960s Points 123 in the mid-1960s Points 123 That I am coming divide to do Satish Ko * Premiere Questions Page for 10th Ko * Premiere Questions Page for 10th Ko * Premiere Questions Page for 10th number one representation of trees pay plus one number of the mid point two point to the number of punjab school 400 dividing former by two is going to subscribe number one is the population in this question on the move into five divide 5.2 doing to take asir into five divide 5.2 doing to take asir into five divide 5.2 doing to take asir top number of bones in the Representation of subscribe to subscribe the Channel Please subscribe to this * the Channel Please subscribe to this * the Channel Please subscribe to this * Question Tarzan The Number Of Way The Three And Subscribe Skin The Sellout Second Number One Boy To A Lesson Air Tight Matchbox Team 2797 Divided Into Two Take Care In Three The Volume To The Number Of Once in a representation of the bill will have visited there itself which contains the number of wave available in the representation of Indian quarter final list of contents of wave available in the representation of its kind of this problem in subscribe I hope you enjoyed watching this problem Counting From You Have Any Time Govinda Comment Section I Promise Oil Answer Tempering 20822 Let Me Know How To Define DSP Mode Chalu So Much For Help You With Programming And Platforms Thank You Want A Very Good Care Of Yourself
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
1,696
hey hi everyone my name is problem uh the problem is jump game six and the core problem number is uh 1696 and it is k it came as uh liquid medium so the problem is there is a list of integer has been given and also a given integer uh so the single integer is basically if i start point out as a index zero and we can go uh or jump at least at max k state and without going outside this boundary so we'll have to make that um we'll have to make that maximum score i can get through which point i am go that then add that all the value of that index will have to be sum of so basically that there is an in i mean that list one minus two four minus seven three so from i can go to the minus one and from minus one i can go to the four so that is zero plus four there is four so four and three so that is the seven so i can go at least at max that is the seven is my uh the maximum score i can get so right now i'm trying to implement that logic as if i drive and then i'm trying to solve my uh solve the problem as a coding format so basically 1 minus 2 4 minus 7 and 3 so my logic is that basically i am trying to put the fast value into the priority queue so priority so after that pointing that priority queue so 1 there is a pointer then after that i am trying to add that next value there and before adding that value we can check that is my position after adding that uh outside this k or not if that is not outside i can put the value that means that 1 minus 1 that is 0 and this is the priority so that is the zero and one so why i'm putting that so basically there is the zero one two three four five so one minus that top value which is what is that there is the zero so one is greater than two no so i can put that value as a sum so after that so minus 2 what is the top value there is one so and the position is 0 and the 2 minus 0 that is 2 is greater than 2 so not so i can put that value so 1 minus 2 that is minus 1 so that is goes there that is minus 1 2 so after that there is the four so if i've been adding that first of all i have to check so three minus top one that is zero three is greater than two yes that is popping so three so if i've been popping there so zero plus four so that is four and first of all three minus one that is two is not greater than two so in that case so four of three that will be putting there so and after that the minus seven so it's three there so basically uh top so four minus three that is one is greater than two no so in that case they're minus three so minus 3 is came to here minus 3 there is 4 and then after that which is the top value that is 5 and minus 3 that is 2 that is not overlapping the greater than k so that's why i am putting that value as a 7 of 5 so after i traverse all the array so my what is the maximum score that is the top value so that will be written as an answer so basically i am taking the uh extra space of order of pain basically so the space complexities order up in and i am taking the priority so basically the sorting technique is internally happening so basically the end log in is the time complexities there basically the traversing is basically in and then the order have been loaded that is the not order of in login because i am traversing onward and internally that is happening so order of n and the order of uh n also same there so right now i am trying to implement my logic as a coding format basically the space complex is order of pain login order of end login not order pain basically because at max we can not greater then it makes the order up and not possible to stay there so basically the order of n login so my logic is that first of all the basic condition is if uh norms of size is equals to zero in that case i will return that is zero then after that i make uh the initialization of the priority queue that is pair integer and integer pq and first i'll insert that the first value basically that the numbers of zero and at its index that means that zero basically and then after the time try starting my traversal from the order of one i is equals to 1 i less than terms of size i plus first of all i check that while i minus pq dot top dot second is greater than k or not if there is that then it will be popping out instantly and otherwise it will be fast it will check that the top value basically and after that the current sum will be integrated basically not there basically there will not require there so basically that was the current dot fast is equals to plus numbers of i and then the current up sorry there is no required that current if i've been taking so basically the current dot second is equals to that i right now and then after that it will be pushed into the priority queue and now if i reached into that the last one that means norms of size minus one in that case i will return the pq to top dots fast because the top or the i can also set the current first current.fast that one and then after that otherwise if i'm not all deposited then you know that pq dot fast that value basically in that case i am right now trying to return my answer so first of all we'll first check that to the run code then to the record i'm trying to submit my code yeah it is accepted let me take another example let me check another example and the same here we're taking so let me check yeah it's got accepted in the run code i'm trying to submit my code yeah it's got accepted thank you so much you
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
1,647
hey everybody this is Larry this is day 12 of delete code daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's forum and I'm all if you see me checking this page at the beginning of the video it's because there's this button that you can click for 10 Bitcoins I don't know if it's good or not but you know it is always I don't know it's fun to click on stuff anyway uh yeah uh today I went to it's actually still September 11th here in New York and uh you know some you might know I actually went to school nearby there so um uh so it you know it's always as a New Yorker it's always a sort of a weird day though it has been 20 something years um today I went to the Jets game it was a very fun game uh and if you watch the NFL let me know in the comments uh let me know if you watch the game because it was kind of fun the most fun part though of course was that there was free food for me so I ate a lot I'm very hungry so I was very hungry now I'm pretty fine anyway let's actually get to today's Farm 1647 minimum deletions to make out this frequency unique all right a string as it's good if they're no two different characters have the same frequency okay give me a string s return the minimum number of characters you need to make us good the frequency of a character is number of times okay I think this one is um pretty straightforward greedy right um if two I think there are two observations right one is that if two characters have the same frequency um like we've got two A's and two B uh yeah two A's or two and two B's or just like you know they're the same it doesn't matter if you delete a or b it just goes down right so that's one and then the other thing is that we you can always find an answer because if you delete everything uh technically if you have a count that's zero it is not in the string so then therefore you can always return or you can always delete everything to make it good though you know you probably never need to uh in fact you could you know unless you start off an empty string you can always have just one strain right so I think that's fine so then now let's I think that's just the implementation now in that greedy way and because we can only delete um the way that we're going to do it is just cascading from high to low because then you know then you could um kind of handle it that way right so yeah let's do this so uh what am I doing so this just gives us the frequency table I'm a little bit lazy and then maybe we can do something like the max value is this right the max of the thing and this has at least one thing in the map so this one for an error um and then that's it and then we do maybe something like we could do a while loop as well while this is greater than zero um yeah if F of oh um I kind of got a little bit lazy what we actually want to do actually is we're on a frequency of all the frequency values so maybe like an FF is equal to collections.counter dot f dot values collections.counter dot f dot values collections.counter dot f dot values technically I guess this is linears and we do it twice but it's gonna it doesn't change the complexity it just changes the runtime but okay right so then now you go if ff of m x is greater than one then uh or we have to keep a counter right of things we deleted um and that means that for every so we want to keep ff of M sub X is one right meaning if the if three characters appear in um if three count disappeared three times you have to remove two of them right so basically yeah so maybe I like uh count as you go ffmx right um so the MX uh what is it uh we subtract count minus one so that we have one left and MX but then of course we by deleting them we added we add that amount to um the one smaller number right meaning if you have four characters now you convert it to three characters right for the same one for the frequency and then that's pretty much it right and then it goes all the way uh you know goes to zero that's why uh I mean the bigger thing of course is to also count this thing so yeah uh also I don't know why typo that's pretty bad actually let's just do count um this is equal to that and then I don't know and also uh we do stuff like this of course you don't want to repeat yourself you know that's the dry principle and so you do change a thing then it becomes easier all right let's give it a spin hopefully I didn't make any silly mistakes uh looks okay let's give it some it yeah looks good apparently I've done it twice before um what is the complexity here right let's go over it uh it may look a little complicated but it will be good this is going to be linear time of a space a is the size of the alphabet right because there's only 26 yeah only lowercase only 26 characters and therefore this only has 26 space um and then here that's just of 26 or of a uh this is also of a but this part and you could actually do a little bit better than this probably um but because you can actually skip ahead and if you do skip ahead that actually makes a complexity way better is that true hmm yeah because if you skip ahead then I think you can get it down to all of oh wait no yeah if you do some kind of skip ahead then this is actually over 26 or of alpha because then invariant is that every time you do this we subtract one um uh which we subtract one from a number of duplicates right meaning that this thing at most is all 26 of them are dupes uh in terms of number of frequency so you subtract 25 of them and then the next step I'm mostly going to be 25 and then 24 and then so that'll be all of alpha but the way that we actually did it because I'm lazy uh is going to be o of n because oh no um actually I think this is still right but the MX makes it all of n because we kind of look for a lot of uh a lot of values that are zero right so definitely we probably could have skipped ahead a little bit maybe hmm oh well yeah so this is of n plus a but of course it doesn't change the overall complexity because this makes it off uh n anyway but you know on running time you could definitely be a little bit better uh what did I do previous times oh notes oh I didn't know I could add notes Here don't care for it but apparently last time I also did the same thing uh and the first time I huh man this is very complicated looking but I mean this already yeah no this sort of just makes it a like a bit just marginally more expensive anyway yeah that's all I have for this one let me know what you think let me know if you could do in one liner apparently people in my Discord have been playing with that I don't know uh yeah stay good stay healthy to go mental health I'll see you out later and take care bye
Minimum Deletions to Make Character Frequencies Unique
can-convert-string-in-k-moves
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**. Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._ The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`. **Example 1:** **Input:** s = "aab " **Output:** 0 **Explanation:** `s` is already good. **Example 2:** **Input:** s = "aaabbbcc " **Output:** 2 **Explanation:** You can delete two 'b's resulting in the good string "aaabcc ". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ". **Example 3:** **Input:** s = "ceabaacb " **Output:** 2 **Explanation:** You can delete both 'c's resulting in the good string "eabaab ". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). **Constraints:** * `1 <= s.length <= 105` * `s` contains only lowercase English letters.
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
Hash Table,String
Medium
null
243
welcome back everyone we're gonna be solving Lee code 243 shortest word distance so we're given an array of strings called words dict and we need to find the shortest distance between word one and word two so the example they give us is word stick is equal to this array and we are looking for coding in practice is at the zeroth index coding is at the third index so three minus zero would be three uh is there another one in here practice and yeah so the output would be three uh word sticked again we can run through this whole thing we're looking for makes index one and coding is index three but we have another so three minus one would be two but we also have another makes over here so we take the index of coding subtracted by this index and we get the well we would take the absolute value if we're subtracting the smaller number first and then we would get that output of one okay so how can we do this well we know we're going to have to calculate the distance between two words so let's make a variable called distance and we will set it equal to uh float of positive Infinity first now in order to do this in one pass we're gonna have to keep track of two other variables let's call them W1 and uh W2 we will set both of these two floats of infinity okay so now what do we need to Loop through our array and find the index of if we're looking for word one right we'll find the index of word one which is coding at index three and then we will update uh word two what is it word one word One respectively so this would be three instead of float of positive Infinity and we'll do the same thing for word two so let's do that so we'll say four index value in uh enumerate of what is it called it's called the word sticked what are we gonna do we need to check if that value is equal to word one then we need to update W1 to be the index and if that value is equal to word two we need to update our um word two variable to be equal to the index right and then after we do this we can potentially update our distance right so say we have example one again right we have coding at index three and practice at index zero right we would update these after we've gone through this for Loop and then at the end right we would update our Max to be 3 minus zero which would be three so how can we do this we can just say distance will now equal the are we looking for the minimum shortest distance minimum we can say distance will not be equal to the minimum of either the current distance that we already have or it will be the absolute value of word one minus uh word two and then we can just return distance at the end let's get rid of some spaces we'll run this we pass both test cases submit okay so what is the time and space complexity of this problem we are not using any extra space so we are o of one for space time complexity is going to be what we have a for Loop here so that is going to give us o of n however we are making a string comparison with inside this for Loop every time we iterate in the list so that string comparison is going to be um an O of K time right so this is this Loop is essentially going to give us an O of n times uh K time complexity and that'll do it for liko 243 shortest word distance
Shortest Word Distance
shortest-word-distance
Given an array of strings `wordsDict` and two different strings that already exist in the array `word1` and `word2`, return _the shortest distance between these two words in the list_. **Example 1:** **Input:** wordsDict = \[ "practice ", "makes ", "perfect ", "coding ", "makes "\], word1 = "coding ", word2 = "practice " **Output:** 3 **Example 2:** **Input:** wordsDict = \[ "practice ", "makes ", "perfect ", "coding ", "makes "\], word1 = "makes ", word2 = "coding " **Output:** 1 **Constraints:** * `2 <= wordsDict.length <= 3 * 104` * `1 <= wordsDict[i].length <= 10` * `wordsDict[i]` consists of lowercase English letters. * `word1` and `word2` are in `wordsDict`. * `word1 != word2`
null
Array,String
Easy
244,245,2320
139
hello welcome back to my channel again today we have leeco 139 word break so this question is really popular and you see a lot like often asked by facebook amazon and more let's take a look at this question so given a string s and a dictionary of string word dicks return true if s can be segmented into a space separated sequence of one or more dictionary words in short it basically means that you have a string and a raise of string if you can use the word dick in here to make it uh this string using the word inside here completely then return true if it's not let's take an example here lead right here code right here so it's fine apple again you we have it pen we have it and apple we also have it so you can use a word inside to combine this word but in here dog right here there's only one word in here can be used so dots right here and also we need to combine to find the words in here to combine this uh string which is not really possible you can't find any s a n right here end up with s a n so it's not going to work so we turn fast so basic idea is let's draw um the example leeco right here we first we create a boolean array but we write out like this so easy to see so you can imagine this is all false at the beginning the boolean so it's all false now it's index 0 all the way to the n now we can first look through the whole entire string so we have an eye look through that string so i will keep moving to the right so every location it then it will check another y for example if i is here keep looping in until t so next for loop is y we create a y loop through zero to the t to grab everything like first we grab y zero so zero to i which is l e t if l e t's inside this word dict will not so if this hap or this word in this vertex then this location will have a chill here this is how it is and since this one is true then next time when we move forward when i is right here it will check from zero again all the way to the this location basically keep checking l e lee if one of them in uh the dictionary so we'll have this location as true yeah and just keep tracking of that and we find out this is true and then we keep looping the i all the way to the end of this array first we check if the whole thing's whole entire things inside this word thick or not so it's not so keep moving this y pointer to here and to here so now there's a checking like if the previous one sorry oh if the previous one texture if the previous one here is true then we check this location which is c-o-d-e and check it uh c-o-d-e and check it uh c-o-d-e and check it uh if it's in the vertical nut so if it's if that is in the vertex then this location should be true so this two conditions met then this location meant to it's kind of confusing so let's jump into the code right now and also leave this right here first we have a boolean array called table equal to new boolean the link it will be the link of the string so next one we have i equal to zero that loop all the way through table dot link okay yeah and then now we have i also we need to have end y equal to zero and y is less or equal than i we need to look through this one by one until you've met with that eye location so y plus and after that we need to check only two conditions will check it so when i equal to 0 or that table y minus 1 is true for example in this situation if i is right here and y is right here so that means this everything before that is true right here does that mean everything before that i would check that have words in there so now this condition matt and we are checking anything after that we're looking for the word to combine together right and also y is equal to y i mean y is equal to zero then i also need to check so at that situation check if the vertex contains let's sub um the sub string what is that substring is right here so y is right here the substring will be y i plus one if this is true then what we can do is put this location as a true which is where i located the table i equal to 2 after you find the true then you break it break this for loop break one for the bony so this i is already founded so we can move the eye forward yep that should be it um at the end when you look through the whole entire thing we have to check the last location right here if this is true that this whole entire word can be combined with this word date then we return if table sling oh minus 1 is true and it should be it and let's erase this code try to run it one more time and it looks good and that's it for this question if you have any questions please comment below and i will get back to you as soon as possible until we meet next time bye see you next time
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
235
Hello friends today I'm going to solve liquid problem number 235 lowest common ancestor of a binary search tree so we know a binary search tree and it um any value to the left is less than the root node and any value to the right is greater than the root node right now we know that thing and now what is an ancestor so we are given a Wikipedia definition I don't want to go you over that I'll just explain you what an ancestor will be through this diagram so suppose we have a value for and a value 7. now the ancestor would be the great grandfather or grandmother maybe anyone uh so both of them will have the same grandparent so four and seven they have a common ancestor which is six because now they are splitting right from six so that is one way we could actually identify the ancestor because 4 is splitting from six and seven so these are actually six is where it divides four and seven because in binary search three four you know four is less than six so it will be towards the left of this node and seven is greater than six which means that it's towards the right always towards the right which means that 6 is dividing both four and seven so that is our solution our answer now what if we have something like four and five in that case which is the ancestor well the ancestor could be the node itself so in this case what we see is uh we check from the very root node is four less than six or yes it is and what about five is also less than six port or less so we go to the left because every element every node less than the root node goes to the left right so that is where we will find it to the left of the root node so we go to the left and now we reach two now four is greater than two what about five it's also greater than two right so now we go to the right of two which is this sub tree here now here we see like four is equals to four which is our condition to find that to note that we have reached our ancestors so if it 4 is um 4 is neither less than 4 nor greater than 4. that is when we found our ancestor and we return our value so yeah um let's dive into the code okay so to solve this problem uh we are gonna use recursion because what we are doing is for each of the node we are checking if uh p and Q lies to the left or to the right and then if we found when we go to the next node we are accept tree we are again checking if p and Q is to the left of this node or to the right of this node so we are repetitively checking for um for whether the values of p and Q are to the left or to the right so that is why we will be using recursion here so now Eve P value is less than the value of root and Q is also less than the value of root which means that our answer is to the left so we call lowest okay I'll just copy this call this function and we go to the left uh with us the same value of p and Q what if p and Q are greater than the root then we are gonna go to the right return a root dot right Q heels okay so I need it else if here elves we have found our solution so that is where we will return our root okay let me run my code submit it woo so the time complexity is O of um what would be the time complexity okay let me think so since we are traversing uh one node at a time so it will definitely be less than the not total number of nodes in this route uh because every time we are dividing our search Space by half okay I'm not sure what the time complexity would be but if any one of you know what the time complexity would be then please let me know on the comments below okay have a great day guys
Lowest Common Ancestor of a Binary Search Tree
lowest-common-ancestor-of-a-binary-search-tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8 **Output:** 6 **Explanation:** The LCA of nodes 2 and 8 is 6. **Example 2:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4 **Output:** 2 **Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[2,1\], p = 2, q = 1 **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the BST.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
236,1190,1780,1790,1816
1,177
hello everyone so in this video let us talk about Wonder problem from lead code the problem name is can make palindrome from substring so the problem statement goes like this that you're given a string s and an array queries where query of I is has is having three variables left eye right I and K of I what all are these three things so you may rearrange the substring from s of left to right for each query and then those up to KI collectors you can replace with any English letter so what you'll actually have to do is that you are given the stringers and you have to do some queries online now let's say a query has left like a left bound right bound and a k now when you are given some query you can take that particular string from left to right and you can like rearrange all the characters in that substring what in whatever manner you want and also you can have the capacity to choose up to K elements like from that whole string and you can change it to any other lowercase character that you want after this whole operation user have to tell that the new substrate that you have formed by reshuffling the whole characters and replacing at most K characters whether the possible string that you have found is a palindrome or not that's the whole thing and just have to find out now uh the overall thing is that to check out whether a particular substring or like any string is palindrome we just have two conditions that it has uh it should be a mirror image about the center okay for that everything should be in pair and if it is odd length then the last the middle character should not be in pair but for a for even or odd length except the middle character or like for an odd length acceptable Captain for even length everything should be impaired okay every cat and you can format a parent or so because it has a lot of queries after five and also length and five I cannot just do this for every uh like in a very boot first I just have to get very instantaneously very quickly what is the number of characters for every substring I have and because that at most 26 characters I can just do it in us some sort of a prefix some type of problem what I'll do is that I will form a prefix sum over this whole substring that at every instance how many characters I have okay at every instead of this particular string I'll tell you the diagram and then if I want to find out how many instance of every character between a particular ranges I'll just use the prefix sum to get that in O of 1. and when I have the particular values of elements in a particular substring but eventually I have to find out whether after doing key operations whether the whole of prefix is operation let us take that into account that is that the whole string is s a e o s r t that's just random word now what you'll do is that you will make a matrix like this which has this number of columns which is fine okay and 26 rows zero so let's say a row for a Row for B Row for C and a row for Z like this let's say that the first character is and let's say s is here somewhere so you will update this S1 now the other character is one here so I will update one here but I will also take this in a prefix manner so whatever values are here let's say zero and one I will also carry forward this to the next column as well and append these values by this so this will be added 0 plus 1 that is one only so this because it is a only so this is only added once here nothing else in this particular column is updated one of them will be zero but all the values will be shifted so this will become zero this will become one because this one is coming from the left hand side will become one zero so now this particular column has two ones now V so let's say V is somewhere here somewhere this here and it is also now becoming one so when I transfer the column values to the next column this will be transferred as one because this will be 0 because there is no a but a is coming from the back okay so this is one this is again those D's as of now to zero then zero this is coming from this one and this coming from this as let's say 0 and this is V so this is coming as 0 and this is one okay so now these are three ones and so on so you can keep appending now when you have let's say one more s so you will append this is coming as one and when I see one more s this will become two what it eventually tells us that until this point like at this point I have 2s okay now what it eventually help us is let's say that I just want to tell how many s are how many o are there between this point and this point okay I have a number of O's that are traversing like this maybe let's say the number of B's are there on a number of let's say number of e order let's assume number e okay the number of e let's say may be stored here and it has appended at this point that is 1 and then it is it might be traversing because the columns added now at this point I know the number of E's is one and this point the number of E's is zero because ease I added here so if I just subtract this from this value I will just get the number of E's between this range because before this there is no e after this there is all R here so I will just get how many occurrence of e are between this point between this particular range and I can do this for all the Getters like how many A's are there between this range how many asps are there between this array and so on so I have all of these particular characters how many of these characters are there between a particular substrate so from left to right I can just do this in of O of 1 because there are 26 cat 26 columns energy they are just constant so what you can actually do is that you can just do this in O of one type of only because the 26 column not much dependent upon n and you can just get that how many uh a b c are there between this particular range okay now you have that now let's say I have two is I have four B's and so uh okay and then I have one C okay like this now I have also some K value like how many changes I can do let's say I have 0 okay I cannot do any change so what I'll do I have this information I can just have to check that whether I can do some changes in this particular string and make this as a palindrome now for a palindrome I just have to check that uh what I have to check that everything should be in peers except one character efficient odd length or it should be evenly paired out so a is or evenly paired out B is evenly paired out by appearing Out means that if I have a string let's say a BBC I can put two A's on the very end then two B is like this and again two B's and then one C in the middle it is a final row same on the left hand side right okay so what we'll eventually do is that we have this information I can get that if I have some K okay what I eventually do is that I will first change out these characters that are not figured out okay so if there is some character that is paid out then I will not change like if it is better you don't want to change them because it's already paid out they eventually formed a parent rule but if it is some that are not available okay I can change to get so I will just change this D into C so that this c will eventually appear with this and that's it so what my overall goal is that I will subject how many order forward numbers are there that are not divisible and then like pair them out somewhere and it can be weird then it is called else so what we will do is that uh we'll first find out that prefix Matrix so we'll just make a vector of n size that is n columns and it has 26 rows or we can do vice versa also that it has um like it has 26 column and uh n rows whatever imagination you can do that and then build that prefix array so whatever character you have first up like add this value and like let's have a so add it into the next column that is I plus 1 and then from the previous column I will just like let's say previous column I will add all the values in the next column that is I plus one so that is how you can just transfer the values where the 26 values 26 will be transferred when this is valuable transfer to the next column that is how the prefix Matrix is built now uh we just have to find out the answer we'll introvers all the queries so a couple of queries left and right so and this number of operations I can do that is K so I have to first find out uh let's see now like there's a base case that if the number of operations I can do is greater than the cactus in the substrate let's say substring as five capitals and I have 10 operations so I can just change all the characters into same character and that is always to that I can form a parallel branches two always else we have to first find out how many odd characters that are not have the same priority or that are not pairing out so I will set it off all 26 characters and what I'll do is that I have to find out how many characters are there in between the left and right range so just find out that and then if it is an odd the character is odd that is not zero and I just increment the odd characters eventually after doing this for loop I have a number of four characters between this particular substance that I have that I want to make a substrate like I want to make a pendulum now what I'll do is let's say I have uh five operations okay so I have uh let's say a few odd numbers and I have five operations so in each operation I will make one odd number equal to the another odd number okay so that they can they will be forming a pair which I've told you and they form a pair and they can be canceled out and we will move to x dot number so what eventually I am forming out is that for every one operation I'm removing out two characters because one let's say there is one C and one C both of them are matching up and they are removing because the odd numbers are that they are odd they are not pairing with something but now by changing or doing one operation I'm making up here because let's have two odd numbers they are C that is occurring odd times and D is also occurring or times what eventually means is that I have not paid CND I just make a pair of one C and One D that is I just convert one C to One D and they will be figured out and they both will be more comfortable so a number of elements that will be removed out is two into operations okay if I have let's say key operations I will remove all of those elements from the odd list I have now eventually if the number of odd elements that are left is e like less than like zero or less than or maybe uh maybe after 10 minutes operation it is one also then it is fine we can do that and make it into parental but if it is greater than one then the answer is false because after doing this whole operation also if there are more than one odd numbers present inside the segment that I'm talking about then it is already false we cannot make it palindrome unless you can make a paradox answers too and we just return the answer for all the queries that we have and that's it that's not our logic and the good part for this particular problem if you still have any doubts you can imagine in the con box for this particular problem thank you watch video till the end I will see you in the next one thank you coding and
Can Make Palindrome from Substring
tree-diameter
You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter. If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`. Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`. Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`. **Example :** **Input:** s = "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\] **Output:** \[true,false,false,true,true\] **Explanation:** queries\[0\]: substring = "d ", is palidrome. queries\[1\]: substring = "bc ", is not palidrome. queries\[2\]: substring = "abcd ", is not palidrome after replacing only 1 character. queries\[3\]: substring = "abcd ", could be changed to "abba " which is palidrome. Also this can be changed to "baab " first rearrange it "bacd " then replace "cd " with "ab ". queries\[4\]: substring = "abcda ", could be changed to "abcba " which is palidrome. **Example 2:** **Input:** s = "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\] **Output:** \[false,true\] **Constraints:** * `1 <= s.length, queries.length <= 105` * `0 <= lefti <= righti < s.length` * `0 <= ki <= s.length` * `s` consists of lowercase English letters.
Start at any node A and traverse the tree to find the furthest node from it, let's call it B. Having found the furthest node B, traverse the tree from B to find the furthest node from it, lets call it C. The distance between B and C is the tree diameter.
Tree,Depth-First Search,Breadth-First Search
Medium
1740
1,029
hey what's up guys chung here again this time let's continue our elite cold journey here let's take a look at this problem 1029 to CD scheduling smarter as easy but to me I think it's like more like a upper end a fancy question because it's not that straightforward but let's anyway let's take a look basically you're giving like a array of two in people's right and for each element represents the to cost for that person the first one is the cost to send that person to CDA and the second one is to send the city to send that person to city B and you need you can only you need to send exactly unperson to that to each city right and then you need to write an algorithm to return the minimum cost basically to evenly sending those two people into state into the city a and B right so this problem is like it's a greedy problem basically every time right we choose a person that's the optimum to send to either CDA or CDP right but what's the criterion of after optimal but option at the moment right so as you can see here right so it's obviously that if we choose let's say for the for exam with a 450 you know the difference between sending this person to a and B is 350 right and this one and for the other one for the let's say for the first person don't the difference will only be a only be 10 right so what so that means that the earlier you know if we have if he sends this person with the biggest difference at the as early as possible which means Adam if we send this person as early as possible it's more likely we'll be able to choose between this will be will have the ability it's more likely we have the ability to choose if we want to send this person to a Twitter a CD A or B right let's take assuming let's say we process this one later on to the very end right then and this is a and B right a and B I'd say when we before processing this person so let's say we already send an persons to the CD be it already has M persons then when we cease this now since this person here the only choice we have is it's nothing but send this person to a write that will give us like a worst a worse result right so basic no it's I think it's pretty clear that what we need to do is we need to sort by the difference of each person right and then we sort or we start processing the person's from with the biggest difference first and then it will have a like a best possibilities to choose right basically to save the cost when we process that person unitary like might there might be some other ways of doing this problem but I think the way I just described was the one I felt like what felt like kind of intuitive at least to me I mean you guys can help ID other process i other solutions were ideas but the concept here is that we need of some health I'm basically sort by the most gains right from the most against to the least gains right that's the key idea here okay let's start coding here and so at least from my solutions here I need to sort this cost right by the difference right so I'm gonna do a sort here right and the key is that lambda right I'm gonna sort it by the X so I'm just using an absolute value here to sort the most the biggest difference right I think I saw another solution instead that you can only you can also sort only sort by the first but by using a miners the first one - the second miners the first one - the second miners the first one - the second one that then you know what's the gains by sending a purse ending the person to a not to be right that will also work but I'll just finish my code here based on my solutions here so basically how to uh to our likes acts right 0 and x1 right so that's how it I do the sorting and like I said since we're going to process from the most significantly the most people who have the most significant difference so we're gonna do a reverse right equals to true right so that's how we do the sorting and not and then we have a and then I have like this first answer right will be 0 and I'm maintaining like a count and the B count here that's can help me keep track how many persons have been sent to a and B right and also in here right so and will be a length for each city will be a length of cost and / - right because we of cost and / - right because we of cost and / - right because we basically will be having 2m persons in the cars and for each cities we need to here we need that this length divided by two so now we can do a cost here since we already stored it so a cost because right in cost right so we do a track if the if a cost is smaller than B right then B cost and what and the and then we just do what we use the cost from a in this case right Allen's answer plus a cost and we will just increase the count by one actually we probably don't need to count turns here all we need is this one so first condition starts or right and or the B count is equals to the end right so if we already have this B can't reach the maximum capacity up CDs so oh we don't need to worry about any of the conditions here which is to simply assign the cost right I think in this case we don't even need that we all we need is a counter for a be so Alves right also we are basic what we do we use the be counter so the because right and then we simply add the B count by one right in the end we'll just return the answer I think this should work um nope ah I know so yeah I think we still need this counter a here because not everything not every time a smaller than B we need and another condition is that end right and the a counter is smaller than the end right and then yeah I need the parentheses to group those things together so those two things will be one conditions or right or like I said or this B CDP has reached them not the most capacity here is that with the is that in mind we also need to maintain this one here yeah I think this time should work yeah so we still need to still need two counters to count a and B here basically after sorting it by the most by the difference between sending the person to see the a and B every time we just do a quick track here right so we try to sort this thing as best as we can this is a like the greedy algorithm here both from here and here right so as long as we have the ability to choose from a and B right then we'll choose the better smaller cost between them if we can choose anymore we simply just stand it simply just simply set this use this city a here right and otherwise we're just to a send this person to the city B and we increase the count and cool I think yeah as you can see this is not the most optimal solutions but I find this kind of like more intuitive to me yeah I think I hope you guys enjoy to enjoy the videos thank you so much for watching it and stay tuned and now we see you guys soon thank you bye
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
863
This is the code for coding on Samadhi sites and in this video, Amit solves the problem and enters it. So, let's see the problem in excel, is it big and you do n't have only one take, the distance will be life or the bank is the giver in it, that the bill is there. It is okay to fill and this note is cut or made, then after the value of a single note, the value of that note is the coins distance away. If you print all the notes you get, then actually the problem is that you have this problem of water. In this entry of this time of life, if I was giving you, as if here, this note, which is Jaipur Railway Ministry, on this, let's say, forced data in Italy, that data was like objectively arranged four, then what does it mean? This means that whatever notes you see are four distances away, which four distances will be required to print them, like if there are four distances, the less time to print is 1234, then this note is 4 distances away, this note is four distances away, then 12345 1234. Notes plus 2 F 3 incomplete 1234 Note 4 Distance is far and such reasons If 1234 notes are far then I have to get someone to print all these notes feel relaxed and return it to you then what is the problem, your notes will be received as if I gave the note Inside this, you can get any run quiz, that few words, note about you will be strong, I get support, it is strong, four distance, whatever should be only life, only 2019, whatever is there, will depend only, if one is given, then you will come and one. Print only one 5mm wicket Note from such works is life This team notes Our volume is above distance I will talk about distance in the meeting Distance from bones Notes will be like distance is normal Then this note is one two This is a note, all the notes are at a distance from it, in the same way, at a distance of three distances, then by doing the chart in it, you will get its value, while the value will keep changing, which means that this will be the benefit of the user base, so whatever input it passes. On this basis, you have to tell that all the notes on that lease distance over this particular distance have to be returned in full relation. So the problem statement is this, so now let's talk about how we will solve it. See, what is the problem, isn't this the foundation? The problem is that the Foundation Center was used in a dream by someone else like this, there I used some extra storage, so if you have not seen the video then watch this video, you will get the video above level-1 as we get the video above level-1 as we get the video above level-1 as we go home way here. But inside Laxman, you have to go inside the pentree, in the binary tree, you have to take life here or were the distance away from the present, so inside this, its solution is explained here first and whatever notes we make to everyone about the distance inside this, then this sim Do the problem again a year, but your approach is a little different. Let's see how you have approached. If you have to print all the notes of the distance, then subscribe or what will you do by adding in it. First of all, you talk about others and yours. Considered unsuccessful, we know what I do here, I take 2 note 5 mobile, I order it after 2 note, then the root of 2 note will come out, if the idea of ​​​​if idea of ​​​​if idea of ​​​​if one after the other, the abstinence will come to us, then I Zero node - 02 1345 then I Zero node - 02 1345 then I Zero node - 02 1345 All these notes come to me and you get 12345 notes. Now what will be the next step? The next thing will be whether I take a function or take a swan of download or don't name then this problem will be solved. It solves our routines and we know that we have solved this problem. I will take the video of this problem and provide it to you in the description so that you can understand how to solve it, so now I have it, look at the area. This is all within me, as if it is the whole matter from beginning to form, what is it, Vijay 8080, the complete path has come to me, now this complete path has come, so now inside this problem that it came to me in the rally and Look here, sugar melts, how far below the bow do I need to print things, like how far down should I go, like the distance down where I have to go, that is, there are four there, so you are like this Write that if I have to go to road distance and print things, then the difference I have made for 'For' is my print things, then the difference I have made for 'For' is my print things, then the difference I have made for 'For' is my own thing, like below means below J3 that don't you have to call the function or will I put Pancham, what will I do, friends, whatever note I will pass and someone else. I will pass the physical if I go down so many levels and print whatever note I get, then what will it do, can I maintain a table, an answer playlist, love things for that, so see four-five curry here 332 206 I have four-five curry here 332 206 I have four-five curry here 332 206 I have lost 120, this means there is no use of going further down, you stop here, okay and I pick up all these notes and print them inside myself, I store the answer ball, for this only print it. I am here, we have bit the value on Tuesday, we have stored it, son, it is okay, son, minister, now after this, the next thing I did is that now here I have a block note, what time will it be, so it can also be called without box and Baikunth Lok. If you do not reach then delete it, then this problem becomes a little difficult to understand, so here there are four dispensary channels like K's rallying for - which four dispensary channels like K's rallying for - which four dispensary channels like K's rallying for - which if I talk about I, you can understand from the search below the chart that all these notes we go Print it out, but if I talk to Aai, then I would be like, how much distance has I used in coming and going, meaning I would have come and how much distance I would have used in travelling, I have used one more minute of distance, total how much distance is there. I had to print all the notes at a distance of 4 units from me to get milk at a distance of 4 units from me, so I had to print them at a distance of four units from me, all of them were used within a minute, so I have them. How much unit heifers distance 3 minutes and distance heifer butt will he like join ISI and then go down three distances and print things will it be good Parishad Cycle Mukesh what will you say three registrations JCI ICJ selecting distance done do n't do this Can we mean that I ca n't have such positive emotions, I can't do such positive emotions, I once up or down group, this chocolate is not allowed to me, then obliteration is not allowed, it means weeks, it makes sense that like let's find out, due to which I got up or down. If you want to print all the sides, then how much lower than I am, for - 1410, how much lower than I am, for - 1410, how much lower than I am, for - 1410, look how rocky this is, three distances away, so if you look carefully, let me tell you the problem right now, problem statement is coming, all of them have become but me. So there is no need of zero MS Word, we will take sugar, if we get them concrete then they will be asked to pay one minute, 2 units per unit, 4 minutes. This is because tuition is done, that is, you travel twice on the same route, this is not low, two on the same route. Bar traveling is not allowed, otherwise what do we do? What do we bring here which is called the concept of block note, that is, when I am good on the I note, then at that time I pass a block note named J. I will check inside, will you pass the block note, on the other hand, I will login for you and I kept it, I did not want to block anyone else, I passed the block note here, on the colonel, when I come, I will pass the block note. I will do it, Jai Ho, what benefit will I get from it, thinking about what benefit he is going to get, now if I block the J note here, then the Pi note will give its left trick like phone call or butter industry, oh this is left. Note, my block is equal to the road, he will not go, that is, he will not travel to all the places and will come back from there, doing packing and after covering the back from here, he came back to I and to come to I. After this, we will start calling it three distances at the bottom, okay and here I am distance KM distance road distance BOW, that is, my answer is done BDO W that is one letter WW and do gas, we will come back to this now. On top of this, the experts will also make the users lucky by using the recognition step and then move towards the solution, for that it is important for me to explain it will be very important only then we can understand the problem. Now let us reach the app. Now look, so that I know how many units and distance I have used, like now I have used two in toe distance, this is the index of the thing, that is, here you have logged in for-two and all and who you have logged in for-two and all and who you have logged in for-two and all and who will become the plot, once. You see, from where the same cord is being made a lock note in RNA, so I am going towards ISAF, then the person who came is aptly and went and I typed in the box and I am coming from this side of you, I myself think that Now you are coming from the side, you will block the same turn that my answer is if it is coming from the right side then I will block them on the right side, my answer is coming from the left side so I will block the left side so mine got it from the right side. I have blocked the right side here, I have not blocked the upcoming turn, lock it here, call point here, grind these two, now I can't go to the right side, so go to emergency 101, add here, okay, profit and I am on the seat like sewerage, think how much you will pass here for - pass here, you will pass here for - pass here, you will pass here for - 3421 so for nice is equal to one, it means 32 distance is used to reach JC, now 10 top districts from the scene are printed below. Which one else is printed below, G is printed there, G is printed here, for - for - for - 179 had been left, so the distance in one becomes G and then the paper life for - co means and then the paper life for - co means and then the paper life for - co means zero in this, you will definitely get C. Now like this is near. Now I come, what is the meaning of this zero distance of any disease that I have to print this mode, so I go here and print this note, then go ahead and - 5 - then go ahead and - 5 - then go ahead and - 5 - will create a clock off, but this In row, it does n't matter what is the value of the distance - if it becomes negative then - if it becomes negative then you want to work on further travels but keep the flop on, you could have broken it also or if you want, one frequency from Punjab Central. You can also return by calling the function, then I understand return or 30, either if you become soft in my form, then you can return, don't I am talking about function, I am worth one millet on you. If we write the function then for this we will add the function 212 of both of them, it is an actual problem, that is, if we want to ask a question in this way, we will be able to switch it on very quickly, so let's see how to do it once, but that practice is boiled so properly. Static boil aa that inside k don't and k don we here how much verification should be done on hands free mode route and one block note here and we have to do that how can I create a block note and you will get fairer list for good result for good Coming soon, what will be your first task? What will be your first task? If you do not get fruit, friends, rate is the end, robber bride Jyoti, give us border news or if you get busy, then returns will be imposed or whatever is my milk. So people can come after turning that block, I will return then as if you are interested in the block note in my form, then this lining will not be known, we will do the alphabet system, then I will call the function of affected and name, Loot Lakhya Ke - this Loot Lakhya Ke - this Loot Lakhya Ke - this was the dynasty. If you pass the reply mode setting, then this is one of the occasion and then you will place a call here or for the right, then it is like I have come home, that as soon as you drink here, the alarms come. It is like if we add 'A' and 'Answer' come. It is like if we add 'A' and 'Answer' come. It is like if we add 'A' and 'Answer' then here we will divide the answer 'Root is then here we will divide the answer 'Root is then here we will divide the answer 'Root is top spread' and now it is 2000 so what is the point of going down Cricket did not reach at all, here you should return ok Now on the basis of this function, let us know how that code will be run. We will fry it a little and test it. Then I will tell the final destination through a code in which way it is the optimized version. That without this extra, so it can be skipped, I will see your thing, I have this statement, okay, now you can see the code, it should be visible and the total should be 350, okay, so I have this requirement, Jhal Trip first. Let's make a root to note thing, we will see a little bit of dough, a root to note, clearly, the size of Parmesan 123 456, we need a quarter inch of hearing, which is here this morning, as I came to FC3, before the darkness of the night, this is the limit which Click OK, let's talk about it here. This zero has come to me here from 12345. OK, here we can keep our data. The data we want to find is that I have Jain and here there is only one life. That's good, okay, so now let's start traveling here, a monk in Jhal, everything will be visible to you, this is how the sea express was stitched, let's look here, first of all, I have the function of the don of IPL Mumbai, now I am the function of your Donge. Let's call that with surgical I pass the root note to it like how many passes I have to pass here only one value will be passed here K is 124 neither for - zero here. We will press and here for - zero here. We will press and here for - zero here. We will press and here we have passed and to whom should I present the block note, there is no problem for the jet, we will pass the option and for this the block note is done, tap and pass the SIM in parts, now just see how Vikram will do it and now you You are going to IG and making a call on the left and how much data will it take? Do you have data in the last 4G network? I am going to the left on taking data free because when I make a call to the email app, it becomes - I am okay, when becomes - I am okay, when becomes - I am okay, when t0 goes, we will return, then in the form of a child smaller than zero, if he is not taken in the block of Brahmins, then he will not get any benefit. Okay, hmmm, I am coming to the left, you take it, then we will take the copy and By taking left embezzlement, you become a teacher here. By taking left zero, your value becomes zero. What does it mean to be zero, what does it become equal to? This is Ujala Data Kunwar, so there is an answer name inside the preparation list. We will go and fold this place. Okay, I felt corrupt after going to this place and let's back track from here because we have found sociable people here that we look inside your answers every day, then why should we return from here? The cord that will go towards the right side, but the type is sonal, okay, if we get the right, we will return it, then we went to ma'am, now if the mango is bright, we will return it, then we have reached it, who will go to the right now, then it will be like a night I get a call in quiet, like who does it seem? You go to the bank by taking two, there was a tap on the left, now you will go to the side, take a drink and then go to this well. Who is the girl and why did you reach here with zero and something like this? You will go here and print it, papaya, you are going to the right, how much data are you taking, take zero, then print it, then you will go back, finally you will beat the cancer, how will you do it while sitting, now you are going to the right, you have gone to the right. We will reach with the data, go to the right, I have help and I have the data, I thought very quickly, but there was no left, okay, let's go to the right, we went to the right and will reach near like here, when you reach here, this data will reach near like when Now after taking 12, a call was made in this fort, while a call was made in ultralight, that is, extra was done, both of them got the batter, did both of them get the batter, then after sitting in the final, now after doing extra, the present well used to be there, if you remember. Yes, that media, if you see, there was a flop going on, it was followed, now it used to put I means equal, witch for - now it used to put I means equal, witch for - now it used to put I means equal, witch for - wall, now like I put a call for management, I has so close to the data, there are three meanings in this. Here they are, I have passed 3, here there are only three passes and how to block the note in this, why is it so bad because when I got it from this side, I block the claw note, see this, now I have a clock. There is a note here, when I came to the jail, a call was made on the left side of the date, extra but that the left note is now like a bank, it means you will not go to the block boy's side, now I have gone to the side of the new one and did it from here as if I From here I am done, now the right to recall will be applied, we will take this piece near the valley with the right to recall and will apply the furnace chapter with data two, it does not do the registry, okay and let's go to the right, then you reach here to it left one. Reached P Ravi with zero, then you painted its inside also, reached I, behind here, near New Delhi on the right, added your W with zero, then you are batter from here, factor from here, finally packed from here. The track is exactly in it was made as you will read now and - Duty has been made as you will read now and - Duty has been made as you will read now and - Duty has been placed in which it will be made in the box, the plot has not been made in the app, it is 200 ns to meaning you i.e. inside the Saif note, the 200 ns to meaning you i.e. inside the Saif note, the 200 ns to meaning you i.e. inside the Saif note, the letter to will be placed on the left hand corner of the note, we are mature. Going left data one and I'm going one secure, see this from left data, we will spray paint one here because as you remember, you paste it here, but now like I came here to X, now exclusive. If you have done cigarette then return is done, now you will come to chew as you want, call HK right but if it is not done then return will be done because roti ko donal means return is ok. Now I reached to the app and I wrote copy and I put this app lock on Note 4 and I put a letter on it, you are taking my Wi-Fi, my home is I this app lock on Note 4 and I put a letter on it, you are taking my Wi-Fi, my home is I this app lock on Note 4 and I put a letter on it, you are taking my Wi-Fi, my home is I block note, it means I will not go towards the right, it will go abstract, after tracking back, finally both of them got it like this. The company did Vectra and went straight to the pass by taking a four -three, just like returning boss by -three, just like returning boss by -three, just like returning boss by taking a four to Maithili, here I will pass one, the one with C will not go left and one will pass, but there will be a loss, wrap Abe inside the box and apply oil in CLF. These are the people of the app, I will become the people who kill this block and the people. Written Annie from here and return and after returning we reached back. I used to press the right key to press the ok key and the data reached on G with this only. Meaning, here you will do the paint factory and then finally you will do the battery. Now you reach near for - do the battery. Now you reach near for - do the battery. Now you reach near for - 40, it is exactly the same, it went left 08830, meaning it did not work, but my aunt T0 Vijay serials go to zero, I appoint this one. And from here I take the factor and there was no chance of getting hurt, that means there was no call under me, so you came back from here to Araria, now near zero for - 5 means how much data is there - one near zero for - 5 means how much data is there - one near zero for - 5 means how much data is there - one and block demonetization, in this I have a butt like These are small and can be returned from there. Let's find out. I have found all my do nots. If you look carefully, you will definitely see this note at a distance of four. Sanchet and detergent, which ones are 1234, all these don'ts, 1234, this note 1234. This note is 1234 Not 1234 This one above is four distant but all these notes were at a distance of four distances like this I got all the notes Now this was the solution in which we had taken groups behind the actress that we had to remove this paste. Some boys can be removed, if you understand any solution then it became very easy for us to remove the space because when I was taking out the route 9 pass, well, while taking out the routes, we had painted it, shouldn't I? And he will always extract the pass code, how foreign is rough, then with this same question machine, I will make my fruit note pass travel by doing anything to me, if you not only get the pass passed correctly then the work will be done for us, let's see how it will happen or you will get inside it. Start traveling, look from Jio, I am on the left of zero and try to find the data here, I will not get it till I ask you, I will return - I will not get it till I ask you, I will return - I will not get it till I ask you, I will return - I will keep thinking, data is not found, figure return - time, if data is found then ignore and return - time, if data is found then ignore and return - time, if data is found then ignore and return negative. If the data is not received then they will return negative, something like this: If the then they will return negative, something like this: If the then they will return negative, something like this: If the data is not received, then they will say that if the data is received, if they have not received it yet, then they will give - Okay, received it yet, then they will give - Okay, received it yet, then they will give - Okay, one has gone to zero balance, is there a pass, or has it gone to the last one, in the passbook collection. DJ pass went to DLF, either don't bring it to the country - work has not been removed, either don't bring it to the country - work has not been removed, ok, went to AP in difficulty, in the same left, did not get salary from schools till Type-2, then they should go - not get salary from schools till Type-2, then they should go - not get salary from schools till Type-2, then they should go - 110 done, BA passed - return. What happened is that data is 110 done, BA passed - return. What happened is that data is 110 done, BA passed - return. What happened is that data is not found then after returning it with the help of a person who came from here to minus one - I have made it with the help of a person who came from here to minus one - I have made it with the help of a person who came from here to minus one - I have made it in my night and put it near this one as it reaches to the left side, one thing is always made from all over the country that you 0k You have gone to the torch light, then you are going to the right of A, I have told you, I have gone to C is going to the left, I am going to the left of the app, I am going to the left of the match, or even X's. In the end, the exclusive pattern was not found. If your data is not found in the tax rate, then it will turn into a bird. Twitter - Data on one was not completely received from you. There Twitter - Data on one was not completely received from you. There is no data in HP laptop. There was no left right in Mathura. Twitter is not there. It means here. Survey completed, taken and returned, there is no time data for the app, if there is no data in the right, then it is completely returned from here too, it is good, the app is done, then right clicked and started running, now left or right, made a call like left or right. I applied it when I reached near the eyes electric and I applied it when I reached near the jail where I got the data. Okay on which Aati I got late. Now just set the next actress on low with this. Is n't it a root toe note thing? I got this jain5 ch00t note, I can't make my own while doing backstreet, how when I come to J, I don't call, when I come to G, I don't call, how much is the value, one verification, another consistent or that's why I will call the don inside, I will call a tree notification, check how much I pass the note of Jain and Sorry J and how much will we pass it first, here we will pass whatever China is world famous. This is for the cuff and passed it for electricity - for the cuff and passed it for electricity - for the cuff and passed it for electricity - I passed it for zero, I am fine - Jio I passed it for zero, I am fine - Jio I passed it for zero, I am fine - Jio phone, let me make it properly in some time, now the pattern will be visible, here we will pass the bright note - G Road distance I want to bright note - G Road distance I want to bright note - G Road distance I want to solve the match for Oh I want to fold it K - zero distance from I want to fold it if there is a I want to fold it K - zero distance from I want to fold it if there is a I want to fold it K - zero distance from I want to fold it if there is a tap inside the block notes then okay Jaiswal up that Don's function knows how to do its job well Want to rely on that's why he created It was earlier that it is okay, pass it absolutely right and I will return the juice from here as if I told how far away my parents are from me, that is, how far away the note to which I am giving information is from me, then genital. Karega and saw it closed like a mirror, so how did I understand that brother, data has been found on my left side, that is why there has been a non-negative return and why there has been a non-negative return and why there has been a non-negative return and fat where I got the data, how far away is the person whom I was looking for, a fearless distance from me. It means that till date you have used 10 top distances, now brother, how much should I look for, I will call, I will not call, I will note that the one who is going to do not call, here he will do I's minus one and in this the block will be made of job. Because the answer has come from my left side, I will block note you are the light, I will block note the left side of I. Who is on the left here, I will block note this one here, that is why I have blocked this note here. Turned to my left, overlocked and called K Don, don't do your work right back, he gave his address, D O W will fight, then from here there are buttons, now because I know that brother, the army, the note I wanted to find was there. If I do n't want a distance of one meter below me, then it means that my friend will not have a booster for how much. If my distance is one meter above me, then that actual note from the parents, how much medicine has been given, two introducers, then whatever my value or return of surplus fund. Do it here, I returned it to you that my clock was stopped but that note was far away from me, then till what time will you do it from my foot, 2 minutes and the distance has gone away, now as you saw and not active from the right, it means If data has been found in the note, then it will say that data has not been found anywhere in the note, that data is not two distances away from me, that is, I have used this top two distance from that note to reach here, now what is the remaining limit for distance saving? K - See the sarcasm here - if you were saving? K - See the sarcasm here - if you were saving? K - See the sarcasm here - if you were writing to hee, then there will be four passes here, if here I will pass that - to pass the distance alarm clock note, that - to pass the distance alarm clock note, that - to pass the distance alarm clock note, here we have passed the Africa right hand craft means hee, okay. He will print it out in 2 minutes and then print it on a board and put it, how much will he say to C, if the distance is left, Snowdon Road is far, then how much distance is it from my friend, it is 3 minutes. As soon as he found out, it is right. The answer has come from the left, it means this - three letter distance, go down and - three letter distance, go down and - three letter distance, go down and print two people, how to make a block note, in this, the app will become Apple Cider, Reebok Note on the left side, because I can't go towards the left side. I can't go there because that answer has come so I wrote one note of the block note here look carefully the episodes in C were revolting and for - that means I revolting and for - that means I revolting and for - that means I passed the theater and called K don Okay, absolutely perfect, now what answer will C give to A? C will say, look C is the distance from A to Z, so how much will it cost for 3, this will be in the chart and will not be placed on its right, once you meet, you will have to place it somewhere else. There is no need, now you have reached and after taking the prior distance, here this note will become oil-4 and block note, this note will become oil-4 and block note, this note will become oil-4 and block note, put C and C inside it, we have made arrangements in it, the victim will finally return to ISRO, how much distance to Europe? Five, look at how far away it is from zero. Five is YouTube distance away. That's a different thing. When I call here for zero, then K-Feature negative number one zero, then K-Feature negative number one zero, then K-Feature negative number one neck return will be filled. So we had the concept of rupee note in active. We were fine with that. Had to understand the method in which he does it, then if you know how to pay attention to the routes, then now in the video I will solve this problem very easily, without any express his presence of agriculture, leave it like this, request. Apart from this, I have not given any actress, okay, so look here, I will break it down by the animals of A and 132 and show you my traffic, that is only the trident target of A in the distance of A, how much will it give, that is, I will have to tell and also I There is one laptop, of all the things we have in the past, but look which one is simple, if people get up, you do not think about anything, return - 2 - means that the thing is not think about anything, return - 2 - means that the thing is not think about anything, return - 2 - means that the thing is not found, the target is one in the fruit bull, in which it means that if the thing is found, then Come here, what reward function should I give him, the password is on the bread, blur it with me and print the things. Okay, so I take this 20 rupees, you don't steal it from me, go and print the things. If you create an inbox, then how much will it contain inside it, this will only remain that how much will be left here for the mic which is basically 250 educational and energy and drop people used to pass it to their heads, how much will they return from here and want to tell that I How far am I from my parents? I am only one Anuj distance away from me. Immediately, if I am from my parents, those who are on the left or right side, then make a mixture, then it is okay, then we can do the left recharge. This is from the left. The aspects of the left distance were, how much is the distance, 200, I made a call at the distance, it is near Garbha and left and some target SIM will be near, Hussain will be near, the scene of the answer will talk, now loot a tent, now if you put a phone here, then it has happened. A Right G which will be done Fasting O You can see the value is A Beautiful to - World Bank It means A Beautiful to - World Bank It means A Beautiful to - World Bank It means Positive What does it mean I got one thing in the left Magistrate I wanted to stop I got it in the left That don't call me While doing this, what should be passed will be correct, I know that I have got my refrigerator on the left, that is, all the methods on the left, I have to make a block note, it is okay - we will do something, see how much to do and - we will do something, see how much to do and - we will do something, see how much to do and here is the total net for making the block note. The blouse will be made and the answer will be love and when the return is cut, I will go to deposit the return. I will check it from here and also check how much I have to return. Look, now I know you must have got the reply late, like the return of the zener diode. I had done that, this was the life there, I wanted to tell that how far is it from I to I, here is one needle distance upside down, so how many units of distance have I done in the committee, as if I were traveling, now when I came back If I go back down, back, when I came back If I go back down, how many more minutes can I go down, if one of these distances has already been done, then save - that meter distance, then save - that meter distance, then save - that meter distance, so basically whatever will be returned to you, that data will be here - then give a call so that data will be here - then give a call so that data will be here - then give a call so that when Call this - left side and here you will when Call this - left side and here you will return something like this plus one love distance from. See I know this much that if I is 19 distance away then this is how much tow distance from the app. Two units so this is one plus one. We will return here, so if there is a J2 rate officer from the app, how much distance should I find from him, because he is a child of FD, then it means safe from here, if it was 2, then it will be only 3 or A+B+, we will do the hunting A+B+, we will do the hunting A+B+, we will do the hunting from here. You should apply these to someone, should you find a diet or desi, I applied a try distance tilak on them that - Cardiff and here at the party and that - Cardiff and here at the party and that - Cardiff and here at the party and here while making a call, now half of the roots have been applied with rotting hormone and if you agree to me, then get the answer from the left now. I need to eliminate it negatively in the galley. This means that he is doing that particular activity only. Mukesh does not do it nor is he doing light Mukesh. So I should do solitaire at this time when will I get my answer. I will get my answer here when Will put us in this tense, my list of fiction programming head posts that fees will be passed in the tenses, will we pass the target or will we pass, have passed inside, submit, it is from here, okay, let's run it and see, this is a loot compilation. It is said that if we first do the mud then I have made a spelling mistake that see and Income Tax Inspector return value - Income Tax Inspector return value - Income Tax Inspector return value - wall, its return will not come soon, patient 162 jeweler will come, for this, an Indian sa is absolutely perfect, he will see it once. Papa, we have a code for 'Papa', so we have a code for 'Papa', so we have a code for 'Papa', so what did we see on this, we will give the record here. Apart from this, no Express News said that do not do this account, this asked you to know, if I was told to just print the data and give it to me, just friend me and see. So if it does not support me, then this paste did not reach me, then I was asked to remove this space, after removing this paste, I did not worry about this particular answer, meaning this is the particular answer name, is there any extra for refilling? Just yes, worry about space representative. By accessing the skill toe, you are not using it, apart from this, no actress is using it, so to solve this problem, the request to us was limited to this skill, apart from this, no actress was using it, whereas before this, we had learned the method in the ribbon which you have been using since that time. Had taught us, we have put extra space inside it, so this is the optimized version of the same chord, we are solving it without using any extra space. Okay, now let's talk here, if we consider the time complexity of it, I just kept it as In the meantime, Yogi is at midwicket, inside that boy, my bittu boss, what could be the turn I wanted to find? Who took my voice to the bus? Could it be that the turn I wanted to find is on the right side of me. Press enter text right on the most is the most right most notable president and here I just how many passes that I passed the infrared she can't be lower now painter from every items I did the whole journey before I used to reach here like I here I reach here then I call don from here then after this you turn on the game from this place then from here you will call it don't call then from this place you will call it aate ki jaan then from this place you will call don't call then you will call this note You spent all your life in finding it, you must have applied benefit and when you are doing technical, you have traveled the volumes again to all the ends, then you have taken total to one time, then time quantity, how many b21 are you also, if I talk about it in the video. This will go there, how much space is taken, record the space of frequent inside it, if you do a Facebook account, then we turned the oven express witch, the space is not applicable at many places, they say, let's replace your red in the tips, apart from this, if you do not do exercise, then I request on this. If I select it then I did not do any actress thing other than this, that is my one miss space, okay, this is the solution in which we have just converted one gar meaning that salary was terrible 3G, we have converted it in some way, now inside the convert barricading method, this The solution that will become the base of the problems coming ahead of me means Bhagya Zee TV problems are going to come, all those problems are going to become problem subs of this problem, so I consider you a very good one, like now whatever problems have come in the future which is constipation. To solve all those problems, you should always write a route note letter. Okay, write it and dry land it because I have understood how to develop the Note 5 on this route. SIM has to be inserted in the step. I think we have understood that how can we smoke a cigarette in this party. Hey, if you also know how to smoke a cigarette, then there will be no problem. No, there will be no problem, rest of us. The problem is just this face, we will draw it, we will deal with the gestures, when the time comes to enter the code, will we set it to the consistent maximum or not? If you can solve this problem for this piece, then what do you have to do? Now you have two tasks. What is left is to first socialize the tents properly, dry the color, understand that we are also with your Maderna, how he behaves, after that, without the hair pack, it will also help like this, if I remove this face, then the starch that I have developed is In what way are you helping me, okay, and should I get the return time from here, am I getting western? Number one minus one means the thing was not found, I wanted to find the magistrate, like if it is from the same left, then it means That I could not find the left side but if the speaker wrote to me on the left something positive values ​​like one to positive values ​​like one to positive values ​​like one to three western and yes then what does it mean if it is 12th what does it mean it wants to say that in Britain and here the three Do it useless? What he wants to tell is that J note is 3 distance away from me and I had found the note within my referee and that note is three distance away from me, so how many notes below me can I ask for? Who are those like I would have used three units of distance to eat Sita, now I would have used three units of distance from the scene - whatever is the value of 3G I would have used three units of distance from the scene - whatever is the value of 3G I would have used three units of distance from the scene - whatever is the value of 3G that I would have gone down three units of Edison and I will print it to the people and how do I make a block note here But the app because the app is my fear left side and I have got the answer from the left then why would I go from C to left, I was thinking that first I got secure from the app, why should I go towards the film Saif, I don't have to go there, so I blocked it. This was the concept of this whole code. If you are using this problem then run it properly and wait for further videos. Now you will get ₹ 50 by producing which solution will you solve? ₹ 50 by producing which solution will you solve? ₹ 50 by producing which solution will you solve? Okay, if you like the video then please watch this video. Don't forget to like and also if you like the quality of our channel and have subscribed to the channel and have come again with us for the first time then tell it to your friends madam tell your friends for two days at the very least I told you good luck A simple concept, who knows, we will get convinced in this matter because the video which was running on this very good internet of ours, mother is providing freenum for so many hours, still no one means that we will be able to pass so much, no, they are also considered as eunuchs. Even then it will be increased when you people help us, when you people share this video as much as possible, tell as many people as possible about this video, only then we will sleep with love, even then people will know about the content as much as possible. And share it, like the video, what happens by pressing like, YouTube will recommend it to other people too, if you press a like is a small button, press it again, which will yeast like our video. Like this video and increase the number of likes on this YouTube channel and we will start recommending it again. If you comment, it will be even better friend, tell us by commenting, we mean interest, tell us what you like in the video and what you don't like. As for whether this video was made by Awasthi or it was not meant to be made at all, tell us about it, please provide some information to the victims, comment, like, subscribe, share as much as you can, okay, my tab is last, Agniveer, if you want to wait. It's okay to share this video, see you in the next video.
All Nodes Distance K in Binary Tree
sum-of-distances-in-tree
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **Output:** \[7,4,1\] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. **Example 2:** **Input:** root = \[1\], target = 1, k = 3 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 500]`. * `0 <= Node.val <= 500` * All the values `Node.val` are **unique**. * `target` is the value of one of the nodes in the tree. * `0 <= k <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Graph
Hard
1021,2175
1,760
So today's problem is minimum limit of balls in bag, so basically what is that we have a bag in which there are balls of some type meaning something like this bag has eight balls in this bag, four balls are ok in this bag, what can we do? What can we do in one step? We can divide the number of balls by number of balls and divide it into four. Okay, it means, it can be any number of balls, we can make a new ball by taking any number of balls. You can make a bag in one step, that is, if you take a ball and make a new bag, then now the maximum number of balls in a bag has been consumed, which was earlier eight, okay, it was like this, so this number we have to make it as much as the minimum possible. What we have to do is to minimize, that is, we have to minimize the maximum number of balls in the bag, if we have a fixed number of steps given, four for example, if we have four steps given, then how much can we reduce. Eight, I divided it by two, okay, four. And here also there are four, it took one step, okay, after that, I have reduced these four to two, I have also reduced this four to two, okay, right, I have reduced this four to two, so how many steps have we completed in all three steps? Our total steps are done, we have four, so the minimum we can do in four steps is two, okay, then in this video I will tell you the general meaning of the concept, what is the concept, okay, in the next video, I will perform draw run problem. Okay, so to do this problem, we will take binary search. Okay, let me tell you the main idea of ​​binary search. take binary search. Okay, let me tell you the main idea of ​​binary search. Suppose in fixed number of steps. A suppose one is a mid which is one which means mid is a number which is possible to achieve. This means that by taking a or less steps of division, we can achieve the goal. This means that we will keep one l, a number which we know can be achieved, this is the number of steps. Okay, this is This much can be achieved in A number of steps or means AA and less than this number of steps. And we will take one which is the least possible meaning it cannot be less than this because We always have to make positive numbers by dividing, it is sensible that how much can we reduce it to maximum, if we divide it into seven different pieces, then the maximum number which has become the maximum number, the assisting one has become one, then it means that we can do only this, what more? If we can do it then one will be the minimum number then this L. We will know that L can do whatever it is, we can do it 100% but can do whatever it is, we can do it 100% but can do whatever it is, we can do it 100% but L we don't know that means the best possible scenario but we will see that means to what extent we can do it. Okay, so what we do is we'll take a mid, which is what it basically suggests, take it as A, okay, take it as L, take it as A, okay, so take it as L. Lo, we will take the middle, we will take the mud, okay, so basically this is the floor, basically, the floor that will be obtained by doing the batu will be the same. It is okay as it generally happens, if we computerize it, then generally the floor value will come. Same thing comes, okay then we will take mid, okay mid, if it is possible, that means m mid is such a value which is impossible in a and less steps, okay, then what will be the meaning that we have got the minimum which we want, okay then. This minimum is found, now what will we do? Now this means that this is a valid answer, so what will we do, we will move and shift aa here and again we will generate a new mid here and here, we will generate a new mid here and understand. What do we mean by this and if supposing mid exists means mid we say mid is not possible, we checked mid and if mid is not possible then what will we do in that scenario if mid is not possible. If it is then anything less than mid will not be possible because if it means three means like it is a supposition three, if three slashes cannot be made then it is okay then obviously less than that cannot be made even less than that cannot be made because in less than that there is and. More divisions will help in reducing it. More divisions will be fine. This means that if I do a dry run in one go, you will know that if three is not possible, then its value will also be less in this particular problem scenario. If it is not possible then what will we do with L? We mean basically this is not possible from here till one. If Mid does not satisfy then what will we do with L? We will shift L to mid plus and okay meaning if mid is this. Then we will do it when the meaning is negative in the middle or it is not possible in the middle. If it is possible in the middle, like I told earlier, then whatever arc is in it, we will shift it to the middle. Okay, so this is a rough idea which is basically the idea of ​​binary. middle. Okay, so this is a rough idea which is basically the idea of ​​binary. middle. Okay, so this is a rough idea which is basically the idea of ​​binary. I told and now coming next that what is the middle in the concept, how will we check whether the middle will satisfy or not, so see the thing, what do you know that the proposal is 10 is a number, okay now we need to know the number 10. The maximum we have to do is three, okay what is the maximum, by dividing this, the maximum value in the array that will be formed will be th, so see how many times it is in 10, like this is 10, so many threes have come in 10, one th has come, two th have come. Three th has come, okay and here one has come, then if I want to make the maximum number three in 10, then obviously look at 10, how many times three comes in 10, three b comes in 10, okay and 10 divided by 3 is also the same. That is, how many times ' divided by 3 is also the same. That is, how many times ' divided by 3 is also the same. That is, how many times ' th' comes in 10, so there will be 3 point something, so th' comes in 10, so there will be 3 point something, so th' comes in 10, so there will be 3 point something, so basically 'th' is the maximum whole number, basically 'th' is the maximum whole number, basically 'th' is the maximum whole number, three is the meaning of dictionary and the rest is a reminder, if 'th' three is the meaning of dictionary and the rest is a reminder, if 'th' three is the meaning of dictionary and the rest is a reminder, if 'th' comes three times, then what is the basic thing, by doing 10/3 comes three times, then what is the basic thing, by doing 10/3 comes three times, then what is the basic thing, by doing 10/3 we get How many number of divisions will we do? Well, we will divide one here, so if it is a stick of 10 and it will be divided in half, okay by doing three operations, that is, by dividing 10 by 3. Okay, and then the meaning is which is and this is what it means, the maximum value in this will be converted into th, okay, but if there is a case of one in this, we have to see that if the supposition means we have nine given and The maximum number which should be converted is divisible by it, so what will happen to us in that case, if I said 9/3 answer then it was if I said 9/3 answer then it was if I said 9/3 answer then it was wrong because it is the last cut which has to be made in the last means. There is no need to cut this one, we can make two cuts here, one cut here, okay, so to reduce that value, we will reduce it to 9-1/2, which means reduce it to 9-1/2, which means reduce it to 9-1/2, which means three. Do you understand what I mean? Basically, we are bringing the answer, here we are doing the same, that is, to convert it to two instead of three, we subtract it from whatever value it is and then divide it. Whatever value we need is fine in it, so what happens in this case is that if means if like this is the divisible part also gives the correct answer and if there is a little one more than the divisible, okay there is one more then. Then like 10 is 10/3 then more then. Then like 10 is 10/3 then more then. Then like 10 is 10/3 then obviously if it is 10 then there will be a little extension here too so this cut will have to be made, okay then what will happen will be 9/3 = then what will happen will be 9/3 = then what will happen will be 9/3 = 3 which is correct which is coming here like this Just think about the moment when what I have said is that when it is divisible, in that case, by taking that corner case, we can see that if the supposition is a stick of length n, then if n - 1 by x we Then then if n - 1 by x we Then then if n - 1 by x we Then if we want maximum x min maximum element size K we can see that this formula is valid okay I gave this proof of that okay so this is a this is an into now how to solve this problem okay that number of if you want to convert a Number n into piece true the maximum number is In Which I Explain The Main Concept I Explain About Binary Search And How Does This Formula Come About Okay In The Next Part I Will Be Doing Dry Run Of The Problem A Okay So Or See You In The Next Video Thank You
Minimum Limit of Balls in a Bag
check-array-formation-through-concatenation
You are given an integer array `nums` where the `ith` bag contains `nums[i]` balls. You are also given an integer `maxOperations`. You can perform the following operation at most `maxOperations` times: * Take any bag of balls and divide it into two new bags with a **positive** number of balls. * For example, a bag of `5` balls can become two new bags of `1` and `4` balls, or two new bags of `2` and `3` balls. Your penalty is the **maximum** number of balls in a bag. You want to **minimize** your penalty after the operations. Return _the minimum possible penalty after performing the operations_. **Example 1:** **Input:** nums = \[9\], maxOperations = 2 **Output:** 3 **Explanation:** - Divide the bag with 9 balls into two bags of sizes 6 and 3. \[**9**\] -> \[6,3\]. - Divide the bag with 6 balls into two bags of sizes 3 and 3. \[**6**,3\] -> \[3,3,3\]. The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. **Example 2:** **Input:** nums = \[2,4,8,2\], maxOperations = 4 **Output:** 2 **Explanation:** - Divide the bag with 8 balls into two bags of sizes 4 and 4. \[2,4,**8**,2\] -> \[2,4,4,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,**4**,4,4,2\] -> \[2,2,2,4,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,**4**,4,2\] -> \[2,2,2,2,2,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,2,2,**4**,2\] -> \[2,2,2,2,2,2,2,2\]. The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2. **Constraints:** * `1 <= nums.length <= 105` * `1 <= maxOperations, nums[i] <= 109`
Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively
Array,Hash Table
Easy
null
949
welcome to september's lego challenge yesterday's problem was largest time for given digits given an array of four digits returned the largest 24 hour time that can be made the smallest 24 hour time is zero and the largest is 23.59 so zero and the largest is 23.59 so zero and the largest is 23.59 so that's like army time starting from zero time is larger if it has elapsed since midnight so that's obvious return the answer as a string if no valid time can be made then return an empty string so we're given four digits and we're always going to be given four digits and these digits will always be between zero and nine so seeing that being the case there's a couple ways that we could kind of approach this but really since there's only four numbers it might be just better to create all the permutations using some libraries and then check to see which ones are valid times and then simply return the max1 out of those valid times so that's what i'm going to do i'm going to go with the three step approach first we're going to find all permutations then we will append them to all append all valid times um using the daytime library and then just return the max out of all of these times so that's a little bit of cheating but um for this problem i think that's just the best way to do it so let's start with getting all the permutations to do that i will use the inner tools use permutations passing the a and the max length which is going to be four right so this is going to be all the permutations for our four digits i'm going to make them to a list so that i could iterate through them um since it's like a it's a generated object i believe and what we'll do is we'll just say for a b c d in perm we're going to cram to a string and i will just use the string format method i'll pass in four parameters with this semicolon in the middle and i'll use the format i'll say just pass in a b c d so now it's going to have a string representation of our digits and now we need to check to see if it's a valid time or not right and to do that i can use the daytime tool datetime it's i believe it's strip time and what i'll do is pass in our temp string with the format of what it will be hours and minutes but this would air out it's going to create an exception if it's not valid so we'll have to do is say okay try this and if we get an exception just catch that and we'll just continue instead if we're able to see that it is a valid time let's append it to some sort of temporary output i'll just call that output and we will append our string there let's initialize that output up here so after this it should give us all our valve times so once that's done we can just return the max of it and the reason i can do that is um basically it converts into a string and we know that the highest number is going to be the highest time right so we don't need to like do any funky conversions there so let's make sure this works of course line 10 nope not exceptions except it looks like that's working let's go and submit it oh okay so if it's empty we need to make sure to return an empty string right so if not output then return an empty string so there we go accept it yeah so this um kind of seems like a brute force approach but it does work it does get accepted i was trying to think of ways to use recursion and backtracking but it really ended up becoming more work than it was really worth so i think this is fine there's definitely some faster ways to do it but hopefully this is good enough so thanks for watching my channel and remember do not trust me i know nothing
Largest Time for Given Digits
cat-and-mouse
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
1727
229
hello um recording the rest version of the majority element version two uh with that let's begin the question I already have the solution posted in Python so if you need an explanation please take a look at that but we're going to be doing the same thing here so essentially we need um we need to have we need to data struct es that we are not going to implement from scratch which is the hash set and the hash map um and I believe this is Hash set and hash map um so we're going to be using these two collections we're going to start with the same approach let mutable uh count is equal to Hash set new oops new and then the same thing but this is going to be the result and this is going to be a hash map and this is a hash set perfect then we need a threshold let threshold is equal to nums Len / 3 I'm going to cast this to nums Len / 3 I'm going to cast this to nums Len / 3 I'm going to cast this as an unsigned 32bit integer so that it's not float then for let's see for n in nums essentially we're going to be going through it and figuring out if initially count contains uh nums if so then we increment nums by one if not we set it to one um I don't know if hashmap has a default um like it does in Python but let's go with this one so far match count get and we need the to get the num uh in the case that it returns Su uh let's call it occurrence then we're simply going to count insert at a specific n the value occurrence + specific n the value occurrence + specific n the value occurrence + one uh in the case where none meaning that it's not found we're going to do absolutely nothing um that should take care of incrementing the count and getting it to the right place uh now let's match on the count get n to figure out if we have found an element that is um oh I was wrong here count insert n and one there we go uh here we're doing something very similar also oops also occurrence uh but this time if there is some occurrence I want to check uh if the threshold is above if the occurrence is above the threshold so if um let's see our currence is greater than thre threshold then I'm going to Simply uh res insert the number n or the letter no the number n and in the case where that does not exist where we haven't even found anything then we do simply this cool then at the end we want to uh we want to convert this count to a um to a vector and I'm pretty sure we can do res um to it collect something like this um with that let's see uh with that we have the majority element we have the count uh set up as a new we have a new hashmap we have a new hash Set uh we have the threshold we want to match the account um result by either occurrence and insert it in this case where there's is already an element there and insert one in the case where there's none um then we want to match on the return value of get one more time and see that if we get some result in this option um then we want to check if the occurrence um okay actually let's see what is occurrence is this going to be it's going to be a number but is this occurrence a um what type is this actually I don't know well I mean let's see if we get the correct value so no um mismatched type and it's saying that oops that's what it was no returning prematurely uh match actually match is still expressions and so uh expressions are have to be capped with a semicolon in the case where they are not returning semicolons and there's a mismatched type here it's claiming that a currence is a reference so urren is a reference so let's destructure it um hopefully that would work or get the value at the pointer and that's it awesome yep so there's a there was a little hiccup there but uh pretty much did its job I'm not going to go into this because this is there's no way yeah I'm just going to be going with the standard implementation um cool thank you for watching bye
Majority Element II
majority-element-ii
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** \[3\] **Example 2:** **Input:** nums = \[1\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1,2\] **Output:** \[1,2\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow up:** Could you solve the problem in linear time and in `O(1)` space?
How many majority elements could it possibly have? Do you have a better hint? Suggest it!
Array,Hash Table,Sorting,Counting
Medium
169,1102
725
Er ki aur humko hai karna hai ks possible no part have size di by one and one ba more than one ok is let two some parts b in this it is saying that whatever number of parts in this there are any parts in this The difference of should not be more than one OK like two or two cannot be more than two The parts should be in order of one The input list The parts coming in size greater It has been It has been divided into parts, so this is the first part, so look at the juice of these two, but what did you say, Moran or Allow, Nahi, Ala, so this is the second part, according to this, there is a break in the photo, so it is covered here. I want to go to Apple, see the explanation, let's see the explanation. Okay, so let's take the first example. The first example is given in this Aa Natu Na Late Ho Tha, Er is given in this [ Tha, Er is given in this [ Tha, Er is given in this Nat 8 Na A 10 Okay and The value of K is given in this, what is its output tooth fur 5 s to 8 na and then 10 ok look at this in the question one thing which is very clear is given that yes it is given in this that we have to break it like this That is, all the parts are either equal, okay, they can be equal, okay, or these are the two parts that are supposed to be, so in the first part, there will be a difference of only one, okay, it can be greater, it can be bigger. It can be true, it can be, it can also be, it can be, we can find out like this, how to disassemble it, separate it, which will be made and will become our set, how will we do it without gold, how will we do it, we will do it without gold. I can do the given one, yes, I will put this one first, I will try to move it after making it, or I will not do anything like this, I will make a plan like this, I have found out how to break the next simple thing. He will directly know how we will break the bank, we will make it like this and store it and then see what we are doing and after dividing it, see what, so what do we find out, what element will be formed, one element will be left and the solution will be But what would have happened is that the elements would have become sets of what would have happened in it, elements would have been created or if we would have added them then these would have become sets of four, we would store it in the array and give its value and keep breaking in this coding step. There is no problem in this method, okay and in this further you know how to put co in part, that will be for us, let's see the solution, look at its code, so in this we have first created a function to find the length, normally just take out the length. We will call this and divide the world into how many parts we can divide it into. We will make a set for Holi, a bigger part will be given, its number will come, what will we do? After making an array, we will enter the value of the parts After this All the extra parts which will not have any difference can be given there but all the remaining parts are part of the tax. What to do now the main part comes like tax, like its return type, give a web page here. J is declared and while we are checking that as long as J is smaller than our k so here the size of J is taken to be zero then the value of the array of J will come to the array of zero. The list head is pointing to the head one and then the current one is also pointing to the head. So now what to do here is to do a pointer in this case. What are the previous pointers doing to point to the current one. Next move the size. We are going to decrease here, whatever will happen in this, in a way, by doing a preview, we will point to the list and click on Y and the result of J came, we will store the result and what will we do now? Q. If there is no tap, then its Tap Next and this question will continue: Should I store everything?
Split Linked List in Parts
split-linked-list-in-parts
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return _an array of the_ `k` _parts_. **Example 1:** **Input:** head = \[1,2,3\], k = 5 **Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\] **Explanation:** The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null. The last element output\[4\] is null, but its string representation as a ListNode is \[\]. **Example 2:** **Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3 **Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\] **Explanation:** The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. **Constraints:** * The number of nodes in the list is in the range `[0, 1000]`. * `0 <= Node.val <= 1000` * `1 <= k <= 50`
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
Linked List
Medium
61,328
496
hello everyone welcome back to another Elite code problem today we're going to be doing problem 496 next greater element one and this is an easy problem technically but we're going to focus on the optimal solution for this problem so that one won't be so easy that's more like a medium or maybe a little bit tougher and so the problem is the next greater element of some element X in an array is the first greater integer element that is to the right of X in the same array you're given two distinct integer arrays nums one and nums two where nums one is a subset of nums two and you are trying to find in each number of nums one you're trying to find where that number is in nums two and what's the first next greater element so for number four we could see it's right here and there is no next greater element because everything to the right is smaller than for number one it's over here and the first next generator element would be three and for number two there's nothing to the right so that's also invalid and if there is no next greater element We cannot put minus one so I think I would assume that for the easy solution what would that be so that's probably going to be something like the brute force and so for a Brute Force what's the most Brute Force we can do well we can take for every element in numbers one we can just find where is it in nums two so we just say for every number in here Loop through this as soon as we find it keep going to the right until we find a greater element if we do find it then put that in and if we didn't find it then return negative one and the problem is the time complexity of this is going to be N squared because we're going to have to go through this array and then we're going to have a nested loop with this array and so it's asking could you find a solution with Big O nums one lengths plus Big O of nums two length and so the solution is going to be a little bit trickier it's asking us to not have an acid Loop and how would we do this in another way and so another way to do this would be let's just think about it for a second so what we want to do is we want to find the index of each one of these numbers in this Loop now ideally instead of searching through the entire Loop we would want to be able to go to the number directly so that would be the first thing we would want to do so how would we do that like if we have this 4 we'd want to be like okay well what's the index well what we could do is we could have a dictionary and so for each of the numbers in here we can so let's just say this is one three four two we can Loop through all of these numbers and we can just store so we can store key equals number equals value which is the index and so it's also telling us that all of these numbers are unique so we don't have to worry about having a value of multiple indices that'll never happen so we could go through this Loop and then we could just keep track of every number and every index and then that way when we call for something like four we could say oh yeah okay well we have the index of four so we can jump two directly so that solves one issue where we just have to Loop through this one time and we store every index now the other issue is to get the neck to get the greatest number they're the next greatest number even if we know where this is for example this 4 is well what if we don't have a greatest number like let's say we just have some huge list like this and let's say this is you know like a thousand elements and it just goes 1000 999 998 997 and so on and so even if we know where we're at like let's say we can jump here directly we'll Define the next greatest number every time we get to a number we're going to have to Loop to the very end so this would still be N squared like if we have a bunch of numbers here we're going to have to Loop to the very end so how do we solve this issue so this would be 998 but you get one point this would be 997 and so on and so a common problem you want to recognize is when you're trying to find the next greatest element or the first element there's a couple problems only code like this I think there's like daily temperatures and some other ones so when you're trying to find the first element greater than the element we are looking at what we're going to want to do is we're going to want to have a stack and so let's demonstrate this so let's say we have these numbers one three four two again so what we're going to do is we're going to want to have a stack so we have a stack that's let's just say it's empty and we're going to go through all of these elements and what we're going to do is if a stack is empty we just pull push the element in so let's say and the way we're also going to figure out what index to like let's say we have an element in here and then we find an element greater well how do we know what was the index of the element that we were looking at so we're going to want to store something like this or we're going to want to store one and the index of one so that would be zero and so on so we would store one zero three one four two and so on and then once we find an element that's greater than it we can always just go back to the index that we were at so let's just walk through this for this example so we're going to Loop through this entire array and we're going to put these numbers in the stack if it's empty and if it's not we're going to check is this number that we're at greater than things that are in here so let's see what that would look like so our stack is empty so our first iteration we're just going to put in one zero here now we so we were at here now we are here so is 3 greater than and our stack the way we're going to do this is our stack should always be in decreasing order because if it's increasing order that means that the number to the right of this number like if there's a 3 here it's greater than the one so we can just pop the one so let's see what that would look like so we can just have something like this where when we're at our element we can just say while current element is greater than stack minus one which is the last element in the stack so in this case it is so we're at three it's greater than one okay well now that we know that 3 is the next greatest element of one we don't really need this one so we're going to pop off this one and we're going to update this index to 3. so we're going to pop off this one and then the stack is empty now so we're going to put in three and the index of three is one okay now we're at four we're going to do the same thing we're going to check from the back of the stack is 4 greater than the last element in the stack yes it is so we're going to pop it again then we're going to put 4 in the stack along with its index and then our last element is two so we're going to say okay well is 2 greater than 4 no it's not so if we can't pop anything from the stack we're just going to pen to the end of the stack so 4 2 and then this is going to be 2 and then the index of two which is three so you can see the stack that we end up with our stack is always going to be decreasing because anytime we have something bigger we're going to be popping from the end and there's another thing we need by the way so we have the numbers one we have a nums two but we also need so it's at we need something to keep of the next greater element for all of these values so we can Loop through this numbs too and we can actually do this in one's Loop so let's write this down so Loop through nums two save every number and index in a dictionary so that's this store Key equals number value equals index so we need to save every number every index in a dictionary then we use our stack to update the next greatest elements and we need to find so this is what we need to update these next greatest elements or where are we going to store these so what we're actually going to do is we're going to make a new array and we're going to have it be the same length as nums two and we're just going to initialize every element to minus one and the nice thing about this is if we didn't update the next greatest element for some value like for here we never updated the next greatest element of four and we never updated the next greatest element of two if we never updated them they're going to be default minus one so that'll take care of that but we did update one to B3 so index 0 is going to be three so this would be three and then we also updated index one to be four so this would be four and so these are the next greatest elements and they're going to be at the exact same index as these so like if we want to know what's the next greatest element of one we just say Okay Hey where's one in our dictionary it's at index zero okay so the next greatest element of one is going to be at the same index because they're the same lengths the next greatest element of 1 is going to be 3. and so for this output let's say for 4 1 2 okay we're going to say okay well where's four is that index two so at index two we're at -1 so at index two we're at -1 so at index two we're at -1 then 1 is at index 0 so that's three and two is at index three so we're over here which is -1 and that would be our here which is -1 and that would be our here which is -1 and that would be our output so we do need to have one more so we need to have a variable that's the dictionary of the locations of each of these numbers so we don't have to leave through the entire array and then we also have an another variable for this next greatest element thing and then at the end we just Loop through all of these numbers and nums one we have some kind of res or output array and we just append to that and that shouldn't give us any more space complexity because we already have this next greater element array okay so let's code that up so the first thing we're going to need is we're going to need a dictionary of locations let's say then we're also going to need this next greater element array so it's greatest greater element array it's going to be like this okay and we also need a stack and usually for these problems like I said if we're doing the easy solution it would be N squared complexity and we wouldn't actually need any extra space I mean we could have a res output but that's about it but the problem is we have N squared time complexity so usually you want to have some kind of trade-off where if the time complexity trade-off where if the time complexity trade-off where if the time complexity gets too big ideally you want to have Big O event for both so this is going to be a better solution okay so let's code this up so like I said we need to Loop through nums two so morning lengths too and what we need to do is for every element we need to store its location so then we also need to use our stack as we said before so when our stack is not empty and the element we're currently at is greater than the last one in the stack so let's do that so while stack and it's 2 I is greater than stack minus one and so remember our stack is going to have a tuple or a list of two values where the first value is the number and the second values index so we need to check it with this and so if this is the case then we need to pop off the end of the stack because we found the next greater element for the volume stack so we can just say number and x equals stack.pop and x equals stack.pop and x equals stack.pop we actually don't even need this number now that we compared it so this can just be this and we just need to update this index with the next greater element here so we can just say next greater index equals to I okay so this is going to keep happening until we either pop the whole stack or this number is no longer greater than the last element in the stack and now after we do that we need to append it to the stack got append and then remember we're appending the number and its index and I think that's it for this part of the code so we should be able to go through the stack we should be able to go through this nums 2 here so now that we have now what we did was we populated this next grader we can even print it if we want so if we just print it's greater let's see what that looks like just to make sure we did that correctly right so it's 3 4 minus one so let's see so the next grader for one with is three the next greater for three is four the next greater for four there is none and then the next greater for two is negative one so this is correct so now all we need to do is we need to have some kind of output array so let's just call that res and then we just need to Loop through every number and nums one and find its next greater element in this next greater array so how would we do that we would just say for I and range length numbers one and then we would say res dot append and then we are pending next grader and then we need to get the index so remember these next greater indexes match exactly with the nums two indices so we need to find where is this num's eye so if we're at like four we need to say where's the location of four so this would be locations of the number we're currently at which is nums one then we can just output that let's see okay also okay yeah so you can see it's quite a bit more efficient than the average solution so let's actually and you can also see that uh yeah they even tell you this daily temperatures is going to be kind of similar to what we're doing here which is this is the one with a stack so let's think of the time and space complexity for this and I did actually find if you do the optimal solution to a lot of these easy problems they become harder than a lot of medium problems okay so let's see what we're doing here so we are looping through nums two one time and then we're storing every single location in this dictionary and so most we can ever the most values we can ever have in our stack is the length of nums two so this whole Loop right here is going to take like let's say this is n and this is M lengthwise so the N is the length of nums one and so let's write that down real quick n equals length of nums one m equals length of nums two this we are looping through nums two one time and then here We're looping three numbers one time so our time complexity would be this solution right here so it would be n plus m okay so now let's think of the space so what are we using so we have this locations dictionary this location's dictionary is going to have a value for every single key numbers two and then we also have a stack and the most values we can possibly have in the stack is every number of nums two which means this would be M plus M worst case and then we also have this res that could also be the same worst case scenario it could be the same length as nums two so it'd be M plus n plus m and this is 3M which just goes down to m so that's our solution for the space okay so that's it for this problem and I'll see you in the next one
Next Greater Element I
next-greater-element-i
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`. Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._ **Example 1:** **Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\] **Output:** \[-1,3,-1\] **Explanation:** The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3. - 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1. **Example 2:** **Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\] **Output:** \[3,-1\] **Explanation:** The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3. - 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1. **Constraints:** * `1 <= nums1.length <= nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 104` * All integers in `nums1` and `nums2` are **unique**. * All the integers of `nums1` also appear in `nums2`. **Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
null
Array,Hash Table,Stack,Monotonic Stack
Easy
503,556,739,2227
45
welcome back and today we will be seeing the problem jump game two this is actually very similar to the previous problem we solved that is the jump game now let's first see what this problem says okay in this problem we will be starting at the zeroth position and we have to say what is the minimum number of steps that are required to reach the end in the last problem we were just checking whether we could reach the end or not in this problem we are checking the minimum number of jumps that are required to raise the end sounds complicated right but we will be using dynamic programming again to solve this problem and it is also given that it is guaranteed that we will be reaching the end so we will be having one less thing to worry about so now let's directly dive into the approach that we will be using so uh let's see why we are using dynamic programming in this problem because uh if we are at the position zero it means we are having two decisions okay so either we could reach three or one from three also we could reach one so it means that this is the overlapping problem and recursion in this particular problem is really very expensive and it is really unnecessary to do that so uh let's maintain a data structure named dp okay now in this data structure we will be storing the minimum number of jumps that are required to reach the particular position okay this much is understood now let's first think about the base case first we will be starting at the zeroth position okay we will always be here so what is the minimum number of jumps required here that will be always zero we will directly put 0 in our first position and in every dynamic programming problem it is really very important to find out the base cases so in this case we know that is 0 and this is the base case now let's when we will code let we will do one thing we will mark all the indexes as infinity first in this dp and what will be the length of this dp will be the length of this array currently now let's quickly do that here also so it will be good to visualize infinity and one more infinity okay so now let's see what are the minimum steps required to reach 3 how will we do that what is currently present for 3 infinity now if we are starting at 2 what is the minimum number of jump to reach 3 that is 1 plus minimum number of jumps required to reach 2 okay so we will always be making one jump from two to reach three at least one jump so how many jumps are required to reach two how we will know that is stored in our tp okay what is that value 0 means 1 plus dp of 0 that is equal to 1 so is this minimum then what is currently stored here yes then we will strike this out and mark it as 1 okay great now is there any element remaining that we could check no element is remaining so we will move on to the next one now we will move on to the one okay so we will start at two again how many steps are required to reach one let's see can we reach one zero plus two is what is the index is two and we could reach here via two so yes we could reach so we will be requiring one jump plus the minimum number of jumps that are required to reach two that is zero so this is 0 so we require only one jump to reach 1 also so is that less than infinity of course it is less than infinity so we will strike this and mark it as 1. now let's calculate for 3 also so how many jumps are required to reach 1 from 3 that will be 1 plus dp of 1 the minimum number of steps that are required to reach 3 so what is that is 1 plus 1 is 2 oh but we have already stored the minimum and 2 is greater than 1 so we will not update this okay so now let's move ahead now we are here so what are the minimum steps to reach here we will check from 2 to we cannot reach this index from 2 so we will not even update anything now we will check from 3 can we reach this index from 3 yes we can why because what is this index 1 plus 4 is greater than 3 sorry 1 plus 3 is greater than 3 i'm sorry so we could reach here so now we will try to update how many jumps are required 1 plus dt of 1 and what is that will be 2 so 2 is less than infinity so we will update this as 2 now let's check from 1 how many steps are required can first of all can we reach here yes we can reach here in this case and then how many steps are required that will be one plus one that is again two and two is already present so we will not update that now let's check for four okay we will c for 2 we cannot reach 4 prior 2 so we will not do anything but we could reach 4 from 3 because 1 plus 3 is equal to its index and its index is also 4. so we have to update means we will see we could update or not means 1 plus dp of 1 and that will be 2 okay we will update this we will mark this as 2 now let's check for one we cannot reach 4 from 1 okay so we will not do anything can we reach 4 from this index yes we can so what are the minimum steps that will be 1 plus dp of 3 and that is equals to 3 but is 3 less than 2 no then we will not be updating this so in the end whatever the number that is stored in this position that will be our answer so we will just be returning dp of what is that 4 and this is the answer okay i hope you have all understood the algorithm now let's quickly code that up this is the function that is given to us so now let's think about the base case if the length of the array is one itself so that means we are currently at the last position so we don't have to do anything we will just written zero okay now it is guaranteed that we could reach the end so we don't have to even check for anything now let's make our dp and what will be the type it will be of type end okay let's quickly make that dp and that will be of nums dot length size okay so now we know one thing that we need zero jumps to reach the zeroth index so let's mark that and before marking that what we will be doing is we will be marking everything as infinity in this dp first okay and how will we do that integer dot max value okay we have done this now what is the next step i said we have to mark the zeroth position as zero because we know that we are at the zeroth position so we don't require any jumps okay we have done this now what we have to do is we have to check for the remaining number of elements how many minimum steps are required so now let's check for the first one we will be starting at the first position and we will go till the end that will be numbers. and i plus okay now we have to check whether we could jump from the previous elements or not and what are all the previous elements that will be starting from the zero position and that will go till i so this is the case now let's see first of all we have to see whether that element is reachable or known how will we check that if j plus nums of j is greater than or equal to y that means this position is reachable now what we have to do is if the jump circle if the jumps that are calculated from this position is less than the currently what is present in the dp then we should update i could have phrased it better but okay let's see if we will only update dp of i like this if whatever the minimum is present we will take that and what is the next one 1 plus dp of g we have already calculated dp object so whatever the minimum is there we will just update that in our dp and believe it or not this is the entire code we just have to written the result and what position are we trying to reach we are trying to reach the last position so we will be returning the last position from here now let's run and see whether it is running or not okay it is running cannot find the oh i'm sorry this should be of type end now let's check again and it is done so let's submit and see as you can see we have actually solved this problem using dynamic programming and we will talk about the more optimized solution that will be the greedy approach in the next video thank you everyone if you find this video helpful please give it a like it really helps the channel a lot thank you
Jump Game II
jump-game-ii
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`. Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where: * `0 <= j <= nums[i]` and * `i + j < n` Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** 2 **Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[2,3,0,1,4\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 1000` * It's guaranteed that you can reach `nums[n - 1]`.
null
Array,Dynamic Programming,Greedy
Medium
55,1428,2001
13
great so welcome back and this is question 13 called roman to integer now for this question we're given a table here and just indicates you know the translation of a roman numeral to a typical number and so oh and so that's exactly what we're going to be doing with this question where we're given a string as our input and that'll be a string of roman numerals and we want to output here an integer value which you know is the numerical translation of that string and so we want to handle kind of two different cases here the first case is just the numbers themselves where we translate for example i three times is three or here where you know l is fifty v is five and three i's equal three and so that's just a straight up translation of the number but then the other case is we want to handle when a smaller number precedes a larger number and so since c is equal to 100 and m is equal to a thousand then since a c proceeds it's a larger number then we'll subtract the smaller number from the larger number to get 900 same thing with xc where it's 90 so 100 minus 10 and 5 minus 1 here that's when a smaller number precedes a larger number but in this case since m is larger than c we just take the straight up value of m which is a thousand which you know is identical to all these cases so l is greater than v is greater than i and these are all equal to each other so you just take out their straight up values now typically to perform this translation i find a lot of the solutions and discussion page uses a hash map but if you actually use a switch case you do get some performance enhancements it's actually a little bit faster than your typical hashmap especially since you're dealing with such a small set of values so i already went ahead and wrote it out just uh in a method here called translate and we're just keeping it private since we're simply using it in this method here and so yeah the switch case does exactly what you think it would you know if it's i we're returning one v five etc and so as we're iterating through this list of or these characters character by character we'll be calling upon this translation method to get the you know integer value of it so we'll go ahead and write a variable called sum which we'll be returning at the end of our method and so this will be you know incrementing each iteration with the translated value and so we'll also want to actually add a value representing the current number that we're looking at or the current roman numeral and so that'll be equal to the translation of the current character which will be index zero character at zero and so next we'll be iterating through that list of or that uh string there character by character so we'll put i equal to one since we already looked at the first value and then we'll be doing i plus since we're iterating by one each loop and then finally we just want to do this while i is less than the length of the string and so now we'll also want to add the next value that we're looking at and so that will be same thing here except we'll be looking at the character at i okay so this will be used so we can compare the current value that we're looking at and the following value to see is the current value greater than the value that comes after it and so to do that we'll just have an if statement here just move me up so if the current value is less than the next value just wrap that in brackets then what we're going to do is we're going to subtract the sum by the current value and so that would be like in this case where we see c here and since c is less than m we'll subtract 100 and then when we get to m we'll be adding a thousand which you know all in all it's 900 great so next we'll do an else and then we'll be adding the current value otherwise which handles the case where okay m is good to add 1000 here or i guess that would be more like this case and so next what we want to do is just set our current equal to our next so each iteration we're just setting the previous value and then the final thing is there's usually an edge case which there is in this case where we'll add the current value to our sum great so just to double check i think that looks good go ahead and run that and submit all right so i hope that helped it's a very performant solution you know it's faster 92 of other submissions so i really suggest using that switch case whenever you can use it and uh yeah so some of this logic is a little finicky like this edge case here of adding the current at the very end and the main thing to get in your head is that you have to compare the any cases where the preceding value is less than the value that comes after it and but all in all that's just a simple if and else statement so yeah i hope that helped and good luck with the rest your algorithms thank you
Roman to Integer
roman-to-integer
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two ones added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given a roman numeral, convert it to an integer. **Example 1:** **Input:** s = "III " **Output:** 3 **Explanation:** III = 3. **Example 2:** **Input:** s = "LVIII " **Output:** 58 **Explanation:** L = 50, V= 5, III = 3. **Example 3:** **Input:** s = "MCMXCIV " **Output:** 1994 **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= s.length <= 15` * `s` contains only the characters `('I', 'V', 'X', 'L', 'C', 'D', 'M')`. * It is **guaranteed** that `s` is a valid roman numeral in the range `[1, 3999]`.
Problem is simpler to solve by working the string from back to front and using a map.
Hash Table,Math,String
Easy
12
37
okay guys let's start that let's start with the thirty-seventh problem at with the thirty-seventh problem at with the thirty-seventh problem at Lincoln Sudoku solver write a program to solve a Sudoku puzzle by filling the empty cell empty sella indicated by the character dot so let's start by checking if board is equally good luck this return as call this all letter board that is the matter we are Beauty to the majority of the book the boolean solve passed board as kilometer 8 6 4 5 4 n I equal to 0 I smaller than 9 I plus 4 K and J equals 0 JS 4 + 9 GA + + okay now and J equals 0 JS 4 + 9 GA + + okay now and J equals 0 JS 4 + 9 GA + + okay now if old I see is equally to do but and we go ahead and have another loop for character number is equal to connector one to number smaller than equal to connect tonight num plus and with all this real check is valid board for I G and numb if it's valid you can go I is equal in number we're putting the number but we will know this will sort of the papazilla not so then we will check if the salt the board so basically we recursively calling the our function song if system control else which is assigned go to dr. board okay so once you walk exertional number we know this return false and if all of these have abandoned you then we return king then we make a boolean function is valid giving it the board and row and column and correct F number then we yes hello oh I equal 1 to 9 I plus so if board so and I is equal number then return false F mode I got hung click go down then your turn pause headboard 0 PI 3 into 3 plus I more tree and all our form by 3 into 3 plus I by 3 is equal to now none than little balls as this looks let's run this load 911 ok understand the game you leave a side of tactics 26th okay understandable okay let's open this okay except these days thank you
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
19
so I will be continuing with our playlist before that hey welcome back to the channel I hope you guys are doing extremely well so the problem that we will be solving today is removing the nth node from the end so what is the problem stating it is stating that it'll be given the head of the link list and it'll also be given a value n you'll have to count n from backwards so if I count it this is the second node you'll have to delete the second node from the end and once you've deleted Ed the three that was pointing to the second node from the end will be pointing to the last node or whatever n minus one node and once this is done you'll have to return me the head of this particular link list after modification after deletion so n can be anything what if I give you n as five in that case n will like the fifth note from the end will be the head of the link list right if you delete this will be the new head of the link list so you'll have to return me this one so depending on the value of n you'll have to give me an algorithm that doesn't so if this problem comes up in an interview what is the extreme KN solution that you can think of like what I can think of is okay n is given as two I definitely cannot Travers backwards so the first step that I can do is maybe take a variable counter which will count the length of the link list right and let's take a temporary node or pointer pointing to the Head let's start counting counter one let's move temp counter two let's move temp counter three let's move 10 count of four let's move 10 count of five let's move 10 and it will reach here which is null stop so you stop and you know the value of counter is five so the value of count is five which is the length of the link list I've been asked to delete the second last note so do I need to reach this note just ask yourself the answer to that is no why because if I delete this deleting it is easy but the original task is to make sure this is pointing to this because I have to change the links otherwise it doesn't make sense I have to change the links so if I reach here how can I change the link of the previous node so technically I need to reach here because if I reach here then I can straight away change the link and point it right so I need to reach the third node and what is this count minus n 5 - 2 I have reach the count minus n 5 - 2 I have reach the count minus n 5 - 2 I have reach the third node so can I say I need to reach the third node which is Count minus n correct so result will be count minus n we will talk about the edge cases afterwards but as of now understand that the result is Count minus one okay so what I will do on the next step is I'll again start I treating okay let's start it treating so temporary is at the head and the first thing that I'll do is I'll reduce the resultant by one and I'll see if I've reached that and the answer is no so I'll move temporary once I've moved it again I'll reduce it have I reached the answer is no then I'll again move it reduce and the moment you reduce after that you will check is it zero it is and if that is zero this is your node where you want to stop at the previous node to the node that you want to delete stopped what is the job that I have to do the first job is please make sure you uh take any other variable and uh maybe delete node and say temporary. next node delete node and say temporary. next just store it so what I've done is I've stored the delete note to be here just store it why I'll explain you done what is your next job the next job is temporary your next can you point to Temporaries next so this link will now go and point to this now once you have done this if it is C++ you say free node free this C++ you say free node free this C++ you say free node free this particular node D node if it is Java you don't have to free it you do not have to free it what will happen is the moment you do this will get freed so it's deleted and this will be your modified link list once it is modified you can return the head of the link list now you might be thinking about an edge case what if n was five in that case the node would have been the head of the link list so there will be a new head you'll end up returning head. nextt end up returning head. next got it so this was The Brute Force if I have to write down the code it's going to be super simple so time to write down the pseudo code in case you want the C++ Java p and JavaScript code want the C++ Java p and JavaScript code want the C++ Java p and JavaScript code for this brute force it will be given in the description like the link there will be article link you can go over there and find it out so what do we need a counter variable so let's take a counter variable which is zero this will keep a count of the length of the link list let's take temporary which is pointing to the head of the link list done what is the next job travels and count the number of nodes so let's Traverse so I'll keep traversing till temporary is not equal to null and I'll do counter Plus+ at the same time I'll do counter Plus+ at the same time I'll do counter Plus+ at the same time I'll say temporary next so it'll go ahead and compute this comput it what is the next job we need to make sure hey if this count is equivalent to whatever like the N that I've been asked to delete that means it is the head that has been asked to delete so what I will do is I'll say the new head is head next this is my new head and I will be returning this new head if you're coding in C++ then please head if you're coding in C++ then please head if you're coding in C++ then please make sure to free the previous head that is very important this is just for C++ because in Java there is a garbage C++ because in Java there is a garbage C++ because in Java there is a garbage collector which will delete it got it done you have freed that space and you have returned then new head what if this is not the case in that case you'll have to move so again Please assign something as resultant so what will be the value of resultant it'll be count minus n and please reassign temporary to head once this is done let's again start traversing so you can start traversing like temporary is not equal to null and what you can do is you can say rest minus because every time you are at a node you just reduce one and if you see the resultant is equivalent to zero in case you straight away break otherwise you say hey temporary can go to the next because I still it's not the element that I'm looking for done what is your next job first thing that you'll do is which node you want to delete please keep it delete node so you're standing at temporary at this point temporary would be standing here so just take the next so what I'll do is I'll take the next because this is the note that I want to delete after this I'll say temporary. next will be temporary dot next of next changed the link once youve changed the link return the head and please make sure you free the node and this is again just for C++ because and this is again just for C++ because and this is again just for C++ because in Java the garbage collector will do it job so let's talk about the time complexity can I say that I'm taking a beo of length of the link list in order to compute the length yes in the first pass and then I'm traversing length minus n because that is what resulted was if you carefully look at this length minus n right so it's taking another length - n in order to reach the length - n in order to reach the length - n in order to reach the previous node then we are changing the links so this will be the time complexity what will be the space complexity that's a big off one because we not using any external space if I ask you about this one what is the worst case that's somewhere near about B of 2 into length Y imagine if n is given as 1 this will be somewhere near about B length hence the total time complexity is twice of length right and this is the reason the interviewer will ask you to optimize it so the optimal algorithm's intution is based on the Brute Force now what we did during the brute force was we tried reaching the previous node the node right before the node that was to be deleted this node was to be deleted we tried reaching right before that so this was the previous node correct and if you carefully observe it is like two steps to the end so can I say this if I Traverse and if I Traverse two steps lesser so technically to Traverse the entire link list it will take five steps because it has five notes if I Travers two steps lesser that is if I Travers three steps I will end up reaching the previous note and that is what I want to do I want to reach the previous note now you'll be asking hey if I don't know five How Will I Know three because 5 - 2 is three without three because 5 - 2 is three without three because 5 - 2 is three without knowing five I cannot I can actually what I will do is I will take a pointer known as fast pointer and I'll move it two steps so one step two step so I have moved it two step yes I moved it two step stop there so I moved it two step okay the next point that I'll take is slow pointer this time I'll start moving them simultaneously slow and fast move them simultaneously by one fast will go here slow will go here next again move them simultaneously fast will go here and slow will go here stop the moment you reach the last node stop and you will see that the slow is pointing to the previous slope yes you do why did that happen because initially you did move two steps and then you covered the next set of steps so you are technically standing at the previous note now if you're standing at the previous note what is your next job I think you know what to do now the same right so what I will do is I'll try to write down the pseudo code now so I'll be writing down the pseudo code in case you want the C++ Java Python and you want the C++ Java Python and you want the C++ Java Python and JavaScript codes there is an article Link in the description open it and you'll find all the codes what is the first thing we'll do we will take a fast pointer for sure and we will point it to the head and we'll move it and steps that is two steps over here so follow Loop of I equal to 0 till n and please move it fast equal to first of next done once you have done this what will happen fast will be standing here perfect after this take slow and point it to head and you know you'll stop when the first reaches the last this is when you stop because the slow will be here so let's do it you basically say hey while I reach the last node which is fast of next is not null otherwise I'll keep moving I'll be like hey can you move slow equal to slow. nextt and can you move fast equal to fast. next perfect once you have done this what is your next job the next job is to make sure that you take this is D node that you have to delete so D node just store it somewhere again just for C++ slow off it somewhere again just for C++ slow off it somewhere again just for C++ slow off next once you've done this free it or rather don't free it because so after the step Do Not Free it why because if you try to free it what will happen is this link will go off and you'll not be able to get this one so do not free it now what you'll do is you'll say slow next equal to slow dot next and next so what this will do is this will not point it once you have done this you are free to free it free delation of node this one is freed and then you can straight away return the head so you'll be returning this particular head now this will work for all the cases apart from whenever n is 5 imagine I give you ns5 let's try to do it so if n is 5 let's see what happens if n is five I'll take the first pointer here one step two step three step four step five step so if it reaches null then you'll have to write something else so make sure you enter it over here if you reach null that means you've been asked to delete head so again repeat the same process that we have done in the root Force delete the head and return head. next so if this is the condition what you'll do is return the new head which is head. next so it basically goes as return head. next I'm not freeing the note you can free that yourself I assume you can do it now so please make sure you return head. next in case your FAS is reaching now this will be the edge case so let's quickly get back into the code editor what I've done is I've written the exact same code I'll hit the submit button and it will be submitted please make sure that you take the deletion like this delete node that you have to delete and delete it after the pointer step not before got it so let's get back to the iPad and discuss the time complexity what will be it can I say it is beo of length y we have two Loops one is the for the other one is the Y and both of them have the fast pointer which is moving if I have to analyze can I see that the fast pointer was here and then it moved till here for the first fall Loop then it took some more steps and moved till the last So eventually if I can compute how much did the Fast Point move overall that will be my time complexity can I see it moved from here to here which is the length of the link list thereby the time complexity is beo of length what about the space complexity that is bego of one yes because we are not using any external space so if you're still watching I'm sure you have understood everything and if that is the case please do comment understood and please do consider giving us a like and if you're new to our Channel what are you waiting for hit that subscribe button right away and with this I'll be wrapping up this video Let's Wait in some other video till then bye-bye take care when your till then bye-bye take care when your till then bye-bye take care when your heart is broken don't forget your golden I will find light
Remove Nth Node From End of List
remove-nth-node-from-end-of-list
Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. **Example 1:** **Input:** head = \[1,2,3,4,5\], n = 2 **Output:** \[1,2,3,5\] **Example 2:** **Input:** head = \[1\], n = 1 **Output:** \[\] **Example 3:** **Input:** head = \[1,2\], n = 1 **Output:** \[1\] **Constraints:** * The number of nodes in the list is `sz`. * `1 <= sz <= 30` * `0 <= Node.val <= 100` * `1 <= n <= sz` **Follow up:** Could you do this in one pass?
Maintain two pointers and update one with a delay of n steps.
Linked List,Two Pointers
Medium
528,1618,2216
853
hey what's up guys this is sean here so today let's take a look at this uh problem number 853 car fleet it's a media level problem so you're giving like n cards and these end cards are going to the same direction and on a one lane road the destination is a target the miles away and each car has a constant speed here okay in miles per hour an initial position and there's also like a ray here uh represents the position of each car okay so and the constraint the constraints like it's this a car can could never pass another car ahead of it so which means whenever a car caught up catches up with the car ahead of him it will drive bumper to bumper at the same speed and the distance between those two cars is ignored they're assumed to have the same position okay so basically you know let's say we have a car here right a bit of a car and then we have another car here okay and this is a target right and this is their driving uh driving direction so the time by the time the second let's say assuming this car has a faster speed right and then whenever this car can catch up with this car basically it will just uh be here right they will be bump bumper to bumpers and they will be treated as the same car and at the same location so they will be they will keep moving forward at the same speed which is the speed that's the first car having okay so that's the constraints and so whenever a few let's say more than one cars and now those two cars is considered are considered as a fleet so and also a single car is also a car fleet okay and if a car catches up to a car fleet right at the destination point it will still be considered as one car fleet okay so which means that you know let's say we have a car we have a fleet which is the uh the target destinations and then there and there's another fleet com coming to the reaching the target they'll be treated as a separate fleet okay they will be only become they'll only be merging to one fleet before reaching the target okay so and it asks you to find the uh how many car fleets will arrive at the destination okay so for example we have like a target right there's a like example here target is 12 and the position is like 10 8 0 5 3 and the speed for each car is like this 2 4 1 3 so the final answer is it's 3 so why is that this is because you know the car one and the car two they will be they will form one fleet okay and the car three itself is a fleet because here you know the target is 12 right that's why the other position is 10 so and we with speed 2 here so the time the rifle time for the car 1 will be what will be 12 minus 2 sorry 12 minus 10 divided by two that's the rival time for the first car right and the rival time for the second car is what's the uh 12 minus eight divided by his speed which is four and this is one this is also one okay all right that's why they can be a forming two into one fleet because they are reaching the target position at the same time right i mean at the same time or equal or b or before the target they all can they'll be considered as one fleet so and then another one is that so for car three here right since the uh the speed is one so the time for the car three for car three to reach the target is what is 12 minus zero divided by one right which is 12. right so how about the uh how about uh car four here so the car four the same thing so this is three this is one this is a one this is car two so car four is like this car four is uh twelve minus five divided by one which is seven right and finally the car five sorry the car five is what it's 12 minus three divided by three right which is three okay cool so as you guys can see here right so the time for four and five right four and five so here's the observation right so when can when kind of car um so when will those two one will two cars as a fleet the first thing is that you know faster car faster cars is on the left first car is on the left of slower car okay that's basically the uh the conditions a car fleet can be formed so to be able to find the uh which cards on the left and which card is on the right so the easiest way is we just do a sort we sort by the position okay so we sort by position and then we process from the right from right to the left and as long as we can see uh a car the current car right the current car which is at the host arrival time it's smaller than the uh then the previous car then we know okay we have to find a fleet so which means that we can simply uh ignore the current car right because it will be uh merged with the previous car yeah and we keep doing that you know until uh we have reached the uh the first car and then in the end the length of the of this the stack will be the uh what would be the final answer because every time when we have a stack here okay we so first we sort by this position along with the speed here and every time when we have a car when we have a at the current car here at the current position here we get it's we calculate its arrival time and then we compare the rival time with the uh with the first element with the top element of this stack if the arrival time is smaller equal or if i mean if the arrival time is equal or smaller than the then the current then the top one then we can simply ignore that car because we know that car will be merged with the current with this car right and then in the end the length of the stack will be our final answer okay uh i'll try to start implementing this code here so this is what i mean okay we have a sorted right we stored it by the zip this is like a helper functions in python where you can zip to a list who has this who have the same length together and then it will generate a sorted a combined list here so i sort by the positions and then we have n here of length cars okay and then we have a i have an answer here okay so the answer is it's like a stack you know basically i'm storing the uh fleet the total fleet in this answer here so for i in range of the n minus 1 minus one so the reason i'm traversing from the end uh reversely is because the uh since we need to know since the condition we are using here is that you know what we want to know if the current car is faster than the previous car which means the car on the right side that's why in order to get the previous cars speed we need to uh traverse from the end okay now we have a the current car's position at the speed right equals to the cars i and then we have arrival time right arrival time equals to what equals to the target miners uh current position divided by s okay so here's the condition here so we only insert uh append to this current answer when what if first is not stack right if the stack is empty we do the insert or what or the rival time or the arrival time is greater than the stack minus one okay and then we do the insert arrival time and then we insert this arrival time okay so this is the same thing right like the uh basically if the current car if the car speed is faster it's faster than the previously a car fleet right and then we simply uh skip that car so vice versa right so when the current arrival time is later it's later than the previously fleet's arrival time then we know okay we have a so this car itself has to be has to become its own another car fleet right so and in the end we simply return the length of the stack sorry answer okay sorry this should be the answer yep so that's it i think that should work position positions okay some typos here position all right accept it submit cool yep that's it you know i think this one is pretty straightforward right so oh and one more thing here i mean actually we don't have to maintain this stack here we can simply use like a counter here that will also work basically we use the counters and then we also maintain the last the previously arrival time so same thing any time when the arrival time the new arrival time is greater than the previous one we increase the counter by one and then we update the uh the previously arrival time with the current one right but i'm just using the stack here because it's a it's more clear for me all right so for the time space complexity i think this one is pretty straightforward right the uh since we have a sort here right so time and space is both unlocked because here it's just a log n here right so that's why the total time space complexity for this problem they're both unlocked yeah i think this one is like it's simple like a sorting problem sorting plus simulations i can say that or is it a greedy idea here prob probably not i think it's more like a sorting and then we do a simulation from the uh from the end to the start yep cool i think that's it for this problem thank you so much for guys to watch this video stay tuned i'll see you guys soon bye
Car Fleet
most-profit-assigning-work
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper **at the same speed**. The faster car will **slow down** to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position). A **car fleet** is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet. Return _the **number of car fleets** that will arrive at the destination_. **Example 1:** **Input:** target = 12, position = \[10,8,0,5,3\], speed = \[2,4,1,1,3\] **Output:** 3 **Explanation:** The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12. The car starting at 0 does not catch up to any other car, so it is a fleet by itself. The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. Note that no other cars meet these fleets before the destination, so the answer is 3. **Example 2:** **Input:** target = 10, position = \[3\], speed = \[3\] **Output:** 1 **Explanation:** There is only one car, hence there is only one fleet. **Example 3:** **Input:** target = 100, position = \[0,2,4\], speed = \[4,2,1\] **Output:** 1 **Explanation:** The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2. Then, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target. **Constraints:** * `n == position.length == speed.length` * `1 <= n <= 105` * `0 < target <= 106` * `0 <= position[i] < target` * All the values of `position` are **unique**. * `0 < speed[i] <= 106`
null
Array,Two Pointers,Binary Search,Greedy,Sorting
Medium
2180
942
hey what's going on guys it's ilya bella here i record your stuff on youtube chat description for all my information i do all legal problems uh make sure you subscribe to the channel give me a big thumbs up to support it and this is called the i string match given a string s that only contains i increase or d decrease let n is equal to s the length and return any permutation a of 0 1 to n such that for all i is equal to 0 up to n minus 1 if s i is equal to i increase then a i is less than a i plus 1. if s i is equal to d decrease then a i is greater than a i plus 1 and let's look at this example we got i which is uh zero is less than four right here uh d means that four is greater than one right here uh increase right here which is one uh is less than three right there uh d which is uh three is greater than 2 right here we got this array in ascending order here 3 is greater than 2 is greater than 0 and 0 is less than one the length of that string is uh greater than or equal to one and this less than or equal to ten thousands s only contains characters i or d and go ahead all you need is this uh and which is the length of that string then left which is zero we got two pointers right left and right uh and right which is n and array which is a new integer and the length of that array is equal to n plus one this array will contain uh the results and we are looking through that string i is equal to zero is less than s or just n right and i plus at each duration uh we set up the value at the position of i which is the current position in the case when the character add which is the letter in our case uh at the current position is equal to uh increase then we uh set up two left pointer otherwise to the right pointer and update left saying that uh left increment by one right you decrement by one in the case when we choose right also array at the position of n is equal to left and finally return this all right that's pretty much it let's run this code accept it let's submit success good let's look at this example one more time real quick we got this uh string s which is right here and this is uh or just let's say you know it's like zero one right two three uh we're at the position of zero initially at uh i right so um n is equal to uh four right uh left which is zero right which is uh four and array has a bunch of zeros you know zero yeah like four you have four zeroes uh and this is zero one two three we start looping through the through this string and we are at the position of zero red zero we are here and you know as character at i which is uh increase so we say left right we got zero we put left here um we increment left by one here uh then increment i by one we are here and here at i we got uh you know d which is uh which means that we need to put right is equal to 4 so we put 4 here then uh increment i by 1 we are here and uh at two we got i which is uh left right left also right here before incrementing we need to decrement right by one we say three then we increment i by one we are here at the position of two and we say that at 2 we got i means that we need to put that left is equal to 1 so at 2 we got 1 we increment left by one two then we are at the position of three and at three we got d which is uh right so we say right here we got three right we got three and um yeah and finally we added that loop right and you could notice that initially we created an array the length of n plus 1 means that 4 plus 1 is equal to 5 so we got an extra addition right there we got four so at four which is n which is four we need to put uh the left right so at three we get right uh we need to decrement by one which is two and at four we put the left which is two that's it that's the whole problem again thank you guys for watching leave your comments below i want to know what you think follow me on social medias uh follow me on instagram at me on snapchat and um i wish you all the best bye
DI String Match
super-palindromes
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Math,Enumeration
Hard
null
56
in this video we'll go over Le code question number 56 merge intervals given an array of intervals where the I element is another array that contains the starting and ending values of that interval we need to merge all overlapping intervals and return the new result for example let's say this is the intervals array if we visualize this on a number line then this is what it looks like we can see that the first two intervals overlap so we would merge them into a new interval that starts at one and ends at five now next we can see that the green and purple intervals overlap but since the purple interval Falls entirely within the green one the merged interval will just be from 6 to 9 and we can ignore the purple one and that's the answer we would return an array with the intervals 1 to 5 and 6 to 9 so here's how we're going to do it first of all the intervals can be in any order so the first thing we're going to do is sort the intervals by their starting values this makes things easier since now we can iterate through the array in order we'll start by comparing the ending value of the first interval with the starting value of the second interval if the end of the first interval is greater than the start of the second interval like it is here then that means the intervals overlap since the intervals are sorted according to their starting values we know that the merged interval is going to begin with the starting value of the first interval in this case one but to find the ending value we'll have to compare the end values of both intervals and take the maximum here five is greater than three so the merged interval goes from 1 to 5 then we do the same thing but this time use our new merged interval as our first interval here the ending value of the first interval is five which is less than the starting value of the second interval which is six that means that there is no overlap so we'll just add the interval of 6 to 9 to our answer then let's do the same thing again 9 is greater than 7 so these two intervals overlap when we compare the ending value values we see that 9 is greater than 8 so the merged interval keeps its ending value of 9 now let's try implementing this solution in Python let's say this is the intervals array as I mentioned the first thing we're going to do is sort the array and the way we can do this is by using the buil-in sort method this is by using the buil-in sort method this is by using the buil-in sort method of python lists but how do we tell python that we want it to be sorted according to the first element in each inner list well we can do that by passing in a keyword argument that is a function that tells python how we want the intervals to be sorted if you're not familiar with Lambda functions I'd highly recommend you check out my video on python Lambda functions and the link is in the description but basically this is a function that says for each interval X I want you to use the element at index zero in other words the starting value of that interval to sort them so using the starting values as the Sorting key we're going to sort the intervals in ascending order we're then going to create a new list called merged and initialize it with the first interval in the intervals list so that's going to be 02 merged is going to be the list that contains our final answer then we'll Loop through the intervals list using a variable called interval and start merging and we're going to use the same logic as we discussed before if the ending value of the first interval is less than the starting value of the second one then there's no overlap and we simply append the second interval to our answer otherwise we take the maximum of the ending values and make that The New Ending value of our merged interval now since we already initialized the merge list with the first interval this first iteration will actually compare the first interval to itself but it's only one extra iteration so it's not really a big deal I do it this way because otherwise this part right here would throw an error since there's no inner list if you don't like this then you don't have to initialize the merge list with anything but you'd have to add something like if not merged or to this if statement to make sure you don't get an error but for now I'll keep it this way because it's also a good example to show what happens if we have duplicate intervals so this part will get the last element in the merge list and in Python we can do this by using an index of -1 so that's going to be this index of -1 so that's going to be this index of -1 so that's going to be this interval here then from that interval we're going to get the element at index one in other words the ending value so that's two we're then going to compare it to the element at index zero of the interval variable so that's zero the starting value you can see that 2 is greater than Z which means these two intervals overlap and we'll go to this else block this is where we're going to compare the ending values of both intervals take the maximum and make that The New Ending value of our first interval so right now both ending values are two so this ending value stays at two and we just move on to the next interval again let's compare the ending value of the first interval with the starting value of the second interval this time 2 is less than three which means there is no overlap so we'll just go ahead and append the second interval which is 35 next the ending value of our first interval is now five since we just depended that and the starting value of the second interval is four 5 is greater than four so this is false and we'll merge the two intervals when we compare the ending values we see that 8 is greater than 5 so let's modify the ending value of our first interval to 8 finally 8 is greater than 5 so this is another overlap let's compare the ending values 8 is greater than 6 so the ending value of our first interval stays at 8 and that's all the intervals in the list all that's left to do is return merged and we're done
Merge Intervals
merge-intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. **Example 1:** **Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\] **Output:** \[\[1,6\],\[8,10\],\[15,18\]\] **Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\]. **Example 2:** **Input:** intervals = \[\[1,4\],\[4,5\]\] **Output:** \[\[1,5\]\] **Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping. **Constraints:** * `1 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 104`
null
Array,Sorting
Medium
57,252,253,495,616,715,761,768,1028,2297,2319
18
Hello Guys Welcome Back To Decades In This Video Bhi See The Force Hum Problem Kuch Is Remedy Ko Number-18 So Latest Video Ko Number-18 So Latest Video Ko Number-18 So Latest Video Problem Statement In This Problem Thursday Ko Switch On In Tears And Thursday Ko Switch A B C D A B SUBSCRIBE NOW TO RECEIVE NEW UPDATES UNIQUE CONTENT TO-DO LIST SUBSCRIBE MUST SUBSCRIBE MORE ELEMENTS DIFFERENT ELEMENTS FROM EVIL MIDDLE UPTEIT DOCTOR PLATE OFF - 2 - TWO 1 MIDDLE UPTEIT DOCTOR PLATE OFF - 2 - TWO 1 MIDDLE UPTEIT DOCTOR PLATE OFF - 2 - TWO 1 PULSAR 200 NS ONE QUARTER PLATE OK NO PROBLEM CANDY - 02 RATE IN THIS Is it The PROBLEM CANDY - 02 RATE IN THIS Is it The PROBLEM CANDY - 02 RATE IN THIS Is it The Video then subscribe to the detention Will take all possible subscribe this Video subscribe The quiet area should be targeted OK security of Al-Shabaab different security of Al-Shabaab different security of Al-Shabaab different using for loop condition given this area will just because they can do all subscribe Button Click Please Click on the Video then subscribe to the Page if you remember only 1 After Having Loop to Multiple Elements OK and They Want to Reduce Shampoo Just Unique Elements in a Very Good Data Structure for Doing a Set Only Key Tuning Elements That Will Remove All Set To Enter Unique Water Element In The Combination next9 News Room Report Subscribe Now To Receive New Updates Reviews And News Shubhendu Jio Phone In The Next Time Zone Khandhe Will Be Checking The Current Affair With Dhawan Radhe-Radhe Video To The great saint of nation Radhe-Radhe Video To The great saint of nation Radhe-Radhe Video To The great saint of nation into the say this is 12345 subscribe combination 153 year 2009 matching with this video subscribe and subscirbe more time complexity will be easy hair oil running from 0001 subscribe 459 total time complexity this is the total time simple subscribe for More Video Subscribe Thank You Love You Removing Final Tube Scandal And Replaced By Two Point Technique Which Left And Right The Love You Two Plus One And Elements Of But I Don't Like And Subscribe In A Reader For This Point to take subscribe and subscribe the Video then subscribe to the Page if you liked The Video 58th When will it improve This lineage on this website Doctors Maintain the setting Order is order important in the first day of the combination I will produce gradually 90 days The Amazing subscribe and subscribe the Channel subscribe our and quarter engagement with just a few and long and time and will be independent of this and press the time in more view subscribe to the Page if you liked The Video then subscribe to The Amazing will do It is the name of the number one time complexity of that habit relax feel already taken up and cube and inside the third Lokpal will be insulting intersect ok insert in set suid a log in time to time complexity will be cube subscribe for More Video Subscribe Set Up To Be Very Interactive Arts Approach subscribe The Channel Question Target And Only Then Will Promo Quadruple Play Services Modification More Subscribe Now To Do The Thing You Can Just For All Possible To Subscribe The Total Number Of Elements Of Obscuritism The Places To Visit the main point Some Wishes in Assam Special K Plus Airtel Suvidha for all the unique combination of combinations This Z1 combination Rate Minus Plus will give wealth Plus Channel Ko subscribe and subscribe the Channel Please subscribe and subscribe the Channel Jhal U End Did exist and the palaces already visible to value day you after quadruplet know the second condition is village after auspicious day it is cotton to observe this order will always fall in love with this order I do not know the thing which comes very quickly s possible to Subscribe Aap Inne Combination of the Channel subscribe Kare Techniques in Assam of the previous explanation Switch of the like Finding the number of voters will give some hair oil use this and others on Google's problem which is the problem use same to you can recommend you To Watch Videos Without Interruption Subscribe Will Find All Possible 2010 2030 Combination - - - - - Hours Or One OK Similarly The Evil Find All Possible 2010 2030 Combination - - - - - Hours Or One OK Similarly The Evil Find All Possible 2010 2030 Combination - - - - - Hours Or One OK Similarly The Evil Increment In The Next 100 Years - Two Increment In The Next 100 Years - Two Increment In The Next 100 Years - Two Plus 06 - 2nd T20 Match 2018 All The Best Plus 06 - 2nd T20 Match 2018 All The Best Plus 06 - 2nd T20 Match 2018 All The Best And Values ​​Will Start From Do And Values ​​Will Start From Do And Values ​​Will Start From Do n't forget to subscribe and subscribe Possible to know what will oo Will start from the same position will be plus C 200 Difficult to minus two plus minus one liner E know oo Will find out the value - - - liner E know oo Will find out the value - - - liner E know oo Will find out the value - - - - Spent Subscribe Combination Solid - Spent Subscribe Combination Solid - Spent Subscribe Combination Solid Combination More U Where is the first quarter - 2nd part plus and quarter - 2nd part plus and quarter - 2nd part plus and minus plus minus two and sonu value will be easy - 205 miles - and sonu value will be easy - 205 miles - and sonu value will be easy - 205 miles - 90 request to medium to present in this is the 2009 this is two three idiot will Live in Villages with Water All The Best Kids Who Can They Take Care Answer Sudhir Which Will Help You To Be Time Complexity Of What They Are Doing All The Possible And Square 2ND Year Singer Who And Travels In All The Best Possible More Present In This will be doing all this and elements for the time complexity subscribe and subscribe the Channel for More videos Time Complexity of New Technique Click Remind Faizabad Up Officer Very Problem S Well S for the Number of Medicine Expert Committee Ne Technique Software From Person to Person IF You Are Able To Understand All Latest Love You All Subscribe Number One Five Simple And Easy Subscribe if you liked The Video then subscribe to the Page if you liked The Video then subscribe to the Will So Take Care Of All The Duplicates Will Remove Duplicates Slide Don't Need To Think About And Finally Bigg Boss Two-Wheeler And Finally Bigg Boss Two-Wheeler And Finally Bigg Boss Two-Wheeler Saturn Will Push All The Elements Of Versus Knobs Even More Like Her Dog In The Element This Point Subscribe Video Dirty Accessible Third Quarter Flat Rate And Will Work Hard [ __ ] Mom Taste Appoint And Will Work Hard [ __ ] Mom Taste Appoint And Will Work Hard [ __ ] Mom Taste Appoint Duplicates Express to the Video then subscribe to the Page if you liked The Video then Jhaal CM Addresses and Values ​​OK Jhaal CM Addresses and Values ​​OK Jhaal CM Addresses and Values ​​OK Swadisht and the First Approach Noida Second Approach to Avoid You Two Point Plus Seat subscribe to the Page if you liked The Video then subscribe to * Shams It Will Wait Or Index Value OK Like * Shams It Will Wait Or Index Value OK Like * Shams It Will Wait Or Index Value OK Like And Share 100 This Is The Operation West And Cooperation For All Possible To Subscribe Not Possible To Subscribe Subscribing All The Best All The Value - subscribe The Best All The Value - subscribe The Best All The Value - subscribe The Channel and subscribe the App Remind someone is pond and will explore all the end elements are so many of storing elements in the form of China in this question is implemented in which is the way were nothing but I will take care of subscribe is the president Of the element which element in increasing order i j k l id no one will not be i 10 minutes ok saugandh and s they should also be different from the events list values ​​and after that only will be events list values ​​and after that only will be events list values ​​and after that only will be pushed into answer chapter and will be doing all This quarter subscribe our Channel and subscribe the comment section which one you understand when you feel free to help possible like share and subscribe our channel thank you
4Sum
4sum
Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that: * `0 <= a, b, c, d < n` * `a`, `b`, `c`, and `d` are **distinct**. * `nums[a] + nums[b] + nums[c] + nums[d] == target` You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,0,-1,0,-2,2\], target = 0 **Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\] **Example 2:** **Input:** nums = \[2,2,2,2,2\], target = 8 **Output:** \[\[2,2,2,2\]\] **Constraints:** * `1 <= nums.length <= 200` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109`
null
Array,Two Pointers,Sorting
Medium
1,15,454,2122
1,769
hello everyone welcome to another video now in this video we are going to look at another medium level question and this is going to be like really simple because uh you know you have come to a medium level question so uh you know most of the concepts from Easy level question now but uh one thing that we need to look uh on this question is that the Brute Force approach is going to be really simple um it is no big deal uh the reason why this question is in medium there's a question a medium level difficulty is that because we need to solve we need to try to solve this in a lower time complexity right so how are we going to do that so for the expectation purpose I will still uh do both the solutions for the brute force and the optimized one okay so let's first understand what the question is all about and then we will look into the solutions as well so right now we have a question so in the question we are given a string I am taking the first example here okay and what this string represents is let's say a kind of boxes okay so right now we have three boxes okay and we need to move uh and this one it represents a ball okay and 0 represents empty okay now we need to move all the balls to each particular index okay or each particular box in this case so um and apart from that we need to see like how many positions the ball has to shift to move from one to from to move all the balls to one particular uh box okay that means if I want to shift this one to the left or right it is going to take one position similarly uh if I want to uh push like this one to let's say the last one so it is going to be one and then two steps right so in that way we have to return the final answer so what's going to be the final answer in this case Okay so if you will see apart from this we have one more uh ball okay so to move that we are going to take only one uh step for this also we have apart from this only one ball that is also going to be going that will also take one step but for this we have two balls okay this is going to take one step but this is going to take two steps okay this is like one and then from here two okay so one plus two that is three so our final result is going to be one and three okay now um The Brute Force approach what is going to be is that for we will be having like a nested Loop okay and we will check if uh we are able to move that box that ball to that particular index or not okay so let's jump into the Brute Force it's really simple and you'll be able to understand just by the code itself I will not have to understand like um you know I will not have to show you uh particularly how to solve that theoretically so let me just start with this Final Answer uh final code for Brute Force so the first thing that we require is the result right so where we are going to store the final hour um solution so for that let me create a vector so there is going to be result and I'm giving the size as well this is going to be same as boxes okay now let's do uh create this uh nested Loops okay this is going to be boxes dot size similarly now we need to check here two conditions I should not be equals to zero the first thing and the second thing is going to be at index J it should be 1. okay only in that case what we'll do is result will include that particular value there but we need to look for the distance right how much they are far that much position that much steps they are going to take so for that I am taking absolute of I minus J why absolute because we are not sure whether I is going to be greater or J is going to be greater okay and that's it our brute force is done I'll simply return this result let me submit this foreign okay salute type index I that is going to be plus equals to um absolute right yeah okay so that was our Brute Force approach but if you will see the run time that's really high and we as our solution is almost like um below 50 percent right and this is going to be taking this will be taking like o of n Square time complexity okay so let's optimize this how are we going to do that so the this is one of the classic examples of two pass okay um yeah to pass okay so two bars is nothing as the name says we are going to pass through our array twice it can be like in the same direction it can be in the opposite direction okay anything so this is the classic example of two pass as I said how let's let me show you so as we have this string here right and we want to see like how much we have to travel okay so I will create a variable travel and we also need to take care okay to track the number of ones we have okay so for that we'll take a variable once as well now in this particular problem what we are going to do is that in the first pass we will see how many ones we have to the left of that index okay that means so how many ones do we have before this zero how many ones do we have before this one how many have ones we have before this that is two similarly in the second pass we'll take care of how many ones we have to the right of the index okay so how many ones do we have at the right of this uh the zero to the right of this one again zero to the right of this one we have one okay now we have this positions but we all but we know we don't need these positions we need the distances between them we need to travel okay so that's what we are going to do that is the main thing that we need to see over here so how is that going to be so first we will find how much we are going to travel how will we find this we will only travel when we have encountered a one okay another thing that we need to take care is that whatever we have traveled we will store that at that particular index okay it will not simply store we will add it as well because we are going to do two pass right so we need to have the earlier result as well okay and lastly we will check like we will check the number of ones we have okay so that is going to be like if we have one once if once then that is going to be um we'll increment our once counter let me rename this is creating a confusion over here if found one then we will increment our ones okay and this we are going to this is the final logic that's it this is a just a three line logic and we are going to repeat this um in both the passes the first pass is going to be from left to right and the second is going to be from right to left okay in the reverse order so let's jump into the coding and see how are we going to solve this so first thing that we require the main two things that we require over here is that our two variables okay first is going to be travel next is going to be our ones okay now let's go through let's make our first fast that is going to be from box from 0 till the size of the string that we have okay here what we are going to check first thing how many ones do we have will add it to travel okay next thing is that at index I will add that I'm sorry we will add how much we have traveled and we will check lastly what if um boxes at index I that is equals to 1 then we have found one so we'll increment one okay after this we have to repeat this again okay in the reverse order so this is going to be boxes the size of our string I greater than till this zeroth index and I minus okay and since the logic is going to be the same let me just copy this and I will simply paste this okay but before submitting this we need to take care of two things which two things the two variables that we have declared right because if you will see here these are outside the for Loop okay so whatever changes we do inside the for Loop that are going to remain as they are okay uh it won't happen like after the for Loop the variables will be converted to zero so we need to return them to 0 because we are going we are making a fresh start with regards to the travel and the number of ones we have encountered to the right side of that particular index okay so for that let me just do let me re initiate this once is equals to zero okay and our code is done okay let me submit this I'm sorry okay now as you can see it has reduced like to 10 ms um we have come from what 360 Ms to 10 ms okay so that's that makes a very huge difference okay now the time complexity for this is going to be Big O of n because technically it's bigger of 2N but since uh you know while um calculating the time complexities we always ignore the constant so this is going to be Big O of n okay so I hope uh you understood this and you like this and you learned something new out of this okay and yeah so that's it for this video uh do let me know if you have any other problems for me to solve from any other platform okay do recommend me your suggestions or the problems that you are facing problem with and I will try to make a detailed video on those problems okay so yeah I will see you in the next one till then keep coding
Minimum Number of Operations to Move All Balls to Each Box
get-maximum-in-generated-array
You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball. In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing so, there may be more than one ball in some boxes. Return an array `answer` of size `n`, where `answer[i]` is the **minimum** number of operations needed to move all the balls to the `ith` box. Each `answer[i]` is calculated considering the **initial** state of the boxes. **Example 1:** **Input:** boxes = "110 " **Output:** \[1,1,3\] **Explanation:** The answer for each box is as follows: 1) First box: you will have to move one ball from the second box to the first box in one operation. 2) Second box: you will have to move one ball from the first box to the second box in one operation. 3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation. **Example 2:** **Input:** boxes = "001011 " **Output:** \[11,8,5,4,3,4\] **Constraints:** * `n == boxes.length` * `1 <= n <= 2000` * `boxes[i]` is either `'0'` or `'1'`.
Try generating the array. Make sure not to fall in the base case of 0.
Array,Dynamic Programming,Simulation
Easy
null
695
solve legal questions 695 max area of a island and this is a median legal question so you're giving er and basically grid and island is a group of ones representing land so one is land connected four directionally horizontal and vertical so you can only go for example like this one here you can only go here left right and down and you can now go diagonally that's why like um this numbers that you have count here is all four directional you may assume all four edges of the grid are surrounded by water the area of an island is number of cells with a value one in the island so basically all ones that connected together are an island retain the maximal area of an island in a grid if there is no island return zero so basically if you look at something like this and this will be your island right so the area is one and this area is one two three four and there's four and one two three four five one two three four and this is an island they are not connected they are not the same island it's because that it's four directionally so there this guy is not connected to this guy at all so here is five and of course the max number is six right yeah so this is this example here and another example that they give us is if it's all zero then you return zero that's simply there's no island at all and this is some constraints here and if you look at here amazon asked this question 18 times in the last six months so i'll say it's a question definitely worth checking out and um if you look at this question it's a very um i feel straightforward definite search problem and you just need to make sure that visit when you count the island right you visit each cell and you want to visit their neighbors and if they're like those zero then you simply don't need to do anything and then after you visit each cell you want to add the cell to the uh hash set that we're going to use so that you will need to visit the same cell again and after that you basically want to run that first search on its neighbor all four directionally and every time you runs it you need to add the data search result to the existing result and let's say you start from this cell here one and here is one right and then you run add a one two on the up down left and right so basically you add all the definition result together and that's the main defer search function and then when you call the default search function you just wanted to go through the entire grid you want to run on the cell that's that has a value as one and also the cell has not been visited already and then you want to basically run that for search but then you want to max you want to get the max output right so you want to run you want to get a max of the result and the deaf research function yep that's the thought process and it's pretty straightforward and i'm going to show you how to do this in code and then i'm going to use a business set to make sure that um to record all the uh cell that the cell the row and column count in the business set so make sure that i don't revisit it again and i'm gonna define typically like how i do it and this is a grid and uh grid zero so just define a graph and here is i'm gonna run the that uh write the main different search function and i'm going to pass two parameters basically is the row and column count any row and column count so first i want to do the condition check is that if r is smaller than zero or like basically if it's out outer bound like c smaller than zero or um r um equal rows or c equal calls or if the rc in visit that i have already visited then i no need to visit it again or grid rc is zero if there are zero i'm definitely not going to count any of them into the island right so totally no need so if they're out of bound or any of this case that i mentioned what should we um what should we do so this function what we wanted to return is the numbers right the max area so in this case if it's out of bound or they're visited already or they're zero we simply want it to return zero in this case right and then after that either way i'm going to add the visit set into all the row and column count into the visit set and then here what we wanted to do is we want to run that first search on the row and columns and basically all neighbors and all four directions so i want to say plus 1 minus one and this one will be plus one and this is minus one and if you think about it and let's say if i started with this guy right i this max area is already one and then i want to add on whatever that is left on the four directions so i actually have to add a one to the result for the cell itself because we're not going to count the grid rc equals zero at all in that case we already returned zero so whatever we're counting here it has to be greater rc equals to one so that one is already an area one so we have to add a one here and then we want to add the four directional neighbors right so the that first search function what i wanted to do is actually return this result if that makes sense so return the data search on all four directions that's basically the main function of the entire area and then i want to say result equal i want to then i'm going to call the different search function when i call the data search function i'm going to assign the max area as the result basically as 0 at the beginning so i'm going to call for r in range of rows i'm basically going to a 4c in range of calls i'm just going to go through every single style in this grid in this entire grid what i'm going to do is that i'm definitely going to call the different search function on the row and column right and then oh actually if grid uh if rc not in visit it has not been visited and also grid r c equals to one i'm gonna write a roundtable search function and then i'm gonna um the result i'm gonna return is a max of the result between the result and the different search function if that makes sense because what i'm trying to do is find out the max every time when i run a different search on each different island right i get a result but i gotta have to update it because they want you to find a max the size max the area so after i run this run through the entire row and column then i can return the result let's see if line 16 oh yeah there's our in uh there's our uh indentation problem here yep it's it retained the result let me just show you the code here yep that is the code and let's submit it okay great so if you think this is helpful please like my video and subscribe to my channel and i'll see you soon with more legal questions okay bye
Max Area of Island
max-area-of-island
You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The **area** of an island is the number of cells with a value `1` in the island. Return _the maximum **area** of an island in_ `grid`. If there is no island, return `0`. **Example 1:** **Input:** grid = \[\[0,0,1,0,0,0,0,1,0,0,0,0,0\],\[0,0,0,0,0,0,0,1,1,1,0,0,0\],\[0,1,1,0,1,0,0,0,0,0,0,0,0\],\[0,1,0,0,1,1,0,0,1,0,1,0,0\],\[0,1,0,0,1,1,0,0,1,1,1,0,0\],\[0,0,0,0,0,0,0,0,0,0,1,0,0\],\[0,0,0,0,0,0,0,1,1,1,0,0,0\],\[0,0,0,0,0,0,0,1,1,0,0,0,0\]\] **Output:** 6 **Explanation:** The answer is not 11, because the island must be connected 4-directionally. **Example 2:** **Input:** grid = \[\[0,0,0,0,0,0,0,0\]\] **Output:** 0 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 50` * `grid[i][j]` is either `0` or `1`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,463,1845,2206
240
Hello friends welcome to my channel Cod destination so as we are continuing this challenge one code one day and we are taking the topic P resarch algorithm so we already discussed I think three variant of binary search in previous days so today uh topic we are choosing is the 2D array basically we will take the question on like 2D array now how we can apply the binary search on the 2D array so this is the last question of binary search of the binary search algorithm Series so today we are considering this question to 40 question number name search uh 2D Matrix so basically we have given this uh Matrix which is basically sorted in the rowwise and column wise manner because we can see for the first row is sorted from left to right and the First Column is sorted from top to down so basically uh this array is sorted if you take any element like any row so that row is sorted from left to right and if you consider any column so that column is uh sorted in ascending order from top to down so basically we have given this array this Matrix basically 2D array and Target we have to find like we have to return whether the target is present or available in The Matrix or not if it is available then we have to return true otherwise false so explanation is very simple so maybe we can discuss how we can approach that problem like uh as like we approach in the 1D array so I already draw the diagram for explanation so here we can see first uh like we will connect the 1D approach to in the 2D approach basically so first we will think how we apply binary search in the 1D approach then we will try to connect the same uh same intuition like almost same intuition on the 2D like array basically how we can think that approach so basically in first in the 1D array what we generally did we just Define the boundary like because we know it is 1D so just it is one dimensional so just I took the boundary element like this zero zeroth Element last element like here uh like it is a normal binary search what we did I just explain why we did so we just take the boundary uh from I and jth and we generally found the middle point because in the uh 1D Direction like 1D array basically we prer uh to find the mid middle only because after finding the middle we generally compare this Middle with the target like suppose in this case the target is nine so we compare this middle element six with nine and after the compar comparison we decide which half we can like uh ignore either this half we can ignore or this half we can ignore and once we ignore that half we can move uh our like search uh search range in the next half so this is the approach basically we discussed so I will just connect that approach the 2D array how we can think so first of all we Define the range using I and G value but in 2D array like we know it is containing row and column so basically and for a for like defining boundary we have four option like this is the first this is the second and this is the third and this is the fourth so we have fourth option in this case uh for defining the like boundary like in the first one D we Define generally boundary like I and JS but in this case uh from where we can start we have to think so suppose uh I take I and J here I here and J here if I think like that then whether it will be good or not you can decide suppose I take this I here uh and this J here so like why I choose I and J here like in the ond case because uh like we can see like if you choose I uh on the Zero index so after that all the element is increasing and if I check choose the J element at the last so that before that all the element is decreasing so this is the property is following in the 1D array so we will choose the same boundary which is following this type of property so we can think if I choose this ith element so like in this case in this direction it is increasing and in this direction also it is increasing so it is sure that this is not a good uh like boundary for the ath because for both Direction it is increasing okay and we have to think this in the 2D manner because in the 1D man in the 1D manner we are just One Direction so we just think whether it increasing or not but in this case we have to think both rows and column so in this case we can see like it is increasing like from left to right and from top to down also it is increasing and from J index like you can see it is decreasing in this direction and it is also decreasing in this direction so basically uh in the 1D array uh we just Define this m and with the m we can say that uh we can ignore some of the part but in this case suppose I choose this uh this boundary so can I ignore any part suppose in this case my target is six and I choose uh like choose to start this from here like there are four possibility but suppose I choose from here to start our searching so like we generally compare this one element uh with the six so I saw this one is less than six but with that uh result we can't be sure that uh whether we have to move that side or we have to move that side because uh there are two possibility either we can move in the row direction or in the column Direction but with this conclusion like if you compare the one with the six like one is less than six so we can't sure that we have to move in the row direction or the column Direction because both direction are increasing so we are not sure so definitely it is not a good uh point to start so the second point is um this one suppose I choose this 10 okay so this 10 I just compare like we can see in that in the direction it is uh increasing but in this direction it is decreasing so basically it is following that type of property in the like we follow in the 1D like from I to like left to right it is increasing and right to left it is decreasing so in the One Direction it is increasing in this case and in the One Direction it is decreasing that is just intuition but we can uh think logically as well like if you compare this 10 with a six then what is the result this 10 is greater than six okay and we know if it this 10 is greater than six and all the it is increasing the this direction so all the element like 13 14 and 17 is definitely greater than six so we have only one option we can just go like uh bottom to top so in this case like we are just ignoring one uh one whole uh Row in that case correct so in this case like we can ignore Row one row so it is it means it is the good point to start from here because in like in 1D ARR generally we just ignore half part but in the 2D array either we can ignore whole row or whole column so in which case uh like in all the cases in which we can ignore either row or column that is a good place to start so this is the first place from where we can start so what is the second place maybe we can think like suppose I start from I my I pointer is here and J pointer is here I am starting from this boundary okay so we can see like in this point in from right to left it is decreasing and from bottom to top it is also decreasing so basically suppose I choose this 17 and I will compare this 17 with six so 17 is greater than six it means we have to choose the less value but in the both cases we are choosing the like we are decreasing so we can't say that whether uh we have to move uh top or whether we have to move left side so from this index we are not sure so that is also not good uh index to start suppose I choose this i j and here so suppose I choose this element and we can see from uh right to left it is decreasing okay it is decreasing and from top to bottom it is increasing so it is also a good uh point because for both Direction it one for One Direction it is decreasing and for One Direction it is increasing like in the 1D for One Direction it is uh increasing and for One Direction it is decreasing so whether this Behavior have that index is good but we can also think logically like this 11th Element 11 element is greater than six so we are sure that all the column like basically all this column is greater than six because it is increasing from top to bottom so just we can ignore this whole uh column in that case and we can just uh move and the left side so like if you are choosing this index so we are like we after comparison we are sure that we can ignore whole a row but we are if we are choosing this index like this uh Corner uh like this boundary then we are sure that we after comparison we can sure that we can ignore all the uh column so basically there are two correct point to start boundary like first is this one either we can start from this Index this index or we can start from this index so that two index is good because this is following the property uh which follow in the 1D array like in 1D when we Define the boundary with I so we can see some observation like from left to right it is increasing and from right to left it is decreasing so this property should be followed uh when uh we choose any boundary case uh in this 2D array so same approach we will find and uh we will approach like how we can solve that so something I uh some observation I can show you here like when suppose in this case that two of two uh cases we can choose so like in my solution maybe I am choosing this one this second case I start from here so what we will do generally like we will just take this element okay we will compare with Target suppose in my case the target is this one this six is my target which we have to get so I just compare this 11 with six so L is greater than six so I just ignore all this uh column I just move my J from here so next I will search this element again I will s like compare this seven with six so seven is greater than six it means all the uh column again I will ignore so I will just go left side so I will just decrease my JF value so I will start from here again I will compare this four with six so in this case four is lesser than six so it is sure that all the element before that is less because in that case like it is decreasing so all the like all the uh column like here all the things is decreasing here so basically all the column in this case this one only remaining so I will just ignore that and I will move my I pointer in the next element so I will just start from here so I will again compare this five with six so five is less than again I will ignore all the uh like column value just before that and I will just move my row value so once I reach I will just return that so same approach I will follow and in the code maybe uh once I write the code then you can connect with logic Okay so what we did I just defined my boundary with I so my I is suppose row defining from zero and J is my Matrix the column okay so I just Define my uh like a starting point boundary so I def I choose this boundary this case like we have two option this one or this one but we are choosing this one in my case okay and yeah what is the condition to stop the uh like this check like I because generally we are just comparing and we are moving the J and I so we are starting here so my like J value is showing the column value and I value is showing the row value so J will move from left to right it means still it will run till it will not go the out of the boundary it means till it is greater than or equal to zero and I is moving from top to down it means it will be move till it is less than or equal to the column size okay so I will Define that boundary in while loop like we'll did in the binary search with 1 D array so my I will greater than or equal to zero uh no sorry j because J is depend in the column and I is less than or equal to okay Matrix Dot length it is a row value minus one so because it Z bit indexing so this is my boundary case so I will find my element here so I will find my element suppose I and jth element okay so what is the case if my element is equal to Target so in that case I found so I will directly return true here and uh if my element is greater than Target so in that case what we can ignore basically my element is greater than Target so if 11 is here 11 is greater than Target like greater than six in this case basically all the um column I can ignore so basically I will move my Z pointer because which is represent the column J minus and if the opposite case it means my element is less than so I will just move my uh I pointer ++ so in this way I can move my both the ++ so in this way I can move my both the ++ so in this way I can move my both the pointers and once it is reach at that element which is equal to Target that case it will return the true and at the last if I didn't got the element I will turn the false here so I think that's it is very simple let me run it yeah so both the test Cas passes let me submit it again yeah it accepted it taking 5 millisecond be 99.9 of Ja so uh you can connect this be 99.9 of Ja so uh you can connect this be 99.9 of Ja so uh you can connect this code with the logic like uh as I discussed already like uh from first we can think from where we can start like I can just write here first we decide our boundary I and J value and I value how we can decide like I compare with uh this 1D aray if I Define I so like for One Direction it is increasing and One Direction it is decreasing so on this behalf we can decide like for One Direction it is increasing and for One Direction it is decreasing so this is uh both like two basically boundary like zero and if my suppose row this is the row size and into M um like Matrix so this will either you can it can start zero row and M minus one column this is first case or it is uh n minus one row or zero column so in both case we can start both boundary which is feasible which is following this property and the second case we are just in the on we find the middle pointer and with by comparing the middle element we can ignore the either one half or this half but in this case uh this is stud array so we can ignore one row or one column so basically we can compare this itself this element like this 11 with the Target and we can by comparison we can show that if it is greater then it means it is ascending order sorted so all the element will be greater so we can one case we can ignore either like uh whole row or whole column so we will think either ignore whole row or whole column so this two case we can think only and we can apply the algorithm directly here so I hope you understood the intuition and how we solve that question so if I'm talking about the time complexity so we can see here like this Loop is moving from J like uh greater than zero and I less than Matrix uh minus one so in the worst case I can think if you visualize this Matrix like we start from here and suppose uh in the worst case we can think like this is our Matrix suppose okay and suppose I start here and my target is supposed in the worst case it is here okay so this is the worst case when we will like uh run our uh like search algorithm like it will take like more time so what we are generally doing like for one comparison we are just ignoring whole row or whole column so basically uh like basically either we are moving this direction here to here okay in the worst case or we are moving this here to here so in both cases uh it is just comparing like checking uh total how many operation we it is taking M plus n because in every check we are just ignoring whole column suppose in this case we are ignoring this column again we check and we ignore whole column then again we check then again we ignore this whole row then we are basically first we are we was moving this direction then we generally we shift in this direction so in the worst case either we can start from this corner to move whole uh like column or we can start from here and whole row so basically in worse case we are taking this M plus n uh operation so this is M plus n if where m is row and N is column basically for the Matrix and the time complexity will be um B go of m+ n where the m and is um B go of m+ n where the m and is um B go of m+ n where the m and is the row and column and if I'm talking about space complexity there are no space we are using so it is a constant space operation so it is a uh B of M plus n and B of one space complexity solution so I hope you understood the intuition and how we build the logic which by comparing the 1D array logic and how we uh Implement in the code so if you like my video please uh like on the YouTube and share it and also subscribe for future videos thank you
Search a 2D Matrix II
search-a-2d-matrix-ii
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: * Integers in each row are sorted in ascending from left to right. * Integers in each column are sorted in ascending from top to bottom. **Example 1:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5 **Output:** true **Example 2:** **Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= n, m <= 300` * `-109 <= matrix[i][j] <= 109` * All the integers in each row are **sorted** in ascending order. * All the integers in each column are **sorted** in ascending order. * `-109 <= target <= 109`
null
Array,Binary Search,Divide and Conquer,Matrix
Medium
74
374
hi today we'll talk about another binary search question this question is very simple and interesting that says guess number higher or lower so it's a guess game so we are going to play a guess game and the game is as follows i will pick a number from 1 to n and you have to guess which number i picked so every time you guess wrong i will tell you whether the number i picked is higher or lower than your guess so there is a predefined api guess and what and whatever i have guessed i will call this api and it will give me answer minus 1 or 0. so if the number i picked is less than the number you guessed you will get -1 from this api you will get -1 from this api you will get -1 from this api and if my peak number is greater than your guess number or you will get one and if the peak number is exactly equal to what you have guessed you will get zero very interesting pretty simple let's see how we can solve and why we can apply binary search all right so this question is pretty simple it is about a guess game i will pick some number which is from one two and range and you have to guess some number which is also from one to end range and when you will you guess some number you will call an api guess num that will return three things minus one and zero if the number you guessed is greater than my peak number you will get minus one so if my pegged number is smaller than the number you have guessed you'll get -1 guessed you'll get -1 guessed you'll get -1 if the number i have picked is greater than the number you have guessed you'll get one and in case peaked number is equal to your number you will get zero now we can clearly see that one to n range is sorted we can use this the first thing is fine and second we do some comparison and that comparison is being done by this api and pretty simple we can use binary search just like the same we will take one to end range one to n we will take a left pointer we will take a right pointer and that will give guess we will call we'll take the mid and we will call this guess api for this mate and that will tell minus one and zero and we will take the decision either we have to go left or we have to go right so let's see how we can code this question hi so we have already discussed we can solve this question using binary search so we will use binary search and we will say left pointer should start from one and end pointer should be at n so that will be our expected binary search and in this binding search we can see that will be the left end and right would be our end and we were expecting mid as an as a return type from this one search now the first thing we can see that the two player is not going to pick anything outside from one to end range so there is no need for base condition so we can simply say ball num and that will be left plus right minus left divide by two and we will call this api guess and we say that's our number num we will pattern match here and we will say if this api returned a zero so it means our number is exactly equal to the picked number so we will say that is the answer if this api returned 1 so it means the number which was being picked is greater than the number what we have guessed so in that case we have to look at the right side so we will say by search made plus one and num and right will be as it is in case it returns minus one we will we have to look on the left side because our the peg number is smaller than the number what we have guessed so left will remain here and mate minus one and that's it let's run the code oh we picked this number made how to write num now we run the code again and that works thanks
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
143
hey guys welcome back to another leak code problem solving tutorial and in this tutorial I'm going to be showing you guys how to solve leak code question 143 asking us to reorder this list in this specific order uh a link list and basically we start from the front go to the end go to here and we just sort of like spiderweb crawl into the middle so I'm going to show you guys the algorithm which we need to use in this kind of in this problem and yeah so we start off with this link list starting off at mode number one and the first thing we want to do is we want to get to the middle of a list because what we want to do is we want to get the second half of the list reverse it to get 4 three and then we want to sort of merge these lists together like this so we end up 1 4 2 3 like that so that's the idea and first step is get to the center of the list and to do this we use a fast and slow pointer so if I just call these fast and slow essentially the fast pointer is going to move two steps every time the slow pointer moves one so we start fast up pointed to one and slow is always point also point to one now fast moves two whereas slow only moves one like this and then we're going to say well our Brak statement for the fast is going to be if the current node is none like if we were here all the next is done neither of which is true so we go back and we add one more and we also add one more to slow to bring us here at this point fast is none so we break the loop and that leaves us on number three which is the center now you can imagine if uh there was a node here five well fast would still break because our break condition is whether fast is none or fast. next is none and fast. next is equal to none so we'd still break here which means if this was an if there was an odd number of items we'd get the exact middle if there's an even then we get the higher midle because when isn't even there's two middle items technically but we'll get the higher one which is good because it's the one we want right like we want this half of the list we don't want uh the slow one to stop here and then we reverse this cuz we want the list to be of even size all right so now that we've done that we can take we can sort of split them apart so we can take the fast or we can just start with the original list so we'll have one two and notice that slow is also going to be here so we have 1 2 3 4 as the original list and slow is currently at this index so this is what slow sees we see slow only has three and four like this and what we want to do is we want to reverse slow this is pretty easy algorithm we can just do something like store slow in we'll store all this stuff in this temp variable so this is the temp and then slow is going to be the current and then what we do is we can just simply uh add slow to the temp so each time we add yeah we add slow to the end of temp and then increment slow like so that makes sense so just a basic reverse list formula reverse list reverse link list algorithm and then we end up with these are our two lists so we're going to have one two three and I'm pretty sure if we use uh this algorithm it's also just going to get rid of everything after this three which is fine so we'll just do one two three that's what we start with and slow is going to be 43 and what we now want to do is we start at 10 we start the first Ty been current and we're just going to repeat until we're just going to keep linking to the opposite list until slow. next is equal to null because Slow's almost always going to be limiting factor this is always going to have at least one or two more so slow is always a limiting factor and that's how we end up with using slow as a limiting factor because now when this links over to here this is going to be none and we end the list and yeah now this has completely been disregarded so we just return this which is the answer so hopefully that made sense this is pretty standard just using standard algorithms but pairing them a special way and there's multiple steps to this program so let's get implemented we get a list node okay so first thing we're going to do is find middle of list using slow and fast Point remember you can't just find the middle like by index cuz this is a link list not a regular list so we'll step fast and slow to initially both be the head node and then our break condition is going to be well while fast is okay yeah so while fast is not equal to none or no and fast is fast. next is not equal to n like so there's our break condition and for each iteration we just increment by increment fast by two and increment slow by one and we can actually Force unwrap this because slow is always going to be behind fast so as long as fast exists slow is definitely going to exist as well so there we go now slow points to Middle node we want to reverse slow I've already made a video of this in the past but with just going to use a link list reverse link list algorithm so if this is the node we're given we need to split this into two parts we'll do the storage which is slow. next so storage essentially store in all the items left so storage is slow. next and we're going to uh one sec can I just for some reps no okay let me just I think if I do something like this then never mind we'll just have to keep Force unwrapping it so yeah we set the storage to be this and then we just complet disregard that from slow just to so now slow is just on its own and we have storage and what we're going to do is let me think okay yeah so we want to repeat while storage is notal to null so while there are still items left in storage I think it would be easier if I choose a bigger example so let's just say we're trying to reverse this entire list we'd have this as the original thing and then storage is all of this and essentially we're just trying to flip these pointers so we'll do storage is point into this node we do storage we have to but if we flip this pointer over here then we need to store that somewhere else so we use a temp variable so con temp equals storage. next then we set storage. next equals to slow like so this points over to there and then we set slow equals to storage so we've created this and then we just want to reset to make this slow now and reset to make storage equal to 10 like so here's simple reverse algorithm now slow is reversed so once we have something like this uh we're going to have the initial head node and we're going to have the slow node and we now need to use the sort of merge algorithm of them so yep so let's say we're here and let me just let me make this a bit clearer do this again so this is our head and this is what our slow looks like so our head starts here and we move this over to there so now we've got this as a list but we need to store this somewhere else so we don't lose it and then once we've done that we now here we point over to here we now we need to store this and then we're here we point this over to here and we need to store this and I guess what we can do is we can just our break statement is going to be while head. next is not equal to no so because once we get here we don't want to add this cuz this is going to be a duplicate but essentially we're checking if the next item in head is null that means that there's no more items left to add and to add this we can just do just perform a swap so we just use head do next and temp we're basically going to swap them I can make this a bit clearer by using a temp variable so now head. next we're pointing this to the temp variable and we need to make sure we store the remaining heads in this temp so we set temp equals to head. next like so there we go so there's the algorithm it's a bit confusing at first but this is oh don't have to return anything cuz we're modifying head in placey head in place so don't turn anything and you can see we're essentially just performing a merge algorithm to interlace these two lists and we're going to break when this head is got no more elements so yeah this was how we solve this question let's see what we get and let's check if there's any kind of Errors first okay um we get a time limit exceeded right that's unfortunate and let's see what's going on here so while pass is not equal to null okay so let's do a bit of testing because this is a bit hard to get all the parties right this is a pretty annoying off by one sort of situation but it's all right so let's just Define a list as this and let's see what happens when we try and call this function we this um what's going on here expected oh I see need to finish this off okay there we go all right so let's see where the problem is being caused so I'm going to print here to check if we make it past this stage that's just run reorder oh reorder this sl. TS okay so we get there now let's see if we get here all right we get there so I'm assuming the issue is here right oh it's not even here oh no we didn't okay yeah so the issue is in here in the mergin of the list so let's attempt to fix that okay yeah so I think we don't have to use head dot next okay so the issue is because when we perform this swap head. next is here so head is actually pointing here um but temp is here so instead of checking whether head. next is null I think what we can do is we can just check while temp is to n hopefully this solves our issue nope okay uh let's have a look at our variables how they're stored so let's print what temp looks like and console.log what head looks and console.log what head looks and console.log what head looks like okay so this is what head is yeah exactly what we expect and this is what temp is exactly what we expect as well okay and let's just think about this algorithm a bit more carefully since it is a bit confusing to implement properly so we're going to get one two three like so 4 three and we want to interlace them like this so interlace that store that in temp then interlace that and store this in temp and then if we interlace this so head is currently there if we interlace this now store this in ter H okay yeah so I think head do null I think set checking if head is not equal to no was the correct move so I'm not sure why it hasn't worked let's just console load let's just see what's happening with the head throughout this let just okay so ah okay we forgot a crucial step we set headon next is equal to this is equal to Temp and we set we perform a swap but then we also need to remember to increment head. next so we've done this and then we just need to increment head to head. net like so here we go okay that should do it so we forgot the most important step of just moving head along incrementing it to the next counter sorry for that slight blunder but now let's check if this works so right okay output so we get 143 not what we're looking for and I think here I can just check if temp is equal to N I think that work so let's just console like this uh oh it appears to be circular okay if I do that so it goes one for that's quite weird wonder if that helps okay there we go so I guess it's a bit confusing because when we do this everything store differently we need to execute the swap first and then increment there we go okay so yeah you can see how link list can be a bit annoying sometimes hopefully that's all we need and okay yeah there we go so that was quite a long solution definitely could have been shorter if I didn't make that mistake but yeah these 83% so decent solution we're basically 83% so decent solution we're basically 83% so decent solution we're basically finding a middle item reversing that and then merging them together thanks for watching and I'll see you guys in future tutorial bye
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
703
everyone welcome back and let's write some more neat code today so today let's solve the problem k the largest element in a stream and it's marked as an easy question but i definitely feel that it's more of a medium and maybe that's why many people disliked it but we are told to design a class to find the kth largest element in a stream of numbers so stream basically means that we could continue to add numbers to the list of numbers after we do that we still have to find the kth largest element now that we've added more numbers to it and they say that the kth largest element is the case largest in the sorted order not distinct and what they mean by that is basically that if we had you know this uh list of numbers and k equals three meaning we want the third largest number if we look at the distinct values we'd say okay three is the largest two is the second largest and one is the third largest but they say we want to return the case largest in sorted order meaning this is the first largest this is the second largest and this is the third largest so we return two we're not just looking at distinct elements if we have multiple copies we include those as well the good thing is we only need to implement two functions one is the constructor where we'll be given the parameter k that we can store and an initial list of numbers and this list of numbers it could be at least k elements or it could be less than k elements or it could be more than k elements so that's something we're gonna have to take care of when we do write out the code uh but the second function is the add function where we can actually add a number to the stream of data and this function is also going to return the new kth largest element every time we call it so they do tell us that whenever we call this function we are guaranteed to have at least k elements in the stream of data so that's good even though we might not have k elements when we initialize it we will have k elements when we call the add function so now the question is how can we efficiently solve this problem well suppose we were given this input right in our constructor this array and k equals three of course the intuitive approach is to sort the input so that we can uh you know look through and find the kth largest element a little bit faster right in the original array we could just scan through the entire input and that'd be o of n to find the kth largest but when the array is sorted though we can of course use binary search which will run in log n time but the problem is if we want to insert a new value for example we want to run add on the value three well yeah we can run binary search to add the number as well we can find where to insert it but when you insert in the middle of an array it's a linear time operation big o of n so the question is there a better approach is there a different data structure we can use and yes there actually is and the data structure that's going to help us the most in this case is a min heap and we are going to require it to be of size k and let me tell you why well first of all a heap is a data structure if you haven't heard of it that has a somewhat sorted property we can add and pop elements from the min heap in log n time we can also get the minimum value of the min heap in big o of one time obviously this is a little bit better than an array especially an unsorted array like we are given in the input but the question is why are we going to require it to be of size k and why are we using a min heap rather than a max heap well one thing we are going to use to our advantage is that we're only going to be adding elements to our stream of data we're never really going to be removing anything so in this example we're given four numbers but we only need a min heap of size k because we only need the k largest values from the array in this case it's four five and three why is that why do we never need the two because we want the third largest value this is the largest this is the second largest this is the third largest so we have three numbers that are bigger than two is two ever going to be the third largest value in our stream of data it's never going to be because we're never going to remove any of these elements right we might add elements we might add a value like six if we add this six value then we don't want to include this f this four anymore then we only want to keep track of these three numbers six five and eight and now this is going to be the third largest number five is going to be the third largest number two is never going to be included in this group two is never going to be in our min heap of size k if we added a small element to our stream like a 1 well we don't care about a 1. now in terms of the code and how we're going to implement this we're going to have a min heap of size k first of all what we're going to do to get this heap is we're going to take this entire input and add it to the min heap right so suppose we have four five and eight in our min heap now we're going to do a while loop while the size of the heap is greater than k we're gonna pop the minimum value in this case the minimum is 2 we're going to pop it thankfully now our heap is size k exactly so we don't need to continue to pop elements and remember our min heap we can get the minimum value and since we have these are the three largest values we want the third largest which is going to be the minimum among all of these i hope now you can see why we're using a min heap because we can get the minimum in o of one time but the add function over here requires us to add a value to our stream of data so for example suppose we want to run add 3 well how do we know if 3 is included among our k largest values well the easiest way to do it there's multiple ways but the easiest is just to take that 3 and add it to our min heap so now we have 4 values in our min heap and we added it in log n time now we want to pop the minimum value from this min heat because we want the third largest value we have four values in the heap let's pop the smallest one which is three we can do that again in login time and now we want to know okay among the remaining what's the smallest value again it's four so as you can see we can do the add function in log n time how many times are we going to run the law in the add function who knows let's call it m and then this is going to be the overall time complexity of add if we count all the function calls that are made to it now in terms of our constructor function actually generating this entire heap it's potentially going to be n log n in the worst case reason being is we can actually initialize the heap like this is our input data we can turn it into a heap in o of n time that's not too bad but then remember when we started with the array we had this two right we have to keep popping elements until we only have k elements remaining so a pop function is gonna be log n time how many times are we gonna have to pop potentially n minus k times so this is the overall time complexity k could be really small it could be one so you know worst case we could have n log n for our constructor but the add function is just going to be log n that's a big improvement over the first solution we came up with which was uh end time when we were just using a array structure so heaps definitely help us out a lot now we can go ahead and code this up now let's code it up first thing we're going to do is the constructor you can see i have one comment that hopefully will help guide us in the code so we can create a member variable with the self keyword in python so first we want to create our min heap and we also want to have another member variable for k which is you know going to be the size of that heap or at least the desired size of it so min heap initially can just be assigned to nums and our k is just going to be assigned to the input parameter k we want to turn this into a heap right now it's just a array we can turn it into a heap in python like this heap q dot heapify keepifying this array into a min heap that will create the sorted property it will run in big o of n time but it could be that it has more than k element so while the length of self.min he is while the length of self.min he is while the length of self.min he is greater than k we can go ahead and pop from the min heap we can do that with heap q dot heap pop on the min heap data structure and don't forget the keyword self since it's a member variable so the constructor isn't too bad now let's do our add function there's multiple ways you could write it but the easiest way is just to go ahead and add this value to our min heap regardless of what it is if it's too big or if it's too small who cares we can go ahead and say heap q dot this value and then we're gonna pop the smallest value which might end up being this value or it might end up being a different value who knows let's go ahead and just pop it and our heap data structure will actually take care of that for us anyway but there's actually just one edge case that you might miss remember our heap might be initialized with less than k elements this loop will execute if it has more than k elements which is good but what if it has less than k elements then if we add a value to the heap we don't want to pop from the heap if it has less than k elements or even equal to k elements we only want to pop if the length of the min heap is greater than k elements so if it's greater than k that's when we want to pop from the min heap but once we've done that we make sure our heap is valid it does have k elements we're guaranteed that when the add function runs so now we just want to return the minimum from our min heap and the way heaps are implemented the minimum value will always be stored in the zeroth index so we can just go ahead and return this and don't be dumb like me we forgot to when we're referencing min heap and the k value we want to make sure we reference it as a member variable so let's use the keyword self.min heap okay it looks good to me self.min heap okay it looks good to me self.min heap okay it looks good to me let's run it to make sure that it works and as you can see on the left yes it does work and it's about as efficient as we can get so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Kth Largest Element in a Stream
kth-largest-element-in-a-stream
Design a class to find the `kth` largest element in a stream. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. Implement `KthLargest` class: * `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`. * `int add(int val)` Appends the integer `val` to the stream and returns the element representing the `kth` largest element in the stream. **Example 1:** **Input** \[ "KthLargest ", "add ", "add ", "add ", "add ", "add "\] \[\[3, \[4, 5, 8, 2\]\], \[3\], \[5\], \[10\], \[9\], \[4\]\] **Output** \[null, 4, 5, 5, 8, 8\] **Explanation** KthLargest kthLargest = new KthLargest(3, \[4, 5, 8, 2\]); kthLargest.add(3); // return 4 kthLargest.add(5); // return 5 kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8 **Constraints:** * `1 <= k <= 104` * `0 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `-104 <= val <= 104` * At most `104` calls will be made to `add`. * It is guaranteed that there will be at least `k` elements in the array when you search for the `kth` element.
null
null
Easy
null
721
hey everybody this is larry this is day 29 of the november league daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about this problem let me help you do how you know if you had any issue of this one today's problem is 721 accounts merge okay we'll see what this problem is i am usually solving these lives so if it's a little bit slow just fast forward whatever you need to do okay so you're given accounts and accounts of i is a list of strings okay two if that's the same some common email above account so if two accounts are the same name they may belong to different people as they could what okay well they count definite say what okay so yes okay let me try to read it again okay so merging the account we turn the first element okay so you have this account and then okay you like to merge if there's some gmail that is the same in this case this is here okay i'm gonna just combine these okay and it's in sorted order okay um so the first thing that i would think about is maybe some sort of union fine type thing um and then you know doing a lookup on it even if they have different name can there be two joints oh there can be two john's okay um okay right now i'm just thinking about it complexity and how to do it but each one can only have at most of 10 accounts so it's not actually that bad um oh sorry no that's the length of an account yeah i know you know uh yeah you trying to have only 10 accounts or you maybe do it greedy or not really naive um it'll probably be too slow but it'll be almost fast enough not really but almost um basically because that would be a thousand squared times 10 squared times 30 so that's like three billion or something like that um but like within the realms of some optimization um yeah i mean the thing that i would think about is maybe just hashing it um i think hashing is a very basic thing as well um yeah okay and i think we just need hashing is just give us a lookup table um and i think that will be fine so let's so this is becomes a more of a implementation problem and i don't think it'll be too difficult um in terms of you know we just have to kind of do it deliberately and make sure every step of the way we're deliberate about um how long like how much time that we get to spend in terms of uh complexity right um okay so let's look so for each account um okay so for name there's such a naming things that's hard for name let's just say acts in accounts um let's actually enumerate this as well so that we get an index of this right um okay so what do we want so for each account we want to map each account to the index we don't actually really care about the name though we do need it at some point in the future right yeah maybe we could do it a couple of ways so i don't know we'll see for a sec um oh actually this is the format is a little bit different okay so actually this is a little bit wrong um maybe uh okay so name is inves how did i do this is it someone like this i forget how you do like the rest in here or something i think that's right it's been a while since i used syntax like this but okay so that's right so that is the syntax um though of course you could have also just win something more deliberately like this and or something like that right it's the same idea um doesn't really matter um okay so then now for emails i guess this is emails right so then for email in emails we just have a lookup table right uh hey let's see how do we want to think about the lookup table okay i mean we just have a lookup table and then we check if it exists if it already exists then we should merge it um i wonder if there's anything about like different periods or something like that but i guess not um so basically the idea here is if email in lookup um hmm let's see i just want to make sure i'm very deliberate about it so okay if email is not in looked up then obviously we'll just do lookup of email as you go to index else what we want to do is do something like we want a union um lookups of email and index right we're going to put them in the same union and that's not that bad yeah and then now of course we have to implement union fine so i just have a parent yes you go to we could use the away version of it and this is very basic union fine stuff uh i like to i don't know i do the same thing mostly every time so yeah oops that's right as i said i realized i just got that wrong that'd been annoying to debug but uh yeah okay right and that then after that we union uh the two indexes because they're the same and that's pretty much the idea that's pretty much it really um we might we have to do some sorting at the end but i think that's should be good enough um and then but all the accounts are the same name okay that's good i was wondering how to do the typewriter on accounts but uh but yeah and then now we just do for i to n if you find if i is equal to i that means that this is the root of the union fine then um then okay actually let's put enter we have this weird array format so if that's the case we first get the name which is accounts of i sub zero um and then we get the rest of the emails right um i guess we don't really put in the emails yet okay fine that's uh i did it in a maybe sub-optimal order but in a maybe sub-optimal order but in a maybe sub-optimal order but okay let's just have a emails away right and then how do we want to write this part we'll need this later anyway so i'll put in the back but basically we want to wipe this loop again so i guess we just do it um i guess we have to d2 but hmm yeah okay fine um okay so in this case what do we want um okay i mean it's just annoying to write i'm just trying to think about what is the cleanest way to write it a little bit but maybe that's fine maybe we just do it again um and maybe there's a better way to clean this um but you know maybe later uh okay and then now we do okay so let's just say we have emails um of let's just put in a dictionary a hash table uh we want it to be a set right so then we want for email in emails um oh what the uh naming things is hard so all emails say all emails sub index uh stuff you find of index whoops almost messed up there uh add emails right add email um and this could actually be yeah i mean that's good enough for now i mean we could clean that up a little bit to be making one line or something but yeah and now we just do the same thing but all emails up i um yeah so we just of course put in this sorted set but that's fine um i think maybe i might have to convert it to list i don't remember oh uh wait what am i doing maybe i can actually just write something like that right let's put this down where we use it and then let's give it some let's give it a spin and then see if that is okay oh i might have to oh no i did saw it i was gonna say i might have to sort it okay so that looks good um so i think i'm happy to just give it a submit i don't know if there are any edge cases that i might not have considered um but yeah let's just give us a minute done i haven't done this farm before apparently one of the rare ones haven't done this month i mean i don't think i don't want to sign the problems right so okay so yeah today's streak is 608 um get accepted yay um let's see what's the complexity right uh i mean it's gonna be linear in the size of the input um the reason i said that is because i don't really have you know because that for i mean we can go and that's assuming that you find a new union is constant which you know there's some nuance there i'm not going to get into it now um but yeah this is a double loop but if you think about it every gmail that's in the original list it gets processed once so this is linear because every email gets processed one and this is linear because every email gets processed once and this is an over one operation um and then here again oh there is a sorting here i forgot so maybe this isn't linear whoops um so then this is i guess this is roughly speaking analog and then um because in the worst case for example if all the emails all belong to one person we would have to sort it so that's gonna be n log n um i was totally wrong about linear i just missed this part actually but i forgot about it um yeah uh so and in terms of space this is also this is actually linear because we just you know there's one entry for each uh email um in the lookup and there's one entry per account in parent so this is going to be linear in the sense of o of n plus u where u is the number of emails and this number of counts or something like that um but yeah uh that's all i have for this one i believe uh let me know what you think yeah maybe that's what i have with this one i mean it's pretty straight forward once you realize what you want to do or maybe there's an easier way to do it um with respect to we maybe you don't have to do a union fine maybe you could just create the graph or something like that and then walk the graph or something but i don't know it goes because you could always walk the graph later and stop doing it live in union um but i don't know let me know what you think let me know how you did um that's all i have uh so stay good stay healthy to good mental health there's only a couple of days left so let's finish this month i'll see you later and take care bye
Accounts Merge
accounts-merge
Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**. **Example 1:** **Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\] **Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\] **Explanation:** The first and second John's are the same person as they have the common email "[email protected] ". The third John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\], \['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted. **Example 2:** **Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\] **Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\] **Constraints:** * `1 <= accounts.length <= 1000` * `2 <= accounts[i].length <= 10` * `1 <= accounts[i][j].length <= 30` * `accounts[i][0]` consists of English letters. * `accounts[i][j] (for j > 0)` is a valid email.
For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph.
Array,String,Depth-First Search,Breadth-First Search,Union Find
Medium
684,734,737
646
hello everyone so in this video let us talk about one more problem from lead code the problem name is maximum length of pair chain so you are given that you have an array of n pairs now the pair consists of left of i and knight of five so that is consisting of a pair and the left device is always less than the right of phi and what you'll actually have to find out is a continuous chain of pairs such that they are not intersecting and they are continuous okay and you have to find out the longest chain you can form from all the pairs you have in this pair setting that's not a problem so this problem is actually similar to a problem i've already made on my channel that is the minimum number of arrows required to burst the balloons so i'll also link that particular video in the i button you can check it out as well so 95 of the problem is almost same okay so you can check out that problem as well if you want to practice more such problems but moving on to such this problem as well so what you actually have to find out is that you have different peers okay if i just draw it out just a second sorry move this out so what you can see is that i have different pairs okay let's say this is a different like a very last number line they're different pairs so let's say one pair start from let's see if this point at this point so up here you can see that it start from left to five and then end it right of five okay so they are different like here so let's say appear start from two and end at like five other players let's start from let's say four and then eight one pier starts at least nine and that let's say level okay the different pairs are there let's say one pair start from let's say six and eight let's say seven okay so the different pairs are there which is given to you now you have to find out a continuous stretch of non-intersecting pairs that will be non-intersecting pairs that will be non-intersecting pairs that will be formed as a chain so you can see that if i take this as a starting appear then this will be deciding with this so i cannot take this as well so that swatch dot this is not intersecting with this pair so i can now take this as appear can i take this as a page as it is not intersecting so let's say this is one more pair like this like it's like this so either i can take this or i can take this anymore i can take so the maximum longest chain i can make is of less than three so you just have to eventually have to find out the longest non-intersecting find out the longest non-intersecting find out the longest non-intersecting non overlapping uh pairs actually or like it's a sub array or like whatever you can say so different pairs non-intersecting so different pairs non-intersecting so different pairs non-intersecting intervals you can say okay and you just have to find out that so what is the basic approach for such type problem is that you have to first sort out these pairs according to the ends why because the end will actually help us to sort out these like what you can say these pairs so that whatever is the order like the order will be maintained when we sort out by the ends i'll tell you how but let's remove this part first so whenever we are sorting out intervals is generally by the starting point of the ending point but in most of the cases it is done by ending points only let's say that we have these pairs like this well let's not denote it why not buy like these brackets let's say by a segment so one pair start from here to here and from here to here like this now what you can see is that i have to sort them by the ending points whatever the ending uh let's say right of i whatever is the very closest will be the first element in the sorted list that we will form so as you can see that if i just mark it as 1 2 3 and so on so this is like let's say this is the first point that is encountered so this will be the first fear inside the answer that we'll be having after sorted starting form so let's just number one so it is one then we'll move forward so let's say this will come next so it will do then this will come so this is three this will come so let's say four all right after the sorting out of all of them inside the secondary of pairs this will be the order after sorting them out now what will actually help us is that we can easily find out what are overlapping for a particular segment so let's say that we are going to find a non-overlapping segment so let's say non-overlapping segment so let's say non-overlapping segment so let's say we'll always take the first element because that is the very first point okay let's say with this now because we want to find a non overlapping let's find out all the segments because see the next closest will be this okay if you are like sorting by any other point then this will come the next point this will come with the next point so the closest are coming very close and thus that is actually helping us to find out what are the intersecting like segments so what you can actually see is that if i take this and segment what you can actually observe is that okay this is intersecting with this so do not take this as a segment okay i if i take this as a segment then i cannot take this and what i can actually do to check it out i have this in the in this uh you can say in a sorted form so if i take this i will check that okay i have taken this what all are on the right hand side of this segment that are not intersecting or like or what are intersecting with this particular segment should be excluded out so this is excluded out let's move on to this segment this is intersecting with this now but this is another one of the final segments that i will be taking out next i have to take this okay so if i'm taking this can i take this four one because it is intersecting i cannot take this so this is excluded but this is not include like uh intersecting with this no so this is one of the options this one options next one is this and then there is stops like there is no more segment so that says that we have taken three segments and the answer is three contiguous non-overlapping pairs i can form that non-overlapping pairs i can form that non-overlapping pairs i can form that will form a longest chain that is this pair the sphere and this okay so that is the pretty much simple approach here that we'll first sort it out and then uh take the current segment match with all the right segments that we have and whatever like intersecting with that extrude them what is not in like intersecting take that as a next segment and try to again find out more segment attendance and remove them out and just find out the non-setting segments that's answered the non-setting segments that's answered the non-setting segments that's answered so let's move on to the code part now so what we have done is that we have sorted them out by the ending points this is the computer function that we've used to sort them by their ending points now after sorting them out we have to always take the first like the first player obviously and most of the cases and it is not empty so the answer will start from one eventually because we have taken the first segment now we will start from the second segment that is i equal to one and check that whether it is intersecting with the first segment that we have taken that is i equal to zero okay and we have stored in this last like you can say variable or let's say last year in which we will be sorting out what is the last pair that we have taken as an answer that we have taken account that we will be making the chain out of it and we will be excluding out which are not part of it like which are part of it we will excluding out if it is not part of it we'll take the next pair as the continuation of the chain that we be okay so we will start from i equal to one if it is not intersecting so if pairs of i comma zero it is written so this is the current period if the pair i comma zero which means that if the current pair starting point is greater than the last ending point if the starting of the next point is greater than the last ending point which means that it is not intersecting then it is a new segment or new pair in the chain so when we have the new pair i will mark my last as this current uh you can say pair and then increment two to the one because now we have got a new chain that new pair that will be added inside the chain and we will be doing this for all the particular pairs to form and elongate my chain and then the student total number of pairs that we have encountered in the whole chain and that's the overall answer so the overall time obviously phase complexity turns out to be that we have first sorted them out so n log in is required for sorting this is an of an operation to just eat it over the whole thing but this is a higher tank obviously so that the overall tango city turns out to be co of n log n and that's overall logic and we have not used any extra space because this is reporting in the same vector and then we're just repeating the whole vector so of like no extra specific required so of one is or like the time uh spacecraft complex like space coverage so that's overall tango setting space completely for this problem if you still have any doubts you can mention down in the comment box thank you for watching this video till the end i will see you in the next finale coding and bye
Maximum Length of Pair Chain
maximum-length-of-pair-chain
You are given an array of `n` pairs `pairs` where `pairs[i] = [lefti, righti]` and `lefti < righti`. A pair `p2 = [c, d]` **follows** a pair `p1 = [a, b]` if `b < c`. A **chain** of pairs can be formed in this fashion. Return _the length longest chain which can be formed_. You do not need to use up all the given intervals. You can select pairs in any order. **Example 1:** **Input:** pairs = \[\[1,2\],\[2,3\],\[3,4\]\] **Output:** 2 **Explanation:** The longest chain is \[1,2\] -> \[3,4\]. **Example 2:** **Input:** pairs = \[\[1,2\],\[7,8\],\[4,5\]\] **Output:** 3 **Explanation:** The longest chain is \[1,2\] -> \[4,5\] -> \[7,8\]. **Constraints:** * `n == pairs.length` * `1 <= n <= 1000` * `-1000 <= lefti < righti <= 1000`
null
Array,Dynamic Programming,Greedy,Sorting
Medium
300,491
203
Dream II car has a family If I knew I was here, I would wear this warranty and solve a wrong exercise. For more detailed information, please go to the book here. I don't like it. It's mine. Go to the first sentence. First, to understand how we operate, welcome everyone to D2 of NaNa Lacoste, our 30th leg has ID 203, named lemuse English therefore our elements are as follows after a list and a value 3 silk our task has to scale all the values where a = how many values ​​for example their form a = how many values ​​for example their form a = how many values ​​for example their form is of the airport values ​​1 2 6 3 is of the airport values ​​1 2 6 3 is of the airport values ​​1 2 6 3 5 3 4 5 6 and argument is 6 we have to go back and buy two 62's so if we need it father will be 1 2 3 5 1 2 3 4 5 and our factory reform has the following form passing on the end of Leeds and the value and drive that we want to leave MU return tell all of the new countries ok as we already know what we want to buy an element in the list then we need to know the part from before Why because it returns to MU an element In the middle, we need to put the molecule in front of it on the back wall. If you don't know about driving, you can blame it in my Sony video. No, my mother-in-law knows. Friends, No, my mother-in-law knows. Friends, No, my mother-in-law knows. Friends, we have already talked about this issue, so for this article, we need to buy these two quarters. Our main task is to name the famous rabbit in my life correctly. so we can send it to prepare this article we will be very similar to two round husbands Chris and a dog Rights need to choose the team that will run from start to finish OK our task is to determine what Because I wish it was right so that we can understand and buy the element that says ok like that. In principle, our writing will always follow Quyen. Now I will meet the dog t&amp;c to make it easier for example. Now I will meet the dog t&amp;c to make it easier for example. Now I will meet the dog t&amp;c to make it easier for example. then its writing must always be here C here awake about here A C here really about here right now my puppy is in the note for me if I want to leave mu then we will do the operation as I transferred Riverside's account to the account of the balance man, then we continue to present this time, we will be here and p, we do not benefit from the field every time we discover and molecular scale , p stands still and don't do anything , p stands still and don't do anything , p stands still and don't do anything unless those elements get the house next pp will be paid next and this guy I'm lonely old mechanical old Okay continue the car again that's the note we want to leave MU coffee also Jumping here, p also has to accept, so now when we return, we choose Duan's nick and continue to let him jump next, the car jumps again until the end of the row Ok so our algorithm is quite simple. like this, we will have a few dogs that will fall down following Quyen's star. But every time we find a hot girl who is satisfied with us, we can't jump on this tree anymore Ok Why is this? More clearly, we can go to my grandmother's house. Ok first, let's just link everything as always, we will have a pointer so we can browse from the beginning to our Cinnamon nice Ok If you have followed If you've been watching for a long time, you're quite familiar with this story. If you're not familiar with it, you can watch the video again to get more familiar with how to dress in English. Okay next, we'll have a baby. point is the poke I know the money we will attach you choose this writing fee is equal so what is the coincidence that we have the right note that has the valve to buy with the flip table that we want to send lip then we will perform the processing Ok So like this, we just need to simply point the nick of Venus to the nex of the door and it will be listed as we can see this is a dog because step So here you go, let 's pick 's pick 's pick up the Facebook frog and your nick hello lonely ok so we've finished zimou and now we'll implement this standard everywhere. The precious note of our people and As mentioned before, we only have to translate the note-extracting button when we do not the note-extracting button when we do not the note-extracting button when we do not encounter the 3 notes that we need to remove or other ones that if we encounter The note I was born in 1000, after we buy it, we cannot move the Chivas cursor. Here I will change and add a variable to check to see if it has the scale to pull the door at that time and say no Ok here I have a variable is a variable found if bifa home trend at that time we would have scaled the note mold then And if we had a remote we wouldn't have done this note jump Ok the I Our joke is as follows because with this Note by entering by letter That means finding, we stand still which will be equal to the value of Ant, otherwise we will be by dispatch because of the Then it will jump to the next step, its current value will be the Notes field. Okay, so I see it's a bus so we can watch Tet so lesson 1 2 6 3 4 5 6 12345 can return. more 6 write I Yes Ok how are you always sexy turtleneck in case there is only one note then we should buy it, the more notes so it must always be here for us Yes if we find but few then finish the note Ours opens with a license. That means if you don't write a note, it proves that the note is the first one to clip the note. Our end will point to the smile it scores, it's the next note. According to other words, if this is the note we need to find, then this virus we will install. So we just need to put the dog in the next note and it will be ok. And here is the other thing, the pig will do it. like this Yes ok I always try to keep the Intruder at least Ok But when it comes to national gymnastics and related industries I will leave the description. If you find this video useful for you then please like and subscribe and remember to Turn On Notifications because I will release videos every day. Remember to turn on notifications so they know if I have made a video. How will I make a video? Hello.
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
1,000
so welcome to my brand new tutorial this is problem solving and data structure and algorithm tutorial so every day we'll solve two three or four problems and up to 1,000 or 500 problems okay uh and up to 1,000 or 500 problems okay uh and up to 1,000 or 500 problems okay uh you I will cover I'm going to cover 500 to 1,000 problem solving in lead code by to 1,000 problem solving in lead code by to 1,000 problem solving in lead code by JavaScript okay so this would be a wonderful journey and as a pro programmer this is our cherishing desire or uh worldest dream to solve problems as much as possible and along with that uh we need to go for uh open source contribution so problem solving is very much important in uh if you want to make your place in for 500 company so problem solving is must uh you will be interviewed by problem solving so this is this will be a master class of problem solving and I am repeating you that you will get 500 to 1,000 problem that you will get 500 to 1,000 problem that you will get 500 to 1,000 problem solving every day I'm going to upload video use over here by the grace of Almighty so stay tuned this will be a wonderful journey and definitely you will get pay bump or you career will New Height okay so let's without further Ado let's dive into the deep so we are going to start from easy to medium to hard problems so you will get uh combination of easy medium or hard on 500 to 1,000 problems medium or hard on 500 to 1,000 problems medium or hard on 500 to 1,000 problems okay solution of 1,000 problem so stay okay solution of 1,000 problem so stay okay solution of 1,000 problem so stay tuned subscribed so this problem is to solve a problem if you can understand the problems very efficiently so programming language is not a big deal you can solve it by JavaScript C++ you can solve it by JavaScript C++ you can solve it by JavaScript C++ python Java or anything else okay so understand the problem is vital Factor over here so what is uh what they're saying here it is Roman to integer uh some Roman numbers are given here and we have to convert it to integers so on correspond with uh I correspond with one B correspond with 500 like that and there are test cases over here first of all you have to read the test cases to get uh to understand it uh quickly so what is saying here say example three so what is sorry so what is saying here some Roman numbers and corresponding values are given so you have to find out the summation of the number like uh here is m is equal to 4 1,000 1,000 1,000 plus uh 900+ 900+ 900+ 90 + 90 + 90 + 4 equal to it should be 1994 so as a human being we can do it easily this is very easy sum but you have to do it programmatically or logically by JavaScript code or whatever code you like okay so my as my 40 is Javascript so I am doing it by JavaScript you can implement it by any language so if you want to understand the problem uh a bit detail so I have a every iteration uh detail what is happening over here initially we are going to uh take a variable and it will be zero and then it I first iteration we'll get 1,900 th way we'll 1,900 th way we'll 1,900 th way we'll go at the end and first iteration second iteration third iteration fourth iteration fifth iteration sixth and seventh iteration everything is given uh detail here so I'll come here again after doing the code okay so let's do it uh say bar Roman to integer equal to function so we have to take a over here say we need to uh take a variable predefined variable and that is this one this is the value okay what is corresonding over here say this is this one I mean this one okay so what we need to do we need to run a for Loop for it iterate over so let I equal to zero I sorry I less than S do length i++ and every iteration what will happen i++ and every iteration what will happen i++ and every iteration what will happen let we are taking two variable on his current and current should be map s i and next should be I'm letting you understand after a bit don't worry uh next equal to map is I + is I + is I + 1 it will go to the next number Okay so we need another condition if next is not equal to undefined and current is less than next then two things will happen first of all if it is true then we will minus okay uh we need another thing let initialize a number with zero okay we'll increment it by the course of time okay zero so it should be we'll update the number and it will be minus current okay so it will be n equal to n minus current and else it will be n we'll update the N plus equal current I think we are done so we should return the number return number so let's see what will happen for this test case so console doog console.log ran to integer okay let's check I hope it will work note n r there is a typo 10 is a typ I think this time n 30 oh sorry should sorry my bed it should be note 13 yeah we got the expected result is 1994 boom and it is 1994 so what is happening over here so let's console log the iteration say console DOT log current current console do block next okay let's get the output on again you see first iteration current is 1,000 next is 100 so it will do this 1,000 next is 100 so it will do this 1,000 next is 100 so it will do this exactly same thing so first iteration initially the N is zero okay and uh what is checking current less than next so it's becoming false so it will happen n equal to n plus current so initially it is zero and now it is plus 1,000 so now is zero and now it is plus 1,000 so now is zero and now it is plus 1,000 so now will update by first iteration now will update by 1,000 the second iteration update by 1,000 the second iteration update by 1,000 the second iteration what is happening current less than so it's becoming true so it will minus 900 it will update 900 second iteration and in the third iteration it is becoming false so it will update 900 with current I mean 1900 in for iteration it will update this one okay so on in the fourth iteration it will become again true and it will update with 1900 minus 10 this way it will update up to sth iteration so uh I am making it easy for you uh as I have gone through all the iteration what is happening over here so I hope this will make sense and uh it will make you a good understanding of this problem so I think problem is solved so I hope you will understand and stay tuned stay connected it will be wonderful Journey we will solve 1,000 wonderful Journey we will solve 1,000 wonderful Journey we will solve 1,000 lead code Problems by JavaScript okay so definitely it will boost your career so stay tuned stay connected see you soon if you like the video please like share and subscribe and share it with your friends and family okay thank you very much see you soon
Minimum Cost to Merge Stones
delete-columns-to-make-sorted-iii
There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`. **Example 1:** **Input:** stones = \[3,2,4,1\], k = 2 **Output:** 20 **Explanation:** We start with \[3, 2, 4, 1\]. We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\]. We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\]. We merge \[5, 5\] for a cost of 10, and we are left with \[10\]. The total cost was 20, and this is the minimum possible. **Example 2:** **Input:** stones = \[3,2,4,1\], k = 3 **Output:** -1 **Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible. **Example 3:** **Input:** stones = \[3,5,1,2,6\], k = 3 **Output:** 25 **Explanation:** We start with \[3, 5, 1, 2, 6\]. We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\]. We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\]. The total cost was 25, and this is the minimum possible. **Constraints:** * `n == stones.length` * `1 <= n <= 30` * `1 <= stones[i] <= 100` * `2 <= k <= 30`
null
Array,String,Dynamic Programming
Hard
null
6
this is the code number six zigzag conversion so you have a string that is your input and this string you have to visualize it as this zigzag pattern so based on the input of rows that you're given so for your first input we are given a number of rows of three so that's why it's p a y and it hits three and then it's going to go down to p a because then it's down to one and then it's going to go up to three and then down to one so what you have to do is write out this string again as it would be across each row so for instance here there is the same string but the number of rows is four so you have to traverse this string and figure out what is in what row and then print it out as a different string and for this one and there's only one character so you can just give back that one character okay we're given this string here and we are given um number of rows so this string has been written in this zigzag pattern so this string here um has three rows one two three and then it decreases until it gets down to one so um what we could do is use a hash map so if we constructed our own hashmap um we could have the key be the row number and the value will be the letters so what we could do here is we could say p is in row one a is in row two y is in row three and then once we could say once we can say we've reached 3 we are going to decrease until it equals one and then we're going to go back to increasing um so we could stir this as a boolean but we can get to that later so we'll just know switching off and on whether or not we're going to increase or decrease so for now if we step through this we could just say okay um we are going to start um we can just keep a count of we'll just do um row is gonna start at one so we're going to say we're keep increasing it so we'll have key so it's going to be 1 and our value is going to be p then we're at row two that's our key and our value is going to be a then we're at row three and our value is going to be y so we reach three so now we're going to decrease so our row is going to be two that key already exists so we're going to put p here we're going to decrease to a then we're going to increase again we have l at two we have increased to three we're going to have i so we reach three we're going to decrease to s now we're going to decrease again to h we're going to increase again to row 2 is going to be i increase again to row 3 is going to be r decrease since we reach 3 to i decrease again to n so we reached one so now we're going to increase again to g and then we're at the end of our string so at the end we can just say um to construct our final answer we're going to take every key so add rows so it's going to be row one plus row two plus row three and that's going to look like p a h n plus a p l s i g plus y i r and this is going to give us the answer so now let's code that up okay so zigzag conversion so um again we are going to use a hash map um with the row as the key and the characters as the value and i'm gonna initialize it to be we're going to use that boolean to say when we are increasing the row or when we are decreasing it at first it's going to be true because we're going to start off increasing it um we're gonna see we're gonna keep track of which what row we're at currently so this is our current row and we're starting at one because we're going to go up to number rows and we are going to use an index um that's gonna start at zero and this is just to um keep track of um what character we are looking at from the input so we want to break when we're at the end of all of the characters in that string input so we could say um while our index is less than the input length so we're going to keep going through all of this and we are just going to say um first check if there is a string for this current row so we can just say string current string is going to be hm get our default so for this row is there a string already if so get that string if not just get a blank string so that's going to be our current string and then after that we're just going to put into this row the current string and we are just going to concatenate it with um the current character that we're at so we're at index and then after we get that character we are going to increment the index so that's how we are incrementing it to the next character but this is for the current character that we're at so that is that um so that's for row one now we are going to um check if we go up a row or decrease this is we're going to check now um for our zigzag so if we're currently increasing we're going to add another one to our row and we can just say wait a sec if this row equals the number of rows next time we are going to go down and we can say else if not increase we're gonna take our row down but we'll say if that row is one next time the increase is going to be true then we're going to want to go back up so um there we have traversed everything and we filled up our hash map so at the end we have to give our answer which is going to be a string and i'm just going to start it off as a blank string and i will say for every key so for every row that is in the hash map key set our answer is going to be whatever our answer was plus get the next row and then at the end we are just going to return our answer and let's see if that works oh i already defined row so i'm just going to call this r okay and so that should be it um this definitely works i think that it's the shortest amount of code that you could use so um you
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
1,255
hi this is Lee killed 12:55 and this is hi this is Lee killed 12:55 and this is hi this is Lee killed 12:55 and this is a resource allocation problem so we have our resource letters here and we want to form words with the maximum value so we can form in this case we can form both the words data and good and the words dad and dog but diamonds good gives up a high score so we output the higher score and we want to use something that is dynamic programming and it's in Python so the run times 44 milliseconds if you use order 2 to the end like some kind of brute forest and it could go up to 700 milliseconds so we want to have say we have oil words then we look at the first word and then we throw the rest into a Bock box and then we just think ok if this having this word the first word in make our lives better or does having the word out make it make our lives better like it doesn't have a higher value and so then within the black box we also do it again so we look at the first word and then look and throw the other ones into a smaller black box and so basically we recursively call this and we look at the maximum of a smaller and smaller black box with or without the first word so that's represented by this line of code here so we have without the word and we have with the word and when we have with the word we have to subtract away the letters from the available letters that the first word has taken and then the other the most important condition here is to make sure that the word is create a bowl by the available letters so we want to be able to form the first word if not we just break it so now the output will look like this here so say we have an example right here then the output would look like this and this is lake otah 55 thank you for your time
Maximum Score Words Formed by Letters
reverse-subarray-to-maximize-array-value
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only be used once. Score of letters `'a'`, `'b'`, `'c'`, ... ,`'z'` is given by `score[0]`, `score[1]`, ... , `score[25]` respectively. **Example 1:** **Input:** words = \[ "dog ", "cat ", "dad ", "good "\], letters = \[ "a ", "a ", "c ", "d ", "d ", "d ", "g ", "o ", "o "\], score = \[1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0\] **Output:** 23 **Explanation:** Score a=1, c=9, d=5, g=3, o=2 Given letters, we can form the words "dad " (5+1+5) and "good " (3+2+2+5) with a score of 23. Words "dad " and "dog " only get a score of 21. **Example 2:** **Input:** words = \[ "xxxz ", "ax ", "bx ", "cx "\], letters = \[ "z ", "a ", "b ", "c ", "x ", "x ", "x "\], score = \[4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10\] **Output:** 27 **Explanation:** Score a=4, b=4, c=4, x=5, z=10 Given letters, we can form the words "ax " (4+5), "bx " (4+5) and "cx " (4+5) with a score of 27. Word "xxxz " only get a score of 25. **Example 3:** **Input:** words = \[ "leetcode "\], letters = \[ "l ", "e ", "t ", "c ", "o ", "d "\], score = \[0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0\] **Output:** 0 **Explanation:** Letter "e " can only be used once. **Constraints:** * `1 <= words.length <= 14` * `1 <= words[i].length <= 15` * `1 <= letters.length <= 100` * `letters[i].length == 1` * `score.length == 26` * `0 <= score[i] <= 10` * `words[i]`, `letters[i]` contains only lower case English letters.
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1]) This can be divided into 4 cases.
Array,Math,Greedy
Hard
null
329
today we're gonna be working on lead code question number 329 longest increasing path in a matrix uh given i'm given an m cross n metric integers matrix return the length of the longest increasing path in matrix for each cell you can either move in four directions left right up or down you may not move diagonally or move outside the boundary meaning you won't wrap around from one side to another side and again you cannot definitely visit an element which you already have it right yeah yep so in this case it's gonna be one two six nine as shown and so the output is gonna be four the way we're gonna be doing it is like using the dip for search and ah at the big like we gonna define uh directions so we're gonna call it public static final end and let's call it directions this is basically going to the right would be 0 1 going to the left is going to be 1 0 no going down is going to be 1 0 then going to the left is going to be 0 minus 1 and going up would be minus one and then zero okay once we have it all we have to do is like basically there's gonna be a sanity check that if the matrix dot length is equal to zero now we just return zero okay uh then the we're gonna have our m equals to matrix dot length and our n is gonna be matrix total number of uh columns sorry not length okay uh once we have it we gonna use in order to like more than a visited one basically it's gonna act as two things it's gonna act as a visited uh matrix and also the value of that uh like how many have you been to like how what is what's the answer last time you came across this index so we're gonna call it cash uh and uh the dimensions are going to be m cross n okay and initially our max is going to be equal to 1 is going to be the minimum answer no matter what unless you just have the there is no element in the matrix and then that's gonna be zero okay now we're gonna iterate and i equals to zero i is less than m i plus and then our j is gonna be going from zero to j is less than n j plus okay now once we have that we're gonna say that we're gonna call our dfs the first search function and with all the values and it's going to return us an integer value which is going to be the length for that we're going to be using matrix we're going to be sending in i the current i and the j index and also the m and the n and the cash so basically we are sending him the total uh the total rows and the columns every single time and the cash so that if we already have calculated this point just return the um just return the length of that i or j uh don't recalculate it and at the end we're gonna say math dot max between the max and the length and in the end we're gonna be returning the max okay now the last thing we need to do is to implement this dfs function let's call it public and dfs it takes a 2d array matrix and it takes an i it takes a j it takes an m it takes a and add cache right okay once we have that okay what do we need to do once we have it first thing we want to check if we have already calculated this index so for that for cache i j uh if it is if the value is not equal to 0 because everything was initialized as 0 we're just going to be returning that value okay looking good so far now we're gonna again start with our max equals to one and then we're going to go through all the directions and at the end at a direction in the directions okay uh we're gonna calculate the next movement so our next x and next y so the next x is gonna be equal to i plus d i r zero and our y is gonna be equal to j plus d i r one oops i think i pressed this insert okay looking good if we are out of bound x is less than zero or x is greater than equal to m or y is less than zero or y is greater than equal to n if we're out of bound or if the new one is not greater than uh the last one right if it is not an increasing uh r the matrix of x y the new one is less than or equal to the matrix of the old one i j in all these cases just continue we don't want to process it like yeah it went out of around or it is not incrementing we don't want to continue we don't wanna go in this direction so just go to the next one okay and uh now we're gonna be calculating the length so that would be one plus the dfs because every single time we are incrementing by one dfs of matrix and then again the x y are the new i's and the js and the same m and n and the cache okay that is would be the end and the max is going to be math dot max of the max and the length okay once we come out of this we gonna uh we're gonna update our cache at the height and the jth position with max and then return the max looking good and it passed all the test cases
Longest Increasing Path in a Matrix
longest-increasing-path-in-a-matrix
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`. From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed). **Example 1:** **Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[1, 2, 6, 9]`. **Example 2:** **Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed. **Example 3:** **Input:** matrix = \[\[1\]\] **Output:** 1 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `0 <= matrix[i][j] <= 231 - 1`
null
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
Hard
null
1,716
chi I hope that you guys are doing good now as you are scared of maths me too now it's just a simple pattern recognition and applying a bit of math that's it in all the problems which involves math if a problems involve math just find the pattern just find a simple formula I'm not saying a very hard PNC can go a bit hard but yeah simple maths will still work and the simple maths when I say is just press minus division uh modulo and sometimes gcd and stuff and a few times the basic algorithms like apgb and stuff cool let's see how the problem say and how we can solve it most optimally now just says that um hery wants to save money for his first car he puts money in the lead code Bank every day he starts by putting $1 on every day he starts by putting $1 on every day he starts by putting $1 on Monday so on Monday it will start off with $1 the first day every day from with $1 the first day every day from with $1 the first day every day from Tuesday to Sunday he will put in one more dollar than the previous day so if it is one on two so on next date is 2 3 4 and so on and so forth up till the end of the week on every subsequent Monday he will put one more than the previous Monday so as you saw okay the week will start 1 2 3 4 5 6 7 in the next week as again Monday Tuesday Wednesday Thursday Friday Saturday Sunday now next Monday will come so next Monday he will put in one more dollar than the previous subsequent Monday which is two and again he will keep on putting three 4 5 and so on and so forth now return given the N return the total number of amount of money he will have in the lead code bank at the end of the day so basically in end days what is the sum of all these numbers it's just what the problem is asking now as in the first glance again we have we are not going into the most optimal approach but as the first glance itself you can see that the numbers will form a pattern they are increasing so for sure they are increasing and I'm not saying increasing as randomly increasing one like this you can see the pattern is being formed so for sure something of pattern sort you will apply it is visible from The Naked Eyes itself now as the N is very small so one thing what you would have done is that simply go on to all the you can just maintain a Monday initially the Monday is one you can go on to all the weeks keep on adding Monday plus let's say the day is this so Monday plus the day which is zero here and then here it is one here it is two and so on and so forth and then as the week finishes go on to next week and simply it trade increase the Monday by plus one it will now become two and with this you can go on to All N elements and perform the same operation just brood force and simply replicate the formula that is the first way but I are we going to do that yeah we can because it will have o of n time and space as time as o of one and space as o of sorry time as o of n space is O of one which is okay for this problem and that is the first intuitive approach which you will tell to the interviewer but then what if I just say as it's a easy problem it's easy just because of the constraint itself it can become medium if I do okay n is one9 or n is8 or n is let's say 1 100 no 18 n is 118 now tell me what will be the answer now if you want to go let's say n is 189 or maybe more than what you can compute in one second for that you will have to figure out the pattern and a formula corresponding to that now I'll write the same stuff as what I wrote above if I go and write the same stuff 1 2 3 4 5 6 7 it will be the first week now how the second again I'm just writing down I have no idea of what the N is just after writing my example down as in how you approach a problem you write firstly this thing you'll firstly write everything like just keep on writing so that you can see from your NE what the pattern is and then after that okay when you have like written something example from your mind something example which is a bit long then you reverse inor to see okay what are the values of N and then what are the values of this row and that row and stuff so okay first I wrote the example down randomly uh 2 3 4 5 6 7 8 3 4 5 6 7 and you for sure know that every week it will increase so that's the reason how I wrote it down and every day also of for the week it will also keep on increasing and 4 5 6 7 now I stop because I have enough big example which will include all the cases as in the entire week I can have here and the remaining week I can have here now my main task was to find its total sum so for sure the individ ual sum as in my main task is to find the total sum of entire stuff this entire stuff right so firstly let's simply keep on finding the individual sum also so and it is just me trying to find a pattern that's it you can go in any ways and you can find some other patterns to in this which can be solvable in other forms but it's just that we're trying to find a pattern only okay the sum is 28 the sum is 35 the sum is 42 the sum is 22 that's it okay now we want that um this last week maybe we can ENT trade because it is just the seven days but the previous weeks can we figure out a formula to just get the sum for that again as you can see it's just that everything is increased by one as you see 1 increase to 2 increas to 3 to 4 to 5 to 6 to 7 and 7 to 8 so every day corresponding like previous day in respect to the pre previous day every day in the next week is increased by one so for sure the next week sum would also be increased by seven because every day and in a week we have seven days and the same goes for next week so you can see that the sum if I just take this as the first element the sum will have the same difference oh the same difference this as soon as this word comes in what reminds you it reminds you of Artic progression because arithmatic progression is a series of numbers in which the difference is same constant and that's the reason now this series funa comes very naturally like it can be happening that you are asked to find the sum ofnatural numbers sum of squares ofnatural numbers and all that stuff you might um like get so it is just again another series okay it's a AP again if you maybe don't figure out just write this series down let's say if you are new to programming so there is uh just write on Google just figure out the series 28 35 42 and so on and so forth just write this down and the computer will tell you as in the Google uh there is alpha wolf from um basically website which tells you the pattern in a series itself and that indect tell you that it's a AP and you can find the nth term you can find the sum and all that stuff so even if you don't remember just don't worry search on Google and you'll get the series itself now when we have fig out the series now what we want is the sum of these let's say here the values are three so let's say here we have ke values now how you got to know that there are three values simple as you know that we have n now N I just did not know initially I just made the example and then from the example itself I backtracked and again get like got what my n should be n is 26 now with this n what I will do is I'll just do because I know that every of this have seven elements so n by 7 is 26 by 7 as simple as that which is actually three which will say I will have three complete weeks seven indicates complete right a week which is complete which I have all these seven days so I will have three complete weeks now when I have three complete weeks then for sure I just want I have K complete weeks so basically I will have these as ke elements now the sum of AP of ke elements is nothing but if you don't know as I have written also here that let's imagine I have a AP1 A1 A2 up till a n which has n elements and a standard formula it is nothing which I have made it's a standard formula again if you don't remember just write this series on 28 35 42 on alha from channel uh like U page or website and then it will give you that it's a AP just go and find the sum of the AP just write the formula and you'll get the formula itself the first term as it's A1 the last term it's again a formula just remember that for future also for an AP that it is a n which is the last sum we represent as a n it is A1 + Aus 1 D and that's very n it is A1 + Aus 1 D and that's very n it is A1 + Aus 1 D and that's very natural you can just also compute that now the sum is a bit tricky to figure out but like it has entire proof of it but simply remember that the sum of the sum is represented as n by 2 A + N - sum is represented as n by 2 A + N - sum is represented as n by 2 A + N - 1D or if you think that it is long for you to remember just remember the sum as n by two first element plus last element and last element you can figure out from this and for the proof I have just bated this existing sum this is existing proof I just dropped it down and broke it into n by2 A1 + a n A1 + nus 1 D and this a1+ n by2 A1 + a n A1 + nus 1 D and this a1+ n by2 A1 + a n A1 + nus 1 D and this a1+ n 1 D was actually the last term so it will be first plus last term and is n by2 so that's how you get the sum again uh I remember this fact which is n by2 because it is actual value with this indirectly we get this value which is sum equal to n by2 + f plus L which is sum equal to n by2 + f plus L which is sum equal to n by2 + f plus L which is the first term plus last term which is not the like you cannot go and get the like intuition of the proof why this value is there because it has entire proof which goes through this value and this value comes first and then from this to remember easily we just put this as n by2 + f n by2 f+ l just put this as n by2 + f n by2 f+ l just put this as n by2 + f n by2 f+ l but still I will use this value n by2 2 a + nus 1 D now if I go back I know that a + nus 1 D now if I go back I know that a + nus 1 D now if I go back I know that I have K elements with me so again the some I know the first term will be 28 for sure because first week we'll have the value or the sum as 28 and I know the consecutive difference is 7even so I know the difference I know the first term which is A1 I know the N which is here K because I cannot use n because n was my existing value so I use K instead so it will be K by 2 a + k - 1 d k by so it will be K by 2 a + k - 1 d k by so it will be K by 2 a + k - 1 d k by 2 K I know from this which I will find initially so I'll just say k = n by 7 I initially so I'll just say k = n by 7 I initially so I'll just say k = n by 7 I will find K initially then I will have my sum which is K by 2 uh 2 into a is 28 which is fixed the Kus one into d is also fixed which is 7 now when I have found the sum but it was the sum for the three complete weeks basically K complete weeks what about the remaining week okay for the remaining week again we can just iterate on all these days instead again you can also find the sum that's also completely okay that's also an AP itself you can also go and find the sum but that's only 7 Days oh sorry U that's only 6 days at Max so what you can do is simply go and iterate on all the 6 days so what we can do is we know the first value is itself k + 1 how byya how k + 1 value is itself k + 1 how byya how k + 1 value is itself k + 1 how byya how k + 1 because you saw 1 2 3 so you knew that you had three Mondays previously so next will be a fourth Monday of course which is a K plus one Monday and then again uh let's see that here the day is zero here the day is one here the day is two here the day is three so simply keep on adding the day corresponding to this value and you will keep on adding this in your sum which is the sum above which you have found and just keep on adding for all the remaining days which is how to know the remaining days as simple as that uh we know that our n was uh this is 21 22 23 24 25 it is 25 so I 25 by 7 which is 325 mod 3 which is actually 4 so I know that I have to go on for up till 4 days which is from 0 D is from 0 to 25 mod 7 which is Open Bracket Which is less than 25 mod 7 Which is less than four that's it and with this I can simply get my answer cool let's quickly code this up we use a same formula we'll just firstly figure out the K we will find this sum because we know the a which is hard as 28 we know the D which is seven and then for the remaining weeks which we will just simply trade on by doing the n mod 7 let's quickly go uh so firstly as we saw that we will find the k for us uh now again uh you can just remember these formulas and you might have remembered because it's a class 10th uh formulas so we'll do a simple um n by 7 for us to get the K now we need to have the sum now this sum is as I showed you um K by 2 basically n by 2 uh n now again as I showed you in the formula it is K by 2 a + k 1 into d right so it is K by 2 A a + k 1 into d right so it is K by 2 A a + k 1 into d right so it is K by 2 A is 28 + K - 1 K - 1 now K - 1 into d A is 28 + K - 1 K - 1 now K - 1 into d A is 28 + K - 1 K - 1 now K - 1 into d is again 7 now K you have figured out previously so you will just pop this K value now when this is done now you have just last of your days remaining so I'll go on to all the days remaining days which is uh less than equals to n mod 7 and I can do a d++ now when we have gone on to this day d++ now when we have gone on to this day d++ now when we have gone on to this day we can simply say that in our sum although it's not a good practice to name my sum as a capital S so I'll just name it like this now I will go on to the first Monday now first Monday is k+ the first Monday now first Monday is k+ the first Monday now first Monday is k+ 1 itself and in corresponding every I'll just simply add a DAT and ultimately um return the sum with this I can simply get my value uh let's quickly sum this up um sorry compile this up and you get the answer cool with this you can see that you will get it in 0 m just of one time and the memory is just for these variables which is very less cool thank watching Again by bye
Calculate Money in Leetcode Bank
maximum-non-negative-product-in-a-matrix
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Array,Dynamic Programming,Matrix
Medium
null
217
Hello everyone, Evgeniy Sulima nov is with you and today we will look at the snail problem 217 searching for a repeated value in an array and how this task was sent to us, we are given an array of integers and we must determine whether there are duplicates in this array, while we don’t care how many while we don’t care how many while we don’t care how many times these values ​​are repeated the main thing that times these values ​​are repeated the main thing that times these values ​​are repeated the main thing that we must understand is if the principle of duplicates, for example, we have an array of 1231 and the result is completely our place, the content and pasting should be hands because the number one is repeated 2 times in the array 1234, the result will be a fall because the value in the array will be repeated, which will come here, the result will be a corpse because that numbers 1 are repeated numbers 3 are repeated from three and four and two date all values ​​are repeated and two date all values ​​are repeated and two date all values ​​are repeated more than 1 time let's first look at the options that come to mind, that is, for now there are three options, that is, 1 and Tahiti, nested loops through the array and compare each pair of values ​​then there is a dad where each pair of values ​​then there is a dad where each pair of values ​​then there is a dad where it will be m complexity, but in terms of time performance it will be n squared, that is, the complexity is unacceptable, so I don’t even make sense to consider the so I don’t even make sense to consider the so I don’t even make sense to consider the second option that came to mind is to sort our array because nothing is said in the conditions sometimes for sorting it, so we can sort and then compare just the current element with the next element, yes, that is, for example, I received such a massive input after sorting, it will look like this and now I can compare the current moment with the next one and if there is a match, then these frame elements then I say that in this a-7 there are frame elements then I say that in this a-7 there are frame elements then I say that in this a-7 there are repeating values, let's look at this option in the code, that is, for sorting I will use the standard sort method of the duck class and flight after that I can be sure that my array is sorted now I loop through my array int i is equal to zero and less than mts. links minus one important point because we will go compare the following elements if we just write links for us it will get index out about exception here and I do and plus well now I make a comparison that is, if on mts and that is, the current element is equal to mts and + 1, that is, to the next equal to mts and + 1, that is, to the next equal to mts and + 1, that is, to the next element, then I return the work, but if, as a result of the entire pass through my array, no match was found, then in this case I return the fall, it seems that there were errors in writing the code, do not pass on the forecast, bend the data, only an amendment is given to drive first like a cat to there was no compilation and after that it followed the event if everything goes well and so we see that on such data we are working on a tarik on I click submit with the name that this solution worked in six milliseconds pretty quickly good the second option that doesn’t come to second option that doesn’t come to second option that doesn’t come to mind is use the set collection more precisely cursed, that is, we know that in java the hashtag collection is a collection that is the same as the table and at the same time it guarantees that I only have unique elements stored and this method, in case of adding, repeat the value, returns a fall, that is, I create collections of integers and I start to alternately hurt all the elements of my array into this collection and if my method this returns the canvas and I return the corpse because I guarantee that there is a duplicate in this array, that is, I write tossed in diger, let's call it the interface is equal to new hair set now in this array here prostrate and change to mts links I say that if the operation of adding to us and in my interior returns me a fall, then in this case I return the corpse, if this does not happen, envy is overkill, then I return the fall in this case, I think it’s clear here, so think it’s clear here, so think it’s clear here, so errors are checked then there is a neighbor integrator engels cursed in the loop without any problems interested we have the brackets placed correctly, it seems like there shouldn’t be any errors, let’s placed correctly, it seems like there shouldn’t be any errors, let’s placed correctly, it seems like there shouldn’t be any errors, let’s first just compile this code for the deception test version everything is fine everything worked and click submit here everything is worked out everything is good the complexity of this approach is from memory and because we devote a lot of data structure to storing all values ​​in the data structure to storing all values ​​in the data structure to storing all values ​​in the worst case and for enumerating all arrays in the best case, that is, the complexity will be 2n, in principle, this is also an acceptable option. With this we finish the analysis of this problem, I say goodbye to you all the best
Contains Duplicate
contains-duplicate
Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** true **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** false **Example 3:** **Input:** nums = \[1,1,1,3,3,4,3,2,4,2\] **Output:** true **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Sorting
Easy
219,220
155
hello everyone so today we will be solving lead good problem 155 that is minimum stack so we have to design a stack that supports push pop top and retrieving the minimum element in constant time so we have to initialize the stack object then we have got push where we will push the element Val onto our stack then we have got pop which will remove the element on the top of the stack then we have got top which will get us the top of the element of the stack and we have got get min which will retrieve the minimum element in the stack we have to implement the solution with o of one time complexity now if you see the input and the output it also does have an explanation so first we will be initializing our stack then we will be pushing minus 2 then we will be pushing 0 then we will be pushing minus three then we have to get the minimum so the minimum would be minus 3 out of all the three elements so we are returning that then it has uh called pop so once it is called pop it must be popping out three from our stack it must have popped out three and then there is top so we will be returning the top element from the stack which would be 0 then we have to get minimum so when you do get minimum as 3 is already popped out so we would be getting minus 2 as the minimum right now so yeah this is about the example let's move over to code this so we will be using two stacks so let's undo that we will be having two stack one a normal stack and another one where we would keep our minimum so we would keep two stacks now in our push let's write our push function a function so we will do self Dot stack dot append and B will append Val what we will do is we will check if element is not in self Dot bin stack or well is less than equal to the last element being pushed to our Min stack if our value is smaller than we will append it to our Min stack so that would be it for the push now we will write for the pop so if our self stack is there if you have got values in our stack then we will check if the last value of our stack the last pushed value is equal to the last pushed value in our minimum stack if it is equal then we will pop it from our minimum stack we will also pop it from our stack now we are having this condition that the last post element like we are checking if the last first element is equal uh to the last first element in our minimum stack that is because if it uh will not be the minimum element then we don't have to pop it out from our uh like minimum stack if it is uh not the smallest element we don't have to pop it from our minimum stack because in the first place we would not have pushed it we might not have pushed it so we would just pop it out from our stack so then top for top we will write if we have stack then we will just return our self Dot stack whatever last element we would have pushed in and then for getting the minimum we would just see if we have got something in our minimum stack then we would return that return self Dot bin stack the last element so yeah that would be uh pretty much it about the minimum stack let's run this to see if we have got any errors so our test case got accepted let's submit it that is pretty much how you solve this problem minimum stack and thank you for watching I'll see you in the next video
Min Stack
min-stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `MinStack()` initializes the stack object. * `void push(int val)` pushes the element `val` onto the stack. * `void pop()` removes the element on the top of the stack. * `int top()` gets the top element of the stack. * `int getMin()` retrieves the minimum element in the stack. You must implement a solution with `O(1)` time complexity for each function. **Example 1:** **Input** \[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\] **Output** \[null,null,null,null,-3,null,0,-2\] **Explanation** MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 **Constraints:** * `-231 <= val <= 231 - 1` * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. * At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
Stack,Design
Easy
239,716
948
hey guys welcome back to another video and today we're going to be solving the lead code question bag of tokens all right so in this question we have an initial power of p an initial score of zero and a bag of tokens where tokens i is the value of the ith token and a we index are starting at zero so your goal is to maximize your total score by potentially playing each token in one of two ways so given a certain token we can do one of two things and these are the options that we have so the first option is if your current power is at least tokens i so it has to be at least tokens i you may play i token face up okay and when you played face up what happens is that you lose tokens i power and you gain a score of one so let's take a quick small example so let's say we have the so tokens i currently has a value of 100 and our power has a value of 200. so what we can do is we can play it face up and what's going to happen in that case is we're going to subtract the number or the amount of tokens from our power so 200 minus 100 leaves us with the power of a hundred but by subtracting it what happens is that our score increases by one so getting one score now the other thing that we can do is if your current score is at least one you may play it token facing down and in this case you're going to gain tokens i power but you're going to lose a score of one so in other words what's basically happening is in this case let's say our tokens i has a value of 100 and our power has a value of 50. so in this case what's gonna happen is that we actually cannot uh place the token face up because to place it face up we have to subtract from our power so in this case what we can do is we can place it fade face down and when you place it face down what happens is we get those tokens so this gives 100 tokens into our power so now our power is going to be 50 plus 100 so 150 but the problem with that is that our score now decreases by one all right so the task that we have over here is that each token may be placed at most once and in any order you do not have to place all the tokens so you do not have to place them all and return the largest possible score you can achieve playing any number of tokens so quick examples uh this is actually the same example i went over so a token of 100 and a p-value of 50 so in this case we and a p-value of 50 so in this case we and a p-value of 50 so in this case we cannot place it face down we have to place it face up and placing it face-up it face-up it face-up it's gonna decrease our score down to negative one and the score that we currently have of zero is actually a better option so we're just going to stick with that and not do anything so this over here is another example so we have 150 so in this case what we're going to be doing is we're actually going to uh place the token of 100 phase up so now our power is 50 and now in this case our score also increases by one and then we're going to stop doing the rest because 200 is too big it's bigger than our power so we have to place it face down but at the expense of losing our score by one and this over here is the example three and instead of going in going over it over here what i'm gonna do is go over it step by step and while we're going over it step by step we'll come up with a solution of how we can actually solve this question all right so over here we have the exact same thing so 100 200 300 400 but just for the sake of explaining i changed the order so 400 100 200 300. so one of the questions that we want to ask is does it matter how big or small the number is and one more thing that we notice or we should notice is sorry so if you go over here uh pretty important each token may be placed at most once and in any order they can be placed in any order that you want it to be placed at so we don't have to go through it step by step so since we are given those rules to play around with we want to ask does the size of the tokens matter and the answer to that is yes because when we have a smaller token what we can do is we're going to lose less points but we're going to gain score so the main goal here is to lose the least amount of points and get the most score that we can in that case what's going to happen is we're going to lose the most points but we could get a score higher or another thing that we could consider when we have a really big number we're going to gain the most amount of points but we're going to lose one score and uh thinking of it that way let's say we have an option between choosing between 400 and 300 right and we're placing both of them face down so in that case we're going to end up choosing 400 because 400 is going to give us more points but and in either 400 or 300 we're only going to end up losing our one score okay so now that we know that the value or how big a number is matters we're going to sort it so the way we're going to sort it is going to be in ascending order so 100 then 200 300 400 and yeah and i'll just rewrite the p-value p-value p-value so the p-value is still going to be 200 so the p-value is still going to be 200 so the p-value is still going to be 200 okay so now let's go through this step-by-step and we're going to be using step-by-step and we're going to be using step-by-step and we're going to be using a two-pointer method a two-pointer method a two-pointer method and we'll see how this works so we have a pointer over here so that stands for left and this over here is going to be our right pointer left pointer starts at index 0 right pointer starts at the very ending all right so now that we have this over here how exactly can we use this to find out the score so what we're going to do is we're going to be going inside of this loop and the condition to enter the root loop is going to be that the left value has to be less than or equal to the right value so that's one thing that we have so let's just write that down uh over here so left has to be less than or equal to right and after we have this we're going to look at one more condition so over here we can have one of two things so over here we could have some value in our score right so our score starts off at zero but we could have some value to it and another thing that we have is we're going to look if our current points is greater than or equal to whatever the value at l is so let's just go to that so tokens and l okay so basically what exactly is happening here so we're going to go inside of our while loop if either one of these are true so if we have a score which is not equal to zero then in that case we can go inside of our while loop now why does that make sense so the reason that makes sense is because when you have a score of zero we can afford to lose at least one score so that is one of our conditions and the other thing over here is if the p value is greater than or equal to the token value that we have then in that case another thing that we could be doing so if this is true we can lose that many uh points from our p value and we can add to our score so if either of these conditions ends up being true we can actually go through instead of our loop all right so now that we're inside of our loop we're going to be doing a check now the first thing that we want to check is the p value greater than or equal to tokens l and again i went through the reason that we're doing this and the simple reason real quickly is because if it is equal to or greater than then we can increase our score by one and again i'll be counting our score over here okay so score starts off at zero and now in this case 200 is greater than 100 so what's going to end up happening is that we're going to have 100 points taken away from us so 200 minus 100 now we have a value of 100 for p our score is going to end up increasing by one so now our score is one and the left value is gonna move to the right by one and the reason we're moving it to the right by one because we can only go to each token one time so let's just kind of cross this out over here okay so now we have this and now we're gonna go inside of our while loop again so in this case we're going inside of the while loop because our score has a value of one it's not zero but one more thing you want to look at is our p value which is 100 is actually less than the smallest value which is 200 so in this case we cannot actually uh expand our score so what's going to happen is we're going to end up losing our score and what are we going to lose our score to 200 300 or 400 and the answer to that is we're going to lose our score to 400 and the reason that we're going to be losing our score to 400 is because in this way we're only going to lose a score of one so now our score becomes zero but we're going to get the most amount of points so now our p value is going to be a hundred plus 400 i'll just write all the p values here since that's kind of messy so we're going to get one for 400 plus 100 so 400 plus 100 giving us 500 right but our score is now zero so now what's going to happen is the right value over here since we already use this token it's going to move to the left by one so now this over here is our right value now over here what's going to end up happening is we have 200 300 and we have a p-value of 500 which is and we have a p-value of 500 which is and we have a p-value of 500 which is greater than 200 so what's going to happen we're going to end up using this face up so in that case score now becomes 1 and 500 minus 200 gives us a value of 300 and now the left value moves to right by one and the left value and the right value are now going to be in the exact same place so in this case what's going to happen is that since they're on the same place we still go through it and 300 so that's perfect right so in this case we're still going to use this face up and we're going to cross this out uh 300 minus 300 now gives us the points of zero and our score over here is now gonna increase by one so one plus one giving us a score of 2 which is exactly what we were looking for all right so let's start off by taking our tokens and we're going to sort it in ascending order so now we did that and over here we're going to have our score so the score is going to start off at zero and simultaneously we're going to have our left and right values so the left value is going to start off at an index of zero and the right value is going to be the length of tokens minus one and the reason we're doing minus one is because we're starting to index at the value zero okay so perfect we have this and now that we have this we're going to go inside of our while loop so the first condition is if left is less than or equal to our right and the reason we're checking for that is because if we have the left value being greater than the right value that means that we're going to end up reusing some values which we shouldn't be doing so that's one of our conditions and the other condition is going to be an or condition so in this case we're going to check if point is not equal to zero so we can just do if points and the other or the other condition that we have is if the p value is greater than or equal to tokens and we're going to get the smallest value which in this case is going to be at the left index all right so now we go inside of our loop and over here we're going to have the first condition which is if the p value is greater than or equal to tokens l and if it okay and if that is the case then what we're going to end up doing is we're going to take our score and we're going to increase it by one that's one thing that happens uh simultaneously one more thing that we're going to be doing is we want to remove that amount of points from a p right so in that case p minus equal and we're going to remove tokens l all right and finally one more thing that we need to do is we want to move our left pointer to the right by one okay so that's one condition and another condition is going to be when uh p is not equal to or greater than token's l and in that case what's going to end up happening is that we're going to uh decrease our score by one and we're gonna gain those tokens into our p but that is not always going to be the case and we're only going to do this when our left value is not equal to our right value and if the left value is equal to our right value then in that case we're just going to break out of this okay and the reason that we're breaking out when the left and the right value is same because one okay so let's just look at this over here so r and l are at the same place but now let's say we actually have to gain tokens so two things happen we gain tokens that's good but we decrease and score and this is going to be the last iteration because after this whatever we do is going to be a repetition which we cannot have so this over here is the last iteration and losing score in the very last iteration makes no sense right so that's why we're not going to be doing anything and the extra points that we gain also don't matter since that is the last iteration okay so now that we kind of understand that uh over here we're gonna check uh we're gonna go to our score which decreases by one uh then we're going to go to our points and we're going to increase it by tokens and the right value over here and uh simultaneously we're going to decrease our right or take the right pointer and move it to the left by one so r minus equals one and that should be it so at the very ending outside of our while loop we're gonna return our score uh let's submit this sorry i was supposed to i was actually referring to score over here and not points so yeah my bad okay so score and as you can see our submission did 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
Bag of Tokens
sort-an-array
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Merge Sort,Bucket Sort,Radix Sort,Counting Sort
Medium
null
739
everyone welcome back to everything swift today we'll be tackling legal question 739 titled daily temperatures we're given an array of integers that represents uh daily temperatures and we're supposed to find how long does it take until the next day that it's hotter right so i think this example is pretty good to understand what the question wants so on the first day the temperature is 73 degrees right and then the next day is 74. if we look at the output here it's one right so how long does it take for this day to experience a day hotter than it is today uh which is the next day tomorrow right 74 so there's one day how long does it take uh 74 this day to experience a day that is hotter than it is uh as of today which is tomorrow 75 so that's one right uh and then uh for 75 one is the uh the next day that is hotter than 75 right so it goes all the way to 76 so that's four right so we get the g's of the question here what they're trying to ask us right uh important thing to note is if there isn't any day that's hotter we just keep it at zero so for example after 76 uh 73 is not hotter than 76 so it's zero and 73 there's no day after that right so there's no day hotter than 73 at this last index so it is zero right so i'm gonna walk through the explanation while i type the code uh yeah let's get started so temperatures is empty basically we just return an array right um this is just for performance check reason we probably don't have to do it because we can assume that we are going to be given an array of integer but it's just a habit uh that i just do for fast performance uh check so uh let's create our output array here called results and fill it with a bunch of zeros so the reason why i chose to do this is because like if there are days that uh there are no hot day hotter than it is today we have to fill it with zero so i don't want to have to deal with like appending zero and stuff like that so i can just fill it with all bunch of zeros first so i'll demonstrate why this is useful and how it works later on and uh i think we need to keep track on the days right on like which day is hotter and stuff like that so just a holder i'm just going to call an index here and yeah i think we can start to look this index temperature in temperatures it's just a follow and here i'm going to check if indexes is empty or not right if it's not empty and the temperatures these temperatures array and we're going to take the last uh index here is less than the temperature right so what this does is we can think of these indexes as a uh functions like a stack right we uh first in and then uh last out right that's what we want to do so we're going to keep track of that and this one look what it does is basically we are finding the next hottest day so temperatures of the last index that we are finding is it uh cooler than today's temperature which means in other words that in this current loop here this temperature is hotter than our previous day because index is storing the days of uh the previous loop right so here i'm just gonna put this here if it's clearer and then here if it is cooler then what we're going to do is previous index we're going to pop this out of indexes we move less and then let's get the difference which is index and previous index and then here we are going to get results of previous index because of this right and then that's about it i guess that's all we have to do right so uh just to explain even further here uh at each iteration we are storing the index the reason why is like we are not interested in the temperature right interes we are interested in how long does it take for us to find the next uh day that is hotter than it is today right so imagine here uh the first loop 73 uh index is empty because it's the start of the loop so we fill it in we take the current index which is zero inside indexes here and then the next loop which is uh at 74 we ask is indexes empty no it's not because it has 73 and index 0 right we're storing zero right so we take uh temperatures and index 0 right so is 73 less than 74 it is right so we have found a day that is hotter than what we stored in our indexes right so we calculate here and then we just fill it up inside the results so as you can see here because there's zero here uh what it does is when it reached to 76 and 73 there's no further operation that i need to do right because uh there's no day that's hotter than that and it's by default already 0 so yeah that is how i'm trying to solve this problem let's go ahead and write this code and make sure i get the right answer there i have it uh let's try and submit this there we go that's the answer uh yeah so basically yeah the indexes is functioning like a stack like we're trying to keep track of the previous days and this loop is just essentially trying to check uh is there any day hotter in the current for loop right if it is then we calculate the difference the index here represents the day right and then once we find that we just fill it inside our update our results array at that particular index and that's it that's the answer so as always if you guys find this kind of video helpful please feel free to subscribe i'm trying to grow this channel i'll try my best to keep posting more videos so thank you very much for your time take care
Daily Temperatures
daily-temperatures
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead. **Example 1:** **Input:** temperatures = \[73,74,75,71,69,72,76,73\] **Output:** \[1,1,4,2,1,1,0,0\] **Example 2:** **Input:** temperatures = \[30,40,50,60\] **Output:** \[1,1,1,0\] **Example 3:** **Input:** temperatures = \[30,60,90\] **Output:** \[1,1,0\] **Constraints:** * `1 <= temperatures.length <= 105` * `30 <= temperatures[i] <= 100`
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
Array,Stack,Monotonic Stack
Medium
496,937
480
hello and welcome back to the cracking Fang YouTube channel today we're solving lead code problem 480 sliding window median the median is the middle value in an ordered integer list if the size is even there is no middle value then the median is just the middle the mean of the two middle values for example array 2 3 4 the median is three if array is 1 2 3 4 the median is 2 + 3 divide 2.5 2 3 4 the median is 2 + 3 divide 2.5 2 3 4 the median is 2 + 3 divide 2.5 you were given an integer array nums and an integer K there's a sliding window of size K which is moving from the very left of the array to the very right you can see that you can only see K numbers in the window each time the sliding window moves right by one position return the median of the array for each window in the original array and you're allowed some margin of error for the rounding because you can divide okay let's look at an example we have this array here 1 3 - 1 - 3 5 3 67 and we're array here 1 3 - 1 - 3 5 3 67 and we're array here 1 3 - 1 - 3 5 3 67 and we're given that k equals 3 so let's look at what the window equals at each point so it is 1 31 so in this case what is the median so remember that the median here is like in sorted order so it would really be let me change my pent color to make it a little bit more visible um how would we order this so this becomes minus1 1 3 um because we want to find the median and unfortunately this isn't sorted so um the median here is actually one so that is why they return one so then the window moves we get rid of this first one so now we have three - 1 - 3 first one so now we have three - 1 - 3 first one so now we have three - 1 - 3 um and again to find the median so it's going to be - 3 -1 3 and in this case going to be - 3 -1 3 and in this case going to be - 3 -1 3 and in this case it's -1 and in the next phase we get rid of -1 and in the next phase we get rid of -1 and in the next phase we get rid of that three and now it's -1 - 3 5 in this that three and now it's -1 - 3 5 in this that three and now it's -1 - 3 5 in this case it's um let's see Min -3 -1 5 and case it's um let's see Min -3 -1 5 and case it's um let's see Min -3 -1 5 and it's minus one again and so on and so forth it's pretty straightforward and you know there's not really too much to it if you're just looking at uh the problem on its own Okay so what we just did was the naive solution right we had our window of size K in this case it's three um basically we sorted the elements and then just took the one in the middle and this is really the naive solution right and if you're in a pickle you've never seen this question before and it comes up in an interview or you just forget how to do the proper solution you can always probably come up with this and your interviewer will probably ask you to improve it but at least you coded something and you didn't just sit there blankly so if all else fails you can do this naive solution it's not optimal but it is what it is so we now know that this isn't the optimal solution and how are we going to solve this right we want some way to avoid having to sort the elements because if K is really large we're basically just sorting the array uh over and over again and then this becomes really inefficient and what we're going to do is actually a similar algorithm to the way that we solved um I forgot the problem number but it's um moving average from data stream and that is actually a two Heap approach and the reason we God that is terrible writing uh two Heap and the reason we have two heaps is because if we have one Min Heap and we have one Max Heap then the median will either there's a few cases right it's either going to be just the sum and then divide by two of whatever is at the top of the Min Heap and whatever is at the top of the max Heap we just divide by two um and then we you know just return that or we'll just assume that Min is allowed to have one more than Max so if there's actually an odd number then we would return whatever is at the top of the Min Heap otherwise we'll do the division so you can think of it as if here is the median value which is what we're looking for if these two have the same elements so if basically um the window size so if K is even then we need to take from the Min Heap and we need to take one from the max Heap and then do basically like you know let's just say the Min Plus plus the Max uh so M1 M2 and then divide by two and that's the median so that's you know how we would do it otherwise we would just take from the top of the Min Heap okay and you know you can think about it as the Min Heap basically having the left side of the elements and then the max Heap or sorry the max Heap will have the um the left side because the max would always be the greatest of the thing so if we think about kind of our Max Heap so for example if we had like one 2 3 4 the max Heap is actually going to store the left side so we always have the element that's basically closest to the middle um coming from the left and then the Min Heap would actually give us the smallest element from the left that way we can if we need to just get quickly get those two you know do 2 + three divide by two you know do 2 + three divide by two you know do 2 + three divide by two and get the median and then we'll allow the Min to basically have um the greater one more than the Min the max because in the case that it's odd we do that so that is pretty straightforward and you know that would be great if we didn't have the constraint that there's only K numbers in the window unfortunately this means that we have to get rid of elements in our Max Heap because they will start to accumulate right whenever we move the window we then get rid of elements that we've you know as we move from left to right and the problem here is that we need to update our Max Heap and the way that we're going to do this is we're actually going to keep a dictionary which maps all of the elements um which are still live um which actually need to be removed from the Heap so we will keep a basically just a dictionary which Maps like the element we need to remove and if ever when we like have a new window we see one of these elements is either at the top of either Heap we're actually just going to pop it to get rid of it and the reason we will only do this when it gets to the top of the Heap is because popping from the top of the Heap is actually a big O of one operation whereas trying to pop from somewhere in it is going to be Big O of K because you not you have to basically reorganize the Heap when you pop an element and we only want to do this in kind of whenever it makes sense so when it actually gets to the top of the Heap we'll actually just remove that element to make sure that um we don't you know accidentally process it because remember we can only have K elements in our window at a time so we want to make sure that we're actually not considering anything for the median uh that shouldn't be there so that's why we will pop things so just to recap the way that we're going to solve this is we're going to use two heaps we're going to use a Min Heap and a Max Heap the max Heap is going to refer to all the elements to the left of the median and the Min Heap is going to keep track of all the elements to the right of the median and the way that we're going to find the median is if K is odd then all we have to do is just pop from the minimum and we'll allow minimum to have one more element in the case that it's odd and in the case that K is even then we just need to pop from both the Min Heap and the max Heap get the top elements and then you know just do the addition divide by two and there's your median and we'll also keep a dictionary which keeps track of the elements that we need to get rid of the Heap but we're only going to do this for the purpose of efficiency when that element actually either gets the top of the max Heap or the top the Min Heap and remember this is because popping from the top of a heap is a constant space uh thing we don't need to basically reorganize the Heap after that so that is the reason we're going to do that okay so that is kind of the intuition here let's now actually go into the code editor and type this one up it's a bit verbose but the logic is pretty straightforward I'll walk you through it line by line as we always do and hopefully everything will make sense um once we do that okay cool let's go code it up let's now code this up remember that to do this problem we're going to need a Max Heap A Min Heap and also a dictionary to keep track of what elements are in the Heap which we might need to remove later or well we will need to remove them later so let's define those um data structures so the first one is going to be the max Heap it's going to be an empty list the next one is going to be a Min Heap also going to be an empty list we now need that dictionary which is going to keep track of the count for each of the elements that are in our heaps so we're going to say the Heap dictionary is going to be um let's see collections do default dict and in because we're storing account okay we also need a result array to store our result now the first thing that we need to do is if you remember we need to basically handle the case of the first K elements uh in this case you know we're not removing anything we're not adding anything uh so we need to populate our heaps uh for the first K elements but we also want to make sure that the heaps are populated correctly so that way when we do the rest of the elements um they are you know correctly set up and remember to refresh our memory the max Heap is going to store the values to the left of the median and the Min Heap will store the values to the right of the median and we have said in the case that there's an odd amount uh of K then the max Heap will be allowed at most to have one more element uh than the Min Heap and that's how we're going to deal with um the odd case so let's now populate the he for the first K elements so we're going to say for I in range K what we're going to do is we're basically going to populate the Heap so we're always just going to assume that we can put it onto the max Heap and then we will take whatever is in the max Heap that needs to go into the Min Heap and actually check whether or not we're balanced after that and if we have to um fix the balance then we will so what we're going to do is we're going to say Heap Q do Heap push onto the max Heap uh and remember that in Python a heap by default is a Min Heap so to get Max Heap we'll use negative numbers so we're going to use negative nums of I now that we've added something to the max Heap uh potentially we need to move something over to the Min Heap so we're going to do that operation as well so we're going to say Heap q. Heap push and we're going to add to the Min Heap uh the value from the max Heap that actually need would now need to move over because of the median now we're not actually going to calculate the median yet because we don't have k elements but we're just going to assume that when you move one when you add something to the max Heap then something needs to get added to the Min Heap to kind of keep them uh in check so we basically take the Min Heap and we want to just take whatever is at the top of the max Heap so um basically that element that's closest to the median we're going to move it to the max Heap and then we'll account for the fact that we may have moved something that we didn't want to move momentarily so we're going to say Heap Q uh do Heap pop so we're going to top pop from the top of the max Heap remember we need to nullify it because we put it in negative and now we need to flip it um back to a positive cuz the Min Heap is going to operate as a normal Min Heap now what we want to do is we actually need to check whether or not the Min Heap has more elements than the max Heap right when we accidentally popped from um the max Heap we actually might have more elements in our Min Heap which isn't allowed right we said that the max Heap should either have the same amount of elements in the Min Heap or it can have one more if the Min Heap actually has more elements then this statement which we did um was we shouldn't have done that so the way that we're going to account for that is we're going to say that if the length of the Min Heap is actually greater than oops greater than the length of the max Heap then what we want to do in this situation is actually get rid of an element from the Min Heap and add it back to uh the max Heap so that way our Heap um invariant is maintained so we're going to say Heap Q do Heap push uh we're going to push onto the max Heap we're going to push on Heap pop uh sorry Heap q. Heap pop uh onto the Min Heap right so we take the positive element um the smallest element from the Min Heap pop it and then add the negative because remember the max Heap um needs to use negative numbers okay so at this point we basically have um our first K elements now at this point we need to calculate the median so what we're going to do is we're going to say if um if K is actually odd then we know we need to basically take whatever is at the top of the max Heap and the reason that we allow the max Heap to actually have one more element than the Min Heap is that in the case that K is odd then we just need to take whatever is at the top of the max Heap because that will be the um the median in our case so in the case that K is odd the item at the top of the max Heap will actually be the median itself uh if it's even then we just need to take the top of the max Heap the top of the Min Heap div add them together and then divide by two so we're going to check if K is actually odd then all we need to do is say result. append what we want to take the minus of whatever is at the top of the max Heap again remember the max Heap is storing negative elements here so we just need to flip the sign uh and then we take whatever is at the top there cuz that is uh the median in the case that we have an odd amount otherwise if it's even then we need to do some math here so we're going to say res. append um what are we going to append so we're going to say minus the max Heap so whatever's at the top of the max Heap plus whatever is at the top of the Min Heap uh whoops Min heap of zero and then we need to just divide this by two and that is our um median so pretty straightforward that's how you calculate a median um mathematically okay now we've processed the first k elements we've calculated our first median now we need to basically do this for the rest of the medians so um we want to basically just move our sliding window up uh by one each time now this is where this problem gets tricky I think there's two hard parts of this question understanding how to set up the Heap in the beginning uh this part is easier and then now what's going to happen is we have to actually sort out um how to add an element and remove an element and basically keep track of what to do with our heaps so pay attention cuz this is the tricky part I'll do my best to explain it so we're going to say 4 I in range so now we need to basically calculate the rest of the elements so starting at K up until the length of num so the rest of the numbers we're going to say that the previous number and this is going to refer to the number that we now need to remove so for example we have these three numbers when we go to our next one we now have taken this minus three added it to our window but we also need to remove the one because we obviously slide it over by one so that previous number is always going to equal to nums of the current index minus K so K before is basically the one that we just added by moving the sliding window one forward so now this number has been technically removed but it's still in our heaps because we haven't popped it yet so we need to basically add this to our Heap dictionary to indicate that this number is in our Heap but we have haven't actually removed it yet so we want to keep track of the count of how many numbers um you know we need to remove so previous number will now have its count incremented by one which later on we will actually remove it from uh the Heap but not quite now so oops uh now what we want to do is we actually need to determine what the balance of our Heap will be uh now that we're removing an element and that we're adding an element so remember that our Max Heap and Min Heap are consider considered balance in two cases right the first case is that um heaps have the same uh number of values so that's the first one uh or uh the max Heap has at most I can't type at most one more value than the Min Heap right in these two cases our um heaps are said to be balanced right because this is the invariant we set for our Heap uh that we want to maintain for this problem to work so anytime our we consider it to be balanced is if both of these things are true so now what we need to do is determine what the balance is based on this previous number so we're going to say that the balance is going to equal minus one if previous number is less than or oops less than or equal to the median otherwise it's one now let's think about this statement If the previous number is less than the median that means that when we're removing it from our window this obviously the previous number if it's less than or equal to the median this will come out of the max Heap because the max Heap stores everything to the left of the median and obviously this number is either to the left or it is the median which means that our Min Heap is actually going to be missing an element so minus one represents the fact that the Min Heap is actually minus one so it needs an element to be balanced otherwise if this number is greater than the median then that means that we're going to have to remove this number from the Min Heap which means that our Max Heap is now going to have one more element um or potentially two more elements than the um the max Heap right because remember it can either be balanced if they're the same or if there's one more so potentially there is one more element that we need to take into account for the balance right because this means that we have to remove from the Min Heap so that is the current balance and that is based on just the number that we need to remove from the left now obviously we just took a number so now we need to account what's going to happen to the balance so we're going to basically go through the two cases here so if the nums of I so the number that we just took is actually less than or equal to the median that means that it's going to go into the max heat because it basically will store everything to the left of the median or equaling to the median so if this is the case then obviously we've now just added a new element to our Min Heap so we can increment the balance and balance really just represents um kind of the state of the max Heap because that's really what we're interested in so we're going to increment one to the balance because we've now added an element to our um max Heap so in this case uh we want to then push the element onto the max Heap so we're going to push minus nums of I okay so that is the case when the number gets added to the max Heap obviously the flip side is if we're adding it to the Min Heap so in this case um the Min Heap will get an extra value so now the balance needs to get decremented by one because now the Min Heap is getting an element which throws off potentially the balance of our Max Heap so now Max Heap is potentially has one less element and we need to take that into account so that's why we decrement the balance here by minus one and then we obviously need to put that element onto the max Heap or sorry the Min Heap and we're going to do that now so we add I cannot type so we're going to add the number to the Heap here okay now what we need to do is take into account what is happening with our uh Heap right because our Heap may not actually be balanced so we're going to say if the balance is actually less than zero what does this mean if the balance is less than zero this means that the max Heap doesn't have enough elements right so we actually need to get rid of an element from the Min Heap and put it onto the max Heap because potentially uh we got rid of an element um from the max Heap and now the Min Heap has more elements so we want to make sure that we actually have our balance back so what we're going to do is we're going to say we're basically going to say Heap q. Heap push so we're going to push onto the max Heap uh an element from the Min Heap to basically restore the balance so minus uh Heap Q do Heap pop of whatever is at the mean Heap okay so that is the case when the balance is less than zero so this is the case where the max Heap needs elements otherwise uh sorry not else uh it should be else if the balance is actually greater than zero then that means that the max Heap has too many elements so in this case we actually need to get rid of an element from the max Heap and put it onto the Min Heap to balance things out so we're going to say Heap Q uh do Heap push so we're going to push onto the Min Heap whatever is at the top of the max Heap to basically rebalance the elements so we're going to say Heap q. Heap pop uh Max Heap and be careful here with the minuses because in this case we need to minus an element from the Min Heap to basically put it onto the max Heap and then here putting something onto the Min Heap we need to flip it from negative to positive because we're taking it from the max Heap so be very careful here because it's really easy to screw up um these minus signs and you need to be careful when working with a Max Heap and an in Heap uh in Python so uh and then there is actually no else case because if the balance equals zero then that means that our Heap invariant is satisfied so we don't need to do anything because the heaps are balanced based on the rules that we set which remember are that they either have the same amount of elements or that the max Heap is allowed to have at most one more element so in that case everything's fine we actually don't need to do anything there now what we want to do is we actually need to clean up our Max Heap from any elements um that potentially we need to remove right because we're storing in the Heap dick elements that we need to remove so now is the time to do this so while uh the max Heap still has elements in it and Heap dick of so minus Max heap of zero so basically while the Heap dict um has a count greater than zero for that element that's at the top of the max Heap we need to remove it because at this point um if it's in the Heap dict we only put the previous number so these are all numbers that have already left the Heap so we just need to get rid of them right so we need to decrement the count of that key in our dictionary so we do uh um we need to decrement the key of whatever is at the top of the max Heap and then we're just going to pop from the top of the max Heap to get rid of it so Heap q. Heap pop uh from the max Heap so that will clean up the max Heap now what we need to do is also clean up the Min Heap and the logic is exactly the same but we'll just do it for the Min Heap so while Min Heap and Heap dict of Min Heap uh zero is actually um greater than zero so while we still need to move things that are still on the Heap and it's at the top of the Heap now you may be wondering why are we only doing this for heap of zero because essentially we want to remove it when it gets to the top of the Heap because that means that um we can get rid of it in constant time um if you pop from the top of the Heap you don't have to then rebalance the Heap and this is the most efficient way to do it because if you think about it when we calculate the median which you'll see in a second we're only ever using the top of the Heap and the yeah basically the top of the Heap for both of the heaps here so we don't actually care about what other elements are in there we're only ever working with the tops of the Heap so we don't care about the order of the other ones we just care that the top of the Heap is what we need it to be so that's why that we want to take care that when something that should be removed from the Heap actually makes it to the top of the Heap we actually get rid of it because as you see the way that we calculate the median is only based on the top of the Heap or yeah basically the top of both heaps so the order of the other elements doesn't actually matter okay um that little ramble aside let's now do the same thing so we need to decrement the count of whatever is at the top of the Min Heap um by one and then we need to pop from the Min Heap so Heap q. Heap pop uh from the Min Heap okay now what we need to do is simply just uh append the result for this case so as you can see we still haven't calculated the median now we've taken care of uh basically balancing the heaps making sure that we removed an element correctly based on how the previous element was removed and then we also added our new element so we took that into account now the last thing we need to do is actually just calculate the median so what we can do is just copy and paste this code here um for calculating the median and paste that there fix the indenting and then this will basically calculate the median again if it's an odd um k then we just need the top of the max Heap otherwise we do the mathematical calculation uh and we just append that to the result and that's it so once this for Loop ends and where's my indentation all we need to do is simply just return our res and we are done now tricky part did I make a mistake coding this up I would say yes but let's see uh yes okay what happened here less than median uh oh shoot I didn't calculate the median um let's see hold on um uh oh okay I need the median from up here um let's see oh I need to keep track of what the median is okay um how can I do this without actually calculating it uh okay yeah so I'll just I'll create a variable for this then uh median yeah so we actually need to keep track of the median so we don't have to do it each time so anyway uh median will equal to minus of Max heap of zero and then we will justad the IMM median so as you can see we're doing some live coding here um okay so and in this case the median equals to that and then and we're going to pen the median okay so in this case we also need to do this and now we're just going to recopy this code here and fix that and now we should be okay yes okay Moment of Truth place your Bets did I it up or not 3 2 1 hey who knew I'm a star okay so what is the time and space complexity for our algorithm well as you can see we're really working with two heaps here and you know they're not the operations aren't nested for them um so they're just really going to happen side by side so for any Heap you know how many elements are in the Heap at once right so it's going to be n item or k items in the Heap and how many times do we need to basically do all of this Heap popping cuz you'll notice here um well actually we do um push things from the Heap and um pop things here so really it's like n log k um for the uh time complexity because obviously we have K elements in the Heap and then we have you know n time n elements that we have to process in our nums um so that is going to be the um the time complexity here so we have that uh what else do we have for the space complexity well we have the Heap dick so the Heap dick is only going to store you know the K elements that we have actually no because we clean it up each time so it should only store at most um three keys I think but it's fine um and then we have the max Heap which obviously is going to store K elements and the Min Heap so it's like Big O of K uh plus Big O of K but we know that this is just ASM totically the same as Big O of K because we get rid of the um the constant uh when we do it so it's like 2K but this is just like Big O of K uh okay so yes time complexity n log K and the space complexity is um Big O of K so that is how you solve this problem Oh God this video is getting so long my brain hurts this is definitely one where it's easy to understand how to do it but coding it up is quite tricky this is definitely a hard question I will agree with the um the rating on this one anyway hopefully this video helped you hopefully I was able to explain what to do with the heaps cuz it is uh quite confusing I will post the code in the um comments section because obviously it's a lot of stuff it doesn't fit on one screen when I'm recording this so I will post that for you so you can um reference it so you don't have to like go through the video otherwise thanks so much for watching hopefully you enjoyed uh me suffering through this question hopefully my explanation helped you if it did leave a like and a comment for the algorithm subscribe to the channel if you want more content like this otherwise thanks so much for watching and I will see you in the next one goodbye
Sliding Window Median
sliding-window-median
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values. * For examples, if `arr = [2,3,4]`, the median is `3`. * For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`. You are given an integer array `nums` and an integer `k`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. Return _the median array for each window in the original array_. Answers within `10-5` of the actual value will be accepted. **Example 1:** **Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3 **Output:** \[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000\] **Explanation:** Window position Median --------------- ----- \[**1 3 -1**\] -3 5 3 6 7 1 1 \[**3 -1 -3**\] 5 3 6 7 -1 1 3 \[**\-1 -3 5**\] 3 6 7 -1 1 3 -1 \[**\-3 5 3**\] 6 7 3 1 3 -1 -3 \[**5 3 6**\] 7 5 1 3 -1 -3 5 \[**3 6 7**\] 6 **Example 2:** **Input:** nums = \[1,2,3,4,2,3,1,4,2\], k = 3 **Output:** \[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000\] **Constraints:** * `1 <= k <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array? Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done. The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?
Array,Hash Table,Sliding Window,Heap (Priority Queue)
Hard
295
1,879
hey everybody this is larry this is me going with q4 of the bi-weekly me going with q4 of the bi-weekly me going with q4 of the bi-weekly uh contest 53 um minimum xo sum of two arrays so this one i thought it was tricky when i first look at it but the key thing is noting that n is only up to 14. um so then this becomes a matching problem where you know for bigger ends you can actually do stuff like um maximum bipartite matching and stuff like that which we're not gonna go get into um which you know you can run for ends which is bigger because you're gonna do matching in like n cube or something like that um but that uh because n is 14 and also max foe is probably not going to be on an interview knock on wood for a long time uh you know um yeah so n is 14 is going to become one of the most hated thing you probably ate it uh which is bit mask dynamic programming i had to do a video on this at some point um like a special video just on the bid mass dynamic programming maybe i'll use this as an example so watch out for that uh i'm you know even as i'm talking now i'm getting requests to do this in more detail but the idea here and is that okay you know for the purpose of matching um i know that they said that you can oh actually i was wrong for some reason when i first read this i read that you could rearrange the numbers one and numbs two but and actually that would have been slightly more harder though very slightly because for the purpose of this problem it doesn't matter because you could fix nums one is what i mean actually i assume that you could rearrange numbers one but it doesn't matter because you know you rearrange both arrays then you might as well only rearrange it one away and in this case again i'm gonna do a really two minute bit mask thing which is that bit mask it's just um is just an array of buoyance you could think about the bit mask is you know let's say we have something like this uh it's a bit mask and that's maybe too long for this problem um just as you go to an array of true false true uh dot you can maybe even you know to put it more concisely just t f okay i got a little blazer over there but yeah so basically you have a disc right and that's basically the idea and what is the point here right is that with n is equal to 14 you can clearly see that um they're two to the fourteen possibilities here right and that's basically the idea of a bit mask i know that is terminating to look at bits and stuff like that um but that's all that is it's just an array of bits that you can use to cache because you compress it into a number because 2 to the 14 um what is 2 to the 14 i'm pulling out my calculator right now to the 14 is 16 000 so that's going to be fast enough um but yeah um and then the funky things that you see here are just operations that are basically if you want to look at the ray equivalent let's say mask is suddenly an array of booleans that's just a mask of x is equal to true which i know that you can simplify a little bit um but you know and if you look at this mask or this bit shift thing uh this is just equivalent to uh set mask of x is equal to true and then you do a recursion of it on it right and the bitmasters allows you to memorize it in an easier way and that's all that is um i know that i get a lot of questions about it um but you know this is if we haven't used this yet oh sorry uh i messed this up actually if this is equal to force right yeah um so this means that we haven't used this yet uh well this means that it checks whether this is true but we check this as you go the zero part is the fourth part so basically we check if the x element is not used we used to we set it to true we said um we used the x element and then we just and then the cost of using the x element is just this xor function which they give you right um you know like that's the sum because you want to sum up all the xor so you go okay so let's say for the num sub one of index we match this with the num sub two of x then we use it and then we do a recursion on it and that's pretty much it um i know that you know this looks intimidating if you're not into bit masks but it really is that's pretty much it um anyway yeah so then now for every index we go from left to right of nums one at a time we go okay web number one of index we want to match up with num 2 of index x and then we do a recursion and now we look at the next index and here like we said we updated the mask to set that bit to true and that's pretty much it um and then the dynamic programming part i'm not gonna you know dwell in uh detail that much because i think i went over the transition um once we matched all the numbers we returned zero and that's pretty much it um yeah and you of course start with zero with the zero index and this zero just represents um a boolean value of all force values um and we said infinity and stuff like that but that's pretty much it and i know that i didn't go into detail that much but hopefully that's enough uh for you to have the idea um because i if you watch the video of me sobbing lived in the contest i think i saw this in three four minutes and i think that's also you know a lot of the top people solved in three to five minutes for that reason because they just recognized and practiced the bit mask whether that comes up when an interview is another story i personally don't think it should but i don't know certain always for example have a way of doing it so you know you let me know how that goes for you um yeah that's what i have for this one so feel free to watch me salvage live during the contest even though i think for the most part i jumped right straight into it so you probably just watched me type this up but you know uh oh yeah just to go over the complexion a little bit i missed that so index could be from 0 to n so the number of states is o of n times 2 to the n and then you know and for each one we do a for loop of n work so total time is equal to o of n times n or n squared times two to the n um yeah and space is of course we have o of one for each space so it's just the number of states which is of n times to the n uh for time for space uh that's all i have for this one watch me stop it live next back to the other one looks more let's minimize okay and it's 14. this is pretty easy actually i didn't notice the end before so then um was just painting for so long it's just over having issues again that would suck ready should we only have 14. oh did i hmm the pending is slow okay that's not good huh oh no this is oh no whoops whoopsie daisies uh the testing is too slow for me to shift any locally maybe okay let's see should be fast enough yeah that one's pretty easy yeah i hope that was a good whatever uh hit the like button to subscribe and join me on discord let me know what you think about this problem and i will see you later good luck later bye
Minimum XOR Sum of Two Arrays
maximum-score-from-removing-stones
You are given two integer arrays `nums1` and `nums2` of length `n`. The **XOR sum** of the two integer arrays is `(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])` (**0-indexed**). * For example, the **XOR sum** of `[1,2,3]` and `[3,2,1]` is equal to `(1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4`. Rearrange the elements of `nums2` such that the resulting **XOR sum** is **minimized**. Return _the **XOR sum** after the rearrangement_. **Example 1:** **Input:** nums1 = \[1,2\], nums2 = \[2,3\] **Output:** 2 **Explanation:** Rearrange `nums2` so that it becomes `[3,2]`. The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2. **Example 2:** **Input:** nums1 = \[1,0,3\], nums2 = \[5,3,4\] **Output:** 8 **Explanation:** Rearrange `nums2` so that it becomes `[5,4,3]`. The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8. **Constraints:** * `n == nums1.length` * `n == nums2.length` * `1 <= n <= 14` * `0 <= nums1[i], nums2[i] <= 107`
It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation
Math,Greedy,Heap (Priority Queue)
Medium
null
330
Hello Everyone Welcome Page Ki Kundli Channel Problem Hai Its Title Is Packing And What It Contains Is Vivechana Sorted In Teacher Hey Number Panel In Teacher End And Fetch Elements Directions At Any Number Indore Range One Comment That This Is Just Tender For Individuals from some elements are in that it is telling that the interior is there but it will be delicate hunter yogi and 10 Kevin will be add we have to add some such elements in it which people report time our it should come within this range one comment how to this What should be the condition to come in the range desi ghee in hindi will be narrated by woman in which mo will give steering element will be upvan comment like forest and tu that if both of these are in then mind is in the house element in this way You can get hesitation, you can get it is written on any stadium that do not use Example Mahal, Amazon and there is a family tree of their values, then there can be minimum element own in it, whatever is given in the answer has been created. So let's see the time and place of 114, whereas we need to add one such element in it so that the other one is explained to us, what is the maximum, what will have to be done for that, host and okay, if I add that, then which Result time, our back cover will come, it is six, one element is needed in it, next let's see the pipe commandant to one, this N value is 120, how much more is it now, how many minutes in 16 years and all, two elements of hello how to make are telling two and phone a. Poster Bollywood, that's why they will have to do something like this, that I can't find the crime of moving such numbers between two elements, which if added to the net in that period, if the time is not wasted then they will do something like this to check the numbers. Get and there is an element in the middle of it, you send a message, now I will add this number so that I understand that this can happen, I used to do the same for Raghu Dixit, we have to do the entire journey, first of all You make an account for the elements that how many elements will come inside the village and then we do not take one. It is possible that the time of the element which is given in this video is previous, we will also calculate it from zero. And we will take a battery saver on, let's set, this is my cat, she is there to trace the cases, this is to see every element in the world in reverse winter, whether any element is adjusting among them, instead of telling in 1857 that two If we do three or four skin elements, then which of these alarms have been set in the parts in which 120 K will be opened, first of all we do this, if we have to enter for K, then the positive note will go till here and then what will we do? Basically a that we will check that the number which is required is a movie at event is to be found if the previous element from the previous element all means a variable and one more city is located we become plus is meaning what are you saying that which is Proposing deep yes your mother has taken it I from Mandsaur you check like made so now in this fight wave I from one and add one more to this it is asked meaning we try to blue print that if you If I get it, I will give you a miss call and if I don't get Udal 2, I will add two to it. If it is not one, then what will I have to do with it? I have got an event in the answer, in the middle of it, you have increased that page of the village. I am preparing the answer for 'Mara' and preparing the answer for 'Mara' and preparing the answer for 'Mara' and now we have explained it. Just recently, we have added a number to it. The number one side is sampling, so what is it doing in this condition that Poonam wants a value of plane, turning screen. I got more eggs than Lakshman, so what does it mean that any judgment can come in between like to and thi, this can be savings, so that is why I have carried the length, first mix the time, then for is greater than, repeat from the relation. To is not inside it, there is sodium in the area inside the face, Pushpendra is not there, so we did the same thing that don't you gave a big one and also increased the value of the union, I edited the segment in it, there are scientists, so we added it, meaning it should be evening now. All that will become the plus pillar which is the Premier League and Champions. That element in it is its ocean and if I call this condition, then what will we do, that we will fill the electricity, they will add us from that number only, dialed 100 numbers that all this will work, support here. It was already ready, you are looking for it for now, so I took it, so I came here, nothing happened, it became like the value of potato, then I checked it for the whole day, the expenditure is more than the whole life partner, understand that among the vegetables of Zero T.I. It was done, understand that among the vegetables of Zero T.I. It was done, understand that among the vegetables of Zero T.I. It was done, now we have to check in it, so if it is inside then only he is seeing the moist side to better than infection i.e. whole tantu infection i.e. whole tantu infection i.e. whole tantu condition Falguni, so it means that you are the one in it, the address is already there, so we don't have anything in it. Will be able to do it, that's why I killed the value of time, Samiti Bajju, I did it, if this number goes, I have added it, then understand that he is the Egyptian that if this is done now, we will add this quarter inch in it that if sometimes this will happen. What I mean is that there is a complete reversal in this and sometimes the shame that we have at that time, we are related to this, we are related to you, we are my target, their value is the target, so sometimes what will happen is that it will completely collapse. In this, my friends told me that I will get it before Bigg Boss, there is a demand that I will get it only then what happened in it and if I get it, then the missed call will come out, then I will have to decide that who we are and yours. My target is to reach more than that, if it is more than that then the fruits will come out and if it is less then we will travel in it till the time the rediment is over that it holds and what will happen I will also do this now. That's it, all the Shivam traders will do it, all the Madams will do the travels and I understand that the second one will not be found equal to inches, so what will we do for this we can add more numbers in it but inside we will check. Shyam, what will we do with our over and toe target, then what will we do to increase the volume of the account, that is, we are going to calibrate it, which element will we do in it, understand something, this is a well-known review, now I have added one more element in it, is a well-known review, now I have added one more element in it, is a well-known review, now I have added one more element in it, I have added one plus one. It means that we have got the target and have taken all the elements, then we will have to add them to fold the elements. I used this belt to fold the elements. What should I hide from this, the account gets heated due to the target, you Samudra Laxman one value and add it. We will do this each time, if we reduce it again, then I will add ghee to it, then we will keep doing it like this, then it will happen from both these forms, we will get better than the evening of the end of the year, like there is a flower of mill in it. We will tell the volume and turn the answer. Add as many elements as you want. If it is HP, then we will point it and see that Yo has run. So this is the code. See, now we submit it. Do what I said in this. Now I have to tell you that yes, I have made a mistake, I did not give increment in this country because I added the number that we have and I did not increase the volume, so this leg remained here, this layer came. After submitting it, let's see if it got stopped, then this way on Sony SAB, if you have understood this explanation, then do like and share it once and yes, if you have not subscribed till now, do subscribe.
Patching Array
patching-array
Given a sorted integer array `nums` and an integer `n`, add/patch elements to the array such that any number in the range `[1, n]` inclusive can be formed by the sum of some elements in the array. Return _the minimum number of patches required_. **Example 1:** **Input:** nums = \[1,3\], n = 6 **Output:** 1 Explanation: Combinations of nums are \[1\], \[3\], \[1,3\], which form possible sums of: 1, 3, 4. Now if we add/patch 2 to nums, the combinations are: \[1\], \[2\], \[3\], \[1,3\], \[2,3\], \[1,2,3\]. Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range \[1, 6\]. So we only need 1 patch. **Example 2:** **Input:** nums = \[1,5,10\], n = 20 **Output:** 2 Explanation: The two patches can be \[2, 4\]. **Example 3:** **Input:** nums = \[1,2,2\], n = 5 **Output:** 0 **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * `nums` is sorted in **ascending order**. * `1 <= n <= 231 - 1`
null
Array,Greedy
Hard
1930
199
hey guys how's everything going this is Jay sir who is not good algorithms I'm recording this video to prepare my interview in this video I'm going to take a look at one and I binary tree right side view wow we're given a binary tree imagine myself standing on the right side of it so view the tree from right return the values who knows I can't see in order from the top to bottom okay so 1 2 3 something like this so it should be 1 3 4 well it's obviously that this should be a BFS right breadth-first search I right breadth-first search I right breadth-first search I mean we should get each layer get to the nodes by layer and just get to the right rightmost items right so yeah it's obvious which BFS how could we handle BFS entry remember it's Q right yeah let's create a queue and let's create a cube push through in and every time we get the items out and push the next to the layer items in right cool that's cute we in generous could be use an array to do it because we have shift method and it should be route right look at first we push it in so wow Q Nance wow there is elements in a queue hmm so how do we do it do we have a new method new elements hmm no we just push them or into the queue so every time we will get the elements all over layer out and then push the next node in right cool but how should we know because we are using the same queue so how we how should we know that it is ended Wow there's a trick we could push a new normal No in right or there's a base not a method using index let's try both first I'll use it using adding new method new one node in a queue push and a new as ending I tend to fire the fire okay cue push look let head Wow head equals Q the shift so this will help us get some the pushing a kettle night layer by layer so this one would put to everything okay for the result would be empty roots values I can see if this new okay let's don't forget if food is no nothing right so and then we could say it is initialize as this and okay now oh my bad every time we get earlier and we will get a layer we will do what we will update to the update last one in every while loop and sets the value to it right so here when this is done we get the head but it's moved and then we said we push the element right but we need to get the index let's say let write most Wow oh okay here set it to head Val and this will be updated but there's only one variable this will be Abaddon over ever in a game for each layer right and they add the last one it will be the rightmost one so and then we should have just we could just push result and push the rightmost Val but and don't forget we need to push new elements in the queue right okay if and left push the left if okay right cube push it right and when each layer is done and then push the rightmost vowel right and then last we will return the result let's review this one more time before we run the code if the new is renewal we return empty and then we use array and push the routine and queue and every time we will pitch a pick up all the elements and we push a new as an indiana fire and identifiers every time we get to the head we're using shift and we update the rightmost file to that and push them out the elements I'll push the nodes in a lack next layer to the queue and then yeah so that's it let's run a code what our of memory what have we what did we what have what did we do OMG Eric a war with rich water out of memory hmm ready if you three even well if it is only one two three still out of memory oh wow there's my solution run our wire loop while its ninth is bigger than zero we're pushed in war and then shaped it until we get the new leaf left laugh or push left if right we push right and then we push the rightmost vowel so this should end what is wrong ah one so there's one element we shift we keep shifting we push an or we shift this will end when we get new or right this is weird something I didn't see oh my god my cool or accept it so oh wow I made a super stupid mistake now let's analyze the time a space complex a time every day I was actually Travis for once so it's linear time space the result these not should not be counted as extra space so we're using the Q as a helper Q and this worst case will be the length of the nodes right so worst case is linear first cool now let's recall that there's another method another way of writing it without using an extra rule checking and of layer by index I pretty personally I like this check I like this and I like this trick well it's easy to understand right sometimes but sometimes we need the newer in the queue for that case we need to push the undefined well the there's still another way instead of pushing the nor we keep track of the index right or not yeah we say the we could check get the last note of layer equals Q dot and then minus 1 right and we could compare that while we get hit we shifted while what while we will stop if hat equals to the last layer we cooperate correct yeah this is also work this also work yeah well this is another way instead of just getting a top element and do things we should do something like counting right like count of this layer equals Q dot min this is the account so we should say when there is nothing when there is no elements in this when there is no element when there are still elements we get to the head it gets the head is Q shift this should still work right hmm no kind of this layer Const oh my bad yeah this should work also anyway this is by checking index or check the element or checks X extra any identifier so I personally I like this way better mm anyway so a bit helps UNIX what see you next time bye
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116,545
155
Are Hello Guys Welcome To Disrespect Interesting Problem Encoding Series Game Means Tech Web Designer Stepmother Spooch Push Pop Top In Relieving Minimum Element Inconsistent Time Malnutrition School Push Element On To The Stock Pushp Options One To Remove The Element On Of The Best Top Functions Me To The Top Elements And Get Man Functions Where To Give Volume Minimum Element Which Is Present Not Tax Let's Get Started See Lifting Co Fruit Force Approach And The Let's See How The Office Meeting Song Office Of Profit Pimple Declaring And Stock Swelling And Symbols And They Want To The Storm Male Elements in the White Push Function Which Can Give a Start Floral Extension in the Function Which Can Give a Start for Boys for the Top Function Winters That Don't Stop Okay Suicide Note Brute Force Approach 9 And Will Work For Optimal Solution Slap To Get The Minimum Element So What We Can Do You Speak And Declare Another Tax Rate In Polytechnic In Test So And Every Place Too Equal To Tabloid Over All Elements No Stack And Find The Minimum Of This Element Screen System Very Alarm Eminem Time Complexity Is Very High For This Approach That were taking birds after vs any current processes and oil S2 not equal to wildest 220 sowe yes you still have elements and you can just to find out of elements present minimum element and element will get in which lies the minimum age limit should declare Ant Man Is Equal To A Maximum Of Integer Value Digestive And Stop Is Lewis Minimum 1 * Lewis Minimum 1 * Lewis Minimum 1 * S2 Laptop And Keep Off Popping Elements From S2 And Queens Baton Minimum Elements In All These Processes Brute Force Approach And Time Complexity Against Sports School 10 But Not Worked at work for small test cases but when they have lost cases to this dish Special Feature To Take Solace Straight Of Some Time Complexity With Tenth Space Complexity So Let's Do Something Syrup To Switch Off The First And Behave The Second Taste Second Step Let Me Just To Rome Minimal Element Hokar Sworn In This Youth Addition Help Track To The Song S2 Servants To Remove Uneven Surface To Two And Fours Element In Stool Sample Play Store Ko Open Pappu Just I Am Posting Five Step One Should Not Pushpa Inspector Because Situ Is Already Smaller Than Five And Five Great And Two Some This Element With Smaller Than Two Family Now Opposite But In This Case Is Greater Than 500 Note Disadvantages Of Asking I Asked Element Support Only 2090 A Smaller Than Two So They Can Push Heroines Tattoo Not Let Go Of I Asked Element Sportsman A Cement Is Three Taking And Not Possible In The Step Of Interest to record search greater dhiru 9 ask 752 push element that this - 110 shell posted in distic and often taken - 110 shell posted in distic and often taken - 110 shell posted in distic and often taken tag recorded to roam elements in this matter smaller than previously seen element hokar approach in 110th and its and tried to follow this approach start ask Shravan Adam Indore and Pushp Function Was Left To Push Elements In S2 I Will First Aid Kit smt So S It's NT And This Access Loosening Guddu S2 Top In This Country Celebrates It's Okay Somewhere Give A Push Elements Of Elementary Nuvve The Function Of Elements In The first to fifth element - 1m subscribe to fifth element - 1m subscribe to fifth element - 1m subscribe second quarter top most element of his address to recall dene laptop very element button's cea introduction element and cheap flour this to paul function hair per 30 ne swt is not exist in a two shoulder top most element and Not equally add to the end cases have to pause element from admin of elements from traffickers 10th not exist in this will be my logic pro x 's note of a protective co swadesh note also 's note of a protective co swadesh note also 's note of a protective co swadesh note also anti switch of a student end of s.st anti switch of a student end of s.st anti switch of a student end of s.st subodh station And also anti tobacco cessation appointment after thm and s road top equal to a student option in that case I will have to point element from its 2nd they have to begin from northern non stop this point for the top most elements in function will be able to Give A Good Time Complexity And Two Daughters Will Have Element To A Minimum So Let's Often When Beauty Of Effigy Of Contract Class Events For Must Be Called Him Into Contact With No Arguments Ohm Egg Students Café And Button To Give Back It's Allied Services Student mt6592 That This So let's check this dish friends this and accepted solution and shifting from the test cases after passing in the recent wonderful that Surya vacancy I think they should have been finally Bigg Boss sir yes find som rate many times faster than forty percent solution shine 125 this Is Not Declaring Festival Function Print Remedy 2012 Elements Are You Not Give You The Service You Are A Very Simple To Enter Into The Giver Plus And Can Give Are Not To Push Element Into English Hotspot Function Will Be Dress Like Abstinence Element From And The Development Will Be Red Beacon Plus Size - One Who Deals For Red Beacon Plus Size - One Who Deals For Red Beacon Plus Size - One Who Deals For Elements Visited And Earn With Resizer Is Red Entry Size To Size - 110 Week Is Red Entry Size To Size - 110 Week Is Red Entry Size To Size - 110 Week And Decrement Size Early Morning Pollution And Wife Love You To Give The Top Functions Victims Were Torn Hey Joe Size minus one feature top function and getting and minimum elements study in this case which can just visit on the minimum element will add to all elements of and surindra its yagya no to complexity of everything will be quite powerful and wicked just divided over all the element Derives from the Red Fort with * Are Dot in Bilaspur Fort with * Are Dot in Bilaspur Fort with * Are Dot in Bilaspur Apne Minimum Element Subh-Morning Another Method Apne Minimum Element Subh-Morning Another Method Apne Minimum Element Subh-Morning Another Method and Vikram Solar Same Problem and Additional Benefits Solution So Let's Amazon is a Solution Yes to this Accepted Solution Don-2 Accepted Solution Don-2 Accepted Solution Don-2 Stock Approach Has Actually Better in Time Complexity Different Immersion Times More Than Light This Illegal Absolutely Minimal Function and Object Wherever All Elements For A Long Time Complexity Subscribe Button Thank You
Min Stack
min-stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `MinStack()` initializes the stack object. * `void push(int val)` pushes the element `val` onto the stack. * `void pop()` removes the element on the top of the stack. * `int top()` gets the top element of the stack. * `int getMin()` retrieves the minimum element in the stack. You must implement a solution with `O(1)` time complexity for each function. **Example 1:** **Input** \[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\] **Output** \[null,null,null,null,-3,null,0,-2\] **Explanation** MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 **Constraints:** * `-231 <= val <= 231 - 1` * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. * At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
Stack,Design
Easy
239,716
1,732
hello everyone welcome back here's van damson and in today's video we will tackle an interesting problem about finding the highest altitude so we are given an RI that represents the net gain in altitude between two uh points and our job is to find the maximum altitude the biker can reach so let's start our coding in JavaScript so let maximum altitude be zero and let current altitude B 0 as well because we start from sea level and four G of gain current altitude will be plus G and if current altitude is greater than maximum altitude we update Max altitude to be our current altitude so finally we return Max altitude so there you have it so let's run test cases to see if it's working so hopefully it works yeah so it's working and we started from zero and then minus five one and five so and then zero and minus seven so maximum uh level we have reached is one uh so there you have it so let's run it for unseen test cases to see if it's working as well so for unsynthesis cases it also working and with respect to memory with bits 98 of other solution in with respect to runtime 87 so also really good and uh yeah so algorithm here is really simple uh so we are doing we're starting at the C altitude of zero and we keep a record of highest altitude we have reached so far and we then look through the gains list adding each gain to our current altitude and if any points the current altitude is higher than our recorded maximum altitude we update the maximum altitude and return it as output so great our function work as expected and this problem has a linear time complexity and constant space complexity of one so uh yep I hope you like this video and if you have any question please leave a comment and also subscribe for more uh JavaScript coding tutorials and solutions and remember keep practicing stay motivated happy coding see you next time
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
746
hi everyone welcome back to lead coding i am your host faraz so first of all congratulations to everyone those who have made this far into the playlist now we are actually solving questions on dynamic programming which is one of the favorite questions of interviewers so let us start solving a few questions so that we have enough practice right in front of us we have a question called minimum cost climbing stills on a staircase the ith step has some non negative cost i once you pay the cost you can either climb one or two steps you need to find the minimum cost to reach the top of the floor and you can either start from the step with index 0 or with the index one so basically we are given an array now in this area each index is having some cost and as soon as we step on that index we have to pay that much cost let me just take an example here 10 15 and 20 right or maybe let me just take this one this example so here we have these steps index 0 1 2 3 4 5 6 7 8 9 so i am supposed to start either with index 0 or with the index one so these are the two places from where i can start now if i start from this index 0 i will have to pay 1 i will paying 1 this is the cost and i can either go to this step or i can jump to this step because it is given that we can either jump one step at a time or two steps so i'm clever i will be jumping to the step number two i will again pay the cost because i'm reaching here and the cost here is one then i can either jump here or i can jump here so i will be jumping here i will pay one more cost then i will be jumping here one more then over here plus one and finally till the end plus one so one plus one total is six i will have to paste six as the total cost now how to solve it using recursion so in recursion we are only bothered about the current step okay so we are only bothered about the current step and equation we are not bothered about the future steps because we are going to explore all these possibilities in terms of recursion how we are going to think first of all we are starting from either this place or this place let us say we are starting from this place the step zero okay how much cost will i have to pay i will have to pay one let me just take a lighter color so i will have to pay one because one is the cost at this place this is definitely something that i will have to pay now i have two options either i can jump to the step two or to the step one from zero i can make these two jumps okay but i don't know which one is beneficial so recursion is going to give me the answer for both of these possibilities my option 1 will be if i jump to the next step that is i plus 1 my option 2 will be when i will jump to i plus 2. so i will get the answer i will get the optimal solution for both of these possibilities using recursion and whichever is better i will go i will choose that possibility now how to do this in terms of code let us just go and code it out int help int i this is the ith step i'm currently on then i will have a vector of int c cost okay so if i is equal to c dot size in this case return 0 because we reach till the end and now we don't have to go further that's why returning 0 from here otherwise i have two options int option one is two is to jump to the next step so if i jump to the next step i will call recursion to the next step i plus one and c so this is going to return me the answer if i jump to the next step that is i plus 1 at step now the option to i plus 2. so this is going to give me the answer i will ask recursion to bring me the answer if i jump to the i plus 2 step and this is going to tell me the answer when i jump to the i plus 1 step now i will compare both of these so i will be returning minimum of option one com option two whichever is minimum plus the current cost that i have to pay there is c of i this is something that i have to pay because i am standing on the eighth step so this is it i think let me just return from here starting from 0 and c also i can start from 1 okay so for that minimum of this comma i will call the same function starting from 1 and c let me just try to run this oops stack overflow why is it giving a stack overflow see these kind of errors you need to handle you must know how to handle these kind of errors because when you are when you will be appearing for your online test the online coding challenge then these kind of errors will appear now as soon as i read the stack overflow i know that this stack is overflowing because of so many recursion calls infinite recursion calls now i have to check the condition how am i getting the infinite recursion calls it is because of this condition the base condition this is not proper the reason is i can either jump to i plus 1 or i can jump to i plus 2 as well so that is why i can become greater than c dot psi so if i is greater than or equal to c dot size then i will be returning 0 okay now i will run it again it is giving us correct answer let me just submit this if the solution is correct it should give us time limit exceeded yes we are getting time limit exceeded you will get time limit exceeded when you are taking a lot of time solving this question now why are we taking a lot of time let us see why let me just remove this so let us say i have the given array zero one two three four five of six size okay starting from zero to five now i can start so if i start on the zeroth step then i have two options either to go to the first step and compute the answer for this one or go to the second step and compute the answer for this one this is my option two okay so if i want to find the answer for this step one then that will be equal to c of one plus best of both these options that is option one here and option two here the first option is to go to the step two and then compute the answer the second option is go to the step 3 and compute the answer okay now to find the answer if you are standing at the step 2 it will be c of 2 plus again 2 options the first option is to find the answer when you are standing at the step three and second is to find the answer when you are standing at the step four all right okay so let me just explore this further now for step three it will be c of three plus option one is to find the answer when you are in step four and option two is to find the answer when you are at the step 5 okay similarly if i explored for this one it will be c of 5 plus if you are on the step 6 or you are on the step 7. now both these 6 and 7 these are actually greater than or equal to the size of the given cost area so we will be returning 0 from here we will get 0 from both these so 0 taking minimum of these 0s so that will be 0 plus c of 5 the cost of 5 that will be returned back okay and so on now again if i want to explore this site it will be c of 2 plus minimum of both these options option 1 and option 2 the first option is to compute the answer when you are at the step 3 the second option is to compute the answer when you are at this step 4 now can you see something we are computing the answer for 3 here we are computing it here as well and we will be computing it somewhere over here as well so a lot of repetition again for four here for four we will computing here we can see there's a lot of repetition so once we calculate the answer for three in this case why to compute it again here y two again branch it like this going to four then 5 then going to 5 and 6 why to branch it like this again if i want to answer if i want the answer for 3 i will have to again explore it to 4 and 5. so once we found the answer when we are at the step 3 that optimal answer we should store it somewhere now to store it we can use a vector so we can create a vector of int dp of size uh let me just create instead of vector let me just create an array so int area of size how much how many steps can be there at max thousand so let me just make it of size thousand one then i will initialize this i can use this function mimset dp minus 1 comma size of dp i am initializing this dp with -1 or i can use a for loop and go with -1 or i can use a for loop and go with -1 or i can use a for loop and go to each of the index and make that index as minus 1 okay why do we do that because minus 1 will denote that this state is not computed this state of dp is not computed so i will come here i will llc if dp of i is not equal to minus 1 that means this state is already computed it has already occurred in the past and we stored it we computed it and we stored it now if we had that stored we can just return dpfi otherwise if it is equal to minus 1 that means we have never come to this state and we need to store this state after computing so dp of i will be equal to this before returning we are storing it let me just try to run this now okay so it should be accepted now hopefully yes it is getting accepted so this is how you solve dynamic programming questions this one more thing that i want to do here this is basically a top down dynamic programming i want to convert it to a bottom of dynamic programming and then you will see that we will be able to actually make some good changes into it so how to make it to the bottom of dynamic programming that also you can do with the help of this particular code okay just keep just look at the code line by line so if i is greater than equal to c dot size that means return 0 so for all the indices which are greater than c dot size i will have to make the dp as zero okay let me just make the dp over here again vector of int dp of size serial size plus 2 y plus 2 because we can go to i plus 1 and i plus 2 i'm just keeping this to be on safer side now what is dp of okay let me just create n here and n is equal to c dot size n plus 2 what is dp of n dp n should be 0 what is dp of n plus 1 it should be 0 again okay because of this condition when i is greater than zero size for all the indices which are greater than c dot size which are greater than or equal to n it should be zero next now we need to compute the answer when we are on the ith step and to compute that we will need the answer when we are at the i plus one step and i plus two with step so basically to compute the answer for the ith step we need the answer for the next two indices as well so for that i will be going backward i is equal to n minus 1 i greater than equal to 0 i minus dp of i it will be equal to c of i the cost of i okay the cost from here plus minimum of dp of i plus 1 comma dp of i plus 2 okay so this is my option 1 this is my option 2 you can see this is my option 1 this is my option 2. now as we are going backward from i equal to n minus 1 to i greater than equal to 0 and we already have the answers for dp of n and n plus 1 so when n when i is equal to n minus 1 we will compute it like this dp of i plus 1 that is dp of n and dp of n plus 1 we already have them so we will get the answer for dp of n minus 1 then we will go to dp of n minus 2 for that we need the answers for dp of n minus 1 and dp of n so that is why we already have all these states to compute the current state and what do we have to return minimum of dp of 0 comma dp of 1 because we can either start from 0 or 1 okay let me just run this again uh yeah we need to remove this so it is giving us correct answer let me just submit this now so this is basically a bottom-up dynamic so this is basically a bottom-up dynamic so this is basically a bottom-up dynamic programming code okay now there's something that you can notice here to calculate dp of i we need dp of i plus 1 and dp of i plus 2 and then we are taking the minimum of these two okay now let us say this is the dp array that we have this is the dp array and here our i is starting from 0 till let's say 1000 okay so we are storing all these elements inside the memory but to calculate the current that is the ith element we only need the next two element so let us say if you want to compute dp of 3 we must have already computed all these dps after 3 so we need dp of 4 and we need dp of 5 to compute dp of 3 but all these starting from dp of 6 till dp of 1000 all these are waste we should not store them okay we should not store that we should only store two states at a time so as we need only two next states so instead of making a dp of size so huge that is dpf size n plus two so instead of creating an entire dp vector dp array i just need two elements to store it so dp i will say this dp1 which will be equal to 0 and dp 2 which will be equal to 0 again so this will be dp of i will be co5 plus minimum of dp1 and dp 2. now i will have to change dp1 and dp2 because next time so when we computed dp of i when this is computed using dp1 and dp2 so now when we want the answer for dp of i minus 1 we should make dp of is dp1 and dp of 2s dp of 1 s dp 2 okay all right so dp of 2 will be equal to dp of 1 and dp of 1 will be equal to the dp of is so i should make this another variable that is int dp dpi will be equal to dpi finally we can return the minimum of dp of 1 and dp of 2 let us just run this so it should be dp of 1 and dp of 2 let me just submit this and it got accepted again so the earlier solution using the bottom of dynamic programming that was big o of n in terms of space and big o of n in terms of time okay how did we figure out that obviously the dp array that we created is of size n so that's a big of n space and as we are filling that entire dp array only once so dp of n so big o of n time the same was the complexity for the bottom of code instead of recursion we were using iterations but the space we were filling big o of n and the time that it took to fill all those is big o of n again but in the last code here over here we are not using any extra space we are just using variables so big o of one extra space but the time is still big o of n because we are running this loop from i is equal to n minus 1 to i greater than equal to 0. so time is still big o of n but the space complexity is bigger for now so we improved it in terms of space that's how you do improvements in dynamic programming so i hope you like the video i hope it is clear to you if you do like the video make sure to leave your likes make sure to leave your comments and subscribe to the channel if you want more such content in future thank you
Min Cost Climbing Stairs
prefix-and-suffix-search
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index `0`, or the step with index `1`. Return _the minimum cost to reach the top of the floor_. **Example 1:** **Input:** cost = \[10,15,20\] **Output:** 15 **Explanation:** You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15. **Example 2:** **Input:** cost = \[1,100,1,1,1,100,1,1,100,1\] **Output:** 6 **Explanation:** You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6. **Constraints:** * `2 <= cost.length <= 1000` * `0 <= cost[i] <= 999`
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
String,Design,Trie
Hard
211
39
Had happened and communication university point in android studio talking combination about time cricket batting problem if we have not subscribed it today then please like it, you can also comment, apart from this join the telegram channel. Now let's clean these media, see what you like in this, do n't forget to subscribe to the District President channel and you can ask us question number, I am also a guide channel, time means school combination, subscribe that one person will hit like and join. If one and a half of it is frequently different then it is considered to be guaranteed. The number of combination has been returned. You all are happy in this entire series. You all are happy with this series. Now you have scored it on cs6 amazon that the target has been set in Ravana. By keeping him with us, what should we do? I will see if you think how many times are possible, explain the combination by which we can strengthen it and give us that return. Now what are we doing here or again and again, no, we add our current time. Will keep doing an index till the current number increases epicenter as it was related then green grass answer came if it becomes biggest then it happens that truck does need to explore further than that otherwise mother's condition here If the dead time is found in me, if it is bigger than your target, I will return you. I do not need to do anything further. I know that we do not leave all nearby positions at this time, a bonding condition will occur. It's not happening, it's not happening, let's go a little further and with the help of the country, mix it with this solution, like it, and the staff here has done this keeping in mind the time of the Second World War, so we six accused That this and one of our answers is temporary, let's make this front, I will make mountains of the possible relations that I have in this, okay remind that I had come, now I have eaten these 20, we have gone and cover a little bit of ours here. And put this remedy above the thread that insomnia commission should also be kept swollen, current time, put it on the side of valid human knowledge, we will speak on the branch of Marathi, team work, friend, put 10 current time on that wrist, it will go all four, now we will see that Ghunghrale Se Gaon 10 Like Comment Subscribe Here and here we will check that by doing Kwatra we will increase our index, we will reach here that if we do it while reciting then we have added it in the last and remove it. Turn it off, now what will we do, we have done this and in this, next first option which is not available, we will cut it, okay, the option which is available, six plus 3, a six plus 3, is not ours, I request to one Tamara, okay, there is no solution to the ticket. For two intervals, Tukur, the conversation did not work out even here, now you understand that we will not speak brother, come back down like this, you are worried that I will come, then I will increase it again, okay, I will increase it again, here, do it bluntly and I am swearing on you, now we have six and a half inches, it has happened to you that I will not speak here, I will not speak further, I will do it, this has started, 3 is our cloth, one is lying, 1617 is the 31st, what should the correction person say? It is here that the matter is made by running it back then this one of ours is our ancestor's or will it come again in the iPhone we have licked something and it will be clear and in that the r2bees condition has been hit. Come on the fourth we cannot do side effects. Let's go there. Go, your work is over, so do n't come back, friend, I have secured all my passes, nothing was found, now you come here, close it with zero, let's change it to 98100 when we come back from here, I came back and said, friend. That now here we close this that we have two, now we will say friend, I will set 20 percent and install it again but if we forget this and if it is subscribed then please Meghnad gets his share, this is ours. Whatever we have taken here, now we have subscribed here, now we have finished our work on U, so it has been packed and posted here, now the last decade will go to 355, we will see again if we post it again, what will happen to us? The answer is that Fragnet weight is in Mexico but Batukumar is in it 212 Kama 253 Both of them will make our map type to bridge this gap We will cut the lining which is the answer so that it does not come again and we will arrest and decide There is but from the answer and we will keep folding like this and then we will go and then we will say that there was a need to do it every tonight, let's start with the frill, we start here, in films you start with seven, then our output is going to come. Just this 2012 Kumar Free one is going to come once and the seventh one is going to come, okay and this is a possible combination, otherwise we will continue like this, you sit comfortably, make a good and complete record of it, traveler, if you get more clarity, then take your photo. How do we set it here, it is our process, we have been mixing it in our approach, every time from Index Khusro to end minus one, everyone is going home, okay, what happened to that, friend, he always sat on 120 first position by doing railway track. He had something, see if the answers can come, take time, if less than half of the loud ones come, then take it here, but and then leave everything else and look at it, we don't get any output, or they get it, they are here again. Can number 7 be set multiple times to big 383 up to two options, but huge loot, we will print it and add it, we will add it and keep doing it as per the condition, we are here both these stories, roast a little, only two options are coming. Do n't fix the obstacles that come or go, and once we know one thing about the creator of this, we can see it, so by doing this our whole question has been solved, now we have to do this, take this corner and give it to us. First make it free of record once, by the time you make it complete, you will get a lot of clarity and you are going to do many such things. Now in the next video, what will we do, we will also write the code of it and share the court martial, you can go to school tiger for that. We will go through this again that we have written the code, whether to cash it or not and till then thank you so much for watching this video x video see you till then stay with the court.
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
743
hey everyone welcome back and let's write some more neat code today so today let's solve network delay time the reason i'm solving this problem is because it's a rare problem that you actually have to use ajixtra's however you pronounce that name this algorithm it's the shortest path algorithm it's not super common on leak code but i think it's a really cool problem to solve a cool algorithm to implement so obviously this is a graph problem we're given a network of n nodes labeled from 1 to n and we're also given a list of times the times are going to be our edges so it's going to be directed edges so a time is a triple value the first value in this triple is going to be the source node so for example this node 2 the second node the second value is going to be the target node for example 1 is this node and the reason it's a target is we can see that there is an outgoing edge going from two to the one so every edge is going to be directed right we can see there's a directed edge there a directed edge here the third value and this is also pretty important for this algorithm is the weight of the edge in the context of this problem the one basically just means the amount of time it's going to take for us to go from here to this node right but this is the weight of the edge so we're given a original node k so this is our starting point the node k is going to be the starting point so for example in this problem in this origin in this graph we're given k equals 2. that means this is the starting point for us what we want to do in this problem is starting at two how long would it take for us to visit every single node basically if we sent a signal from here in every direction so in this direction and in this direction how long would it take for that signal to reach every single node now if it's not possible for example in this case it is possible but what if we had a fifth node over here that's just not connected to these four nodes over here then it would be impossible for this node to send a signal here in that case we're simply going to return negative one because it's not possible but what about in this problem because it is possible how long is it going to take that's the only question now looking at the picture it's pretty obvious starting at 2 how long is it going to take for this to reach a signal it's going to take 1 right because the weight of the edge is 1. how long is it going to take for this node to get the signal also one because the weight of the edge is one so now we're over here let me just change the color to make it a little bit better by the way this was the original node how long did it take this node to get the signal technically zero right because it's the one sending the signal how long did it take this three to reach the signal one how long did it take this to reach a signal one now we're going to continue going from this three we know that this one doesn't have any more nodes that it can send the signal to but this three does it has a node over here four right now how long is it going to take this four to reach the signal well the weight of the edge is one so does that mean it's going to take the for one second or whatever our time unit is to reach this no because we have to add the one from over here right remember our signal first started over here then it traveled over here with one then it's going to travel again over here with one so in total once we have visited this node it's going to have taken two units of time to reach it now after this node reaches gets the signal that means everybody has gotten the signal how long did it take what's the largest value we have it took this one right this one took two seconds or whatever so therefore we're going to return two because after two you know units of time every node has received the signal so our output value in this case is going to be 2. now from looking at this example that we ran through you might be able to tell that jigstr's algorithm is actually a breadth first search algorithm that i'm going to show you the general idea of but the one difference about regular breadth for searches this algorithm actually uses a minimum heap aka a priority queue so we're going to be needing this data structure it's not a super common data structure but it is needed for this graph algorithm let me show you the actual algorithm after that we're going to jump into the code so in case you want to google this algorithm or do some more research it is called jigsaw's algorithm it is a shortest path graph algorithm and it's pretty common you have probably learned it in school if you study cs and what it does is in this case let's say our source or our starting point is this node the value one what it does is for every other node it basically tells you the shortest path right so for example three what's the length of the shortest path to this node well from directly from one to three it takes one so one is going to be the shortest path for this node what about this two node what's the shortest path to this node right with this it's pretty obvious because there's only one way to get here anyway but take a look at this node there's two different ways to get there now this is this the shortest path it's the obvious path right it's just one node away but the edge has a weight of four that's a problem because take a look at the second path that we can do we can go to three right over here then we can go to the four and then we can get to the two right that took three edges didn't it that took one edge two edge three edges but when we total these values up we get a sum of three that means this path is actually shorter than the path up here so it's not always clear right that's why we need an algorithm and that's exactly what we have jigsaw's algorithm and we're going to be doing a breath first search right so starting at this node the start node 1 we're only going to be possibly visiting nodes that are right next to our frontier right depth first search would be we just go one direction we just keep going right but breadth first search is we're gonna do this layer by layer right we're going to go to the first layer the next layer and so on if we had a bigger graph right that's how breadth first search works and every node that is on our frontier right so if this is our starting point we have two options of nodes we can visit this node or this node these both are going to be added to our min heap and we're only going to visit the one with a shorter path that does make sense so far doesn't it makes sense that we would want to visit this node because it has a shorter path rather than visiting this node first which has a longer path right that makes sense so far that's why we're using a minimum heap minimum heaps can get us the minimum value pretty efficiently right every time we want to get a minimum value from the min heap it's just a log n operation okay so the way we initialize this algorithm is we know that we're starting here right what we're going to actually do is add this node to our min heap initially right so and in our min heap we're going to be keeping track of two values obviously the path length right because we're always going to be popping from the min heap based on the minimum path right so that's what that's like our key value that's what we actually care about right that's what's going to determine which one we pop but we also want to keep track of which node it is right so initially the path to reach uh the initial node one is zero right because we're that's where we're starting so it doesn't cost us anything to get there and the node itself is obviously one so this is how we're gonna start then we're gonna pop this value it's only one value so far so it's simple of where we're popping right once we pop this value what's our next step well like i said this is a breadth first search right so we're gonna take a look at the node over here it's one we're gonna look at all of its neighbors right it has two neighbors right we're checking that first layer this we're going layer by layer with breadth first search right so this is our first layer right we're gonna take the first neighbor three how long does it take to reach three one we're not visiting it yet we're simply adding it to our min heap so the path length is one and this is for node three then other node that we can reach is two the path length is four let's add that as well four and the node is two and since we've already visited the node one we can cross it out now so now we're popping another value this time we have two values so which one are we gonna pop well this is a min heap right we're gonna pop the value with the minimum path it's this one right of course that's the one with the shortest path that's what we're gonna pop now so as we pop every element we're basically determining the minimum path so now we can say for sure that the minimum path to reach three takes us one right because one was the value that we added to our min heap and again we're just doing a breath first search what are all of the nodes that three has neighbors with it only has neighbors with one node right this four we have a directed edge going exactly to four so let's add four to our min heap so we're adding the node 4 right so that's what we're going to put in the node position what are we going to put in the path position are we just going to put 1 because it only takes 1 for us to get there from 3 that's not actually what we're going to put we're going to take the total that it took to reach three which was one and it's taking us another one to reach four so we're gonna add the total to this right we're not just keeping track of the single one we're keeping track of the total path it takes for each node we want to know how long it takes to reach node 4 all the way from our starting position we care about the starting position so when i put the path value of the path length for this node i'm going to put a 2 value so now we are once again done with this node so now again we are going to decide which one are we going to pop from our min heap we want to pop the value with a shorter path so we're going to pop this one so now we're at this node right and how many nodes can this node reach well it only has a single outgoing edge to this node 2 right and we see that 2 has actually already been added to our min heap right but the only difference is this time and i'm running out of space so i'm just going to add a little slot is that for this 2 it's how long first of all how long did it take to reach this it took a distance of two to reach this four and plus one means that to reach this two now it's actually a distance of 3 which is shorter than this one right so now we can actually add that same node 2 to our min heap but this time we're going to have a distance of 3 which is shorter so we visited this node and now you can see that we only have one node remaining to visit good thing for us both of our options in the min heap lead to that node which one are we gonna pick it's a min heap so we're gonna pick this one 3 is less than 4 so we're going to pop this from our min heap so now we finally popped the last node it's a path length of 3 so now that we've reached every single node in our array and by the way this node does not have any outgoing edges so we don't have to do anything more and we even though we do have an a value left in our min heap once we pop it we're going to see that it's the same node that we've already visited we visited this two node and we visited every node now and you can see the max value that we got in terms of length is three so three is going to be our output in this case it takes three units of time or whatever for us to start at this position and then send a signal to every other node in the graph so analyzing the time complexity of this problem is actually a little more difficult than you think so i'm going to use e to tell us basically the number of total edges inside of our graph that we're given and v for the total number of nodes or vertices that we're given and just so you know the maximum number of edges that we could possibly have is about proportional to the number of nodes squared because like it's just kind of how it works so like if we had two nodes or rather three nodes you know there's we could have bi-directional edges we could have bi-directional edges we could have bi-directional edges for every pair of nodes and if you just basically this is just something that's true and that's what i'm going to assume so the max size of our heap could actually be v squared even though we have let's say four edges we noticed that some of the uh or rather we have four nodes we notice that some of the nodes could be added into the min heap multiple times that's dependent on the total number of edges that's why we're saying v squared is the total number of nodes that could be in the heap so every heap operation is possibly worst case log v squared and how many times are we going to be doing this operation it's going to be e times worst case basically the number of edges because for every edge is how many times we can add values to the heap right so and this and the way logs work logarithms if you take this 2 we can actually get rid of that too put it over here right put the two over here and we know how big o complexity works we don't care about constant values so this two actually goes away so the overall big o time complexity with a priority queue for a jigsaw's algorithm is going to be e log v this is just the general overview now let's get into the code so we're actually given a list of edges and we want to create an adjacency list of that first for jigsaw's algorithm so the first thing i'm going to do is create a dictionary or a hashmap of edges initially it's just going to be an empty list so i'm going to go through every edge in the input so for every edge u i'm going to get a list of all of its uh neighbors right because we know that's pretty useful for a gixxer's algorithm we're going to basically get every single outgoing neighbor so v is the neighbor node and w is the weight of that node so we're going to add that to edges list for you so this is just creating an adjacency list for us which is going to be useful now i'm going to create that min heap we remember we want to just initialize this min heap with the first value and the weight of it's going to be 0 because we know it doesn't cost us anything to get there and that starting node is given to us as k i'm also going to have one more data structure it's going to be a set basically it's going to keep track of all the nodes that we've visited because we know we don't want to go in a cycle we don't want to go in a loop so we do have to sort of keep track of that i'm also going to have a variable t for the result initially it's going to be 0 basically the max value that we end up getting or the last node that we visit and the cost or the length to visit that note is going to be the value that we return so now we're just going to continue our algorithm while our min heap is non-empty we're going to keep popping is non-empty we're going to keep popping is non-empty we're going to keep popping from our heap while it's not empty we know that there's two values that we added the weight was the first value the second was the actual node itself so we're going to say keep q dot heap pop from our min heap this is basically how you do it in python it's pretty easy in python that's what i like and like i said we don't want to visit a node multiple times so if we see that this node n1 is in visit meaning it's already been visited then we're just going to continue to the next iteration of the loop we don't want to go through all of this node's neighbors if it's already been visited otherwise what we're going to do is add it to visit so that we don't visit it again and we're also going to update our result t so we're going to set it to the max of what it already is and the max of the weight that we just got the weight is remember the time it takes to reach this node so we're going to update that now we're going to do the breath first search portion of it so we're going to go through all the neighbors of this node so the no the neighbor and the neighbor's weight so i'm just going to call that n2 and w2 because i'm bad at naming these so in edges basically neighbors of this n1 original node that we just popped from our min heap we're going to go through it and for all of the neighbors that haven't already been visited so if n2 is not in visit it's it has not been visited yet then we're going to add it to our min heap so heap q dot heap push on to our min heap is going to be this node n2 but remember the first value we're adding is the weight so weight 2 but remember this weight is just this weight 2 is just the weight that it takes for one edge but we want to keep track of the total uh path length to reach this node so we're actually going to add that w1 the first weight to it as well so w1 plus w2 the total path that it takes to reach n2 i know that this algorithm is actually pretty complicated it's not a lot of code it's about 20 lines but it's actually you know it does take some practice to get used to it after you've written it a few times you do kind of understand the subtleties of it's pretty easy to go wrong with this algorithm but we've basically written the entire thing so now we can return t after this loop is done executing after the min heap is empty our t should give us the uh basically what it takes to reach every single node if it's possible right remember if it's possible and we know that it's possible basically we've visited every single node if the length of visit is equal to our input value n which tells us the total number of nodes if we visited every node then we can return t remember the other condition was if we can't visit every single node we return negative one and that is the entire algorithm remember the overall time complexity is big o the total number of edges multiplied by log the total number of vertices so this was a pretty long one it was pretty difficult i actually had a lot of bugs when i was writing my code for this video and i hope that this came across pretty clear if this was helpful please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Network Delay Time
closest-leaf-in-a-binary-tree
You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target. We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`. **Example 1:** **Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2 **Output:** 2 **Example 2:** **Input:** times = \[\[1,2,1\]\], n = 2, k = 1 **Output:** 1 **Example 3:** **Input:** times = \[\[1,2,1\]\], n = 2, k = 2 **Output:** -1 **Constraints:** * `1 <= k <= n <= 100` * `1 <= times.length <= 6000` * `times[i].length == 3` * `1 <= ui, vi <= n` * `ui != vi` * `0 <= wi <= 100` * All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.)
Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
30
um hello so today we are going to do this problem called substring with concatenation of all words um so the problem says is that we have a string and an array of words that are the same length so this is important same length here and we want to return all starting indices of s in s basically such that um those substrings are concatenation of all the words in words and this concatenation can be in any order right uh and so what this would mean here if you take a look at this example the different like combinations of these words is fubar or barfu right and so we have bar for once here so it starts out at index 0 and then we have 4 bar that starts out at index 9. if you count you would find that this here is 9. if we take a look at the second example right we are looking for a combination of these so either word good best word or good word best word and then all the different permutations um and if we look at this here the problem is here we have two successive goods but that's not like a combination we want each wall to occur only once this here we have all three but the problem is that there is good repeated two times before getting word right so we need actual the combination we need is word good best word but that doesn't work because there is these two in between um so that's why we return list because there is no substring like that if you take a look at the last example bar for the we have it here foo bar this one first and then this and we have it here as well okay and then it seems like we have so this one starts out at six this one starts out at nine i think no this one starts out at 12. um and then what do we have the second one yeah we have a second one here bar the four right so this one is the one that starts out as six this was the one that starts out at um sorry this one nine and this one twelve right uh so we have three that's what we written here we just done the indices of the start of the substring occurrence i hope that was clear um now let's see how we can solve it um okay so let's see how we can solve this so um one thing to note in the problem statement is that it said that the each word in the list of words sorry each word in the list of words has the same length okay um so that's one statement so what this would mean is that what we are looking for overall the size of the concatenation which is the concatenation of all the words but in each time in different orders that's just the size of all the words right and since we have let's say words right then if we consider um let's say word length to be the length of the first word right so if we consider that to be the length of words zero with the first word then actually what we are looking for like let's call it size is just the word length since each word has the same length it's multiplied by how many words we have so the length of all the words right because let's say we have four words right and the first one has length three right um since all of them have the same length that means we have overall if the concatenation has length three by four twelve right and that's exactly what we are doing here so this is what we are looking for right so what we can do is just look and then we have our string s like this so we can look for i starting from position 0 all the way to i to the length and minus size plus 1. so this is n why because well this here is smaller than like let's say let's take this maybe it's n minus size minus 4 this index here if we start from this index we won't have enough for all the words concatenation so that will never be a valid substring and so we don't need to look past this position here so that's the first thing we can take i just from this position from zero to this position and minus s z um and this here so one thing to note here plus one needs is needed only in python because to get to the last one you need range um up into n minus z plus 1 but really concretely is n minus size that's what we are dealing with here okay so that's the first observation now the next thing how do we for a substring we have a substring that is a possible candidate let's call it a candidate substring how do we determine if it's in s and get the get its index right so let's call that um presence or check presence something like that okay so check presence starting from one of these positions okay so how do we do that well what we can do is just look at each word look at each like range of word size word being just let's say if we had again three look at each chunk of three characters and check if it's one of these words right if it is it means we continue searching if it isn't we shouldn't check right if it isn't let's say this is foo bar d and maybe car right if you find i don't know um level or something string or actually we need something of length three if we find let's say sky then we should stop right because in that substring that would never be a valid solution so we should break so that's the first thing the second thing is what if um what if we have actually in our list of words what if we have foo and then bar and then car something like this right we have food two times that means in the substring that we are looking for in the string we need to have it two times as well right so for this actually to be easy to determine we can use a counter or you could use a map that counts how many times each word occurs in the list of words just so that we can make sure exactly that number occurred so in python we can use a counter for this okay um so those are just like a couple of ideas that will keep surfacing now how do we tell that we have the substring that one of the concatenation exists right so the way we are going to do it is we actually going to take every substring of length size which you are looking for and check if all the words in w are in it that's what we are going to do so basically for each substring of size the not the size we are looking for of length size check if all words in w exist in it with the same number of occurrence occurrences number or occurrence count so that's what we are going to do so the easiest way to do it is to have the counter for how many times it occurs and each time we find that word that sub word decrement right and count how many words we found and at the end check if the number of faults we found is actually equal to uh the length of words which would mean that so which would mean that we that it's a substring right um so how do we do that well let's say we have word count right for each so this is just for the check presence function so let's define that a little bit here so check presence starting from a position i how do we do that um we need a word count right so let's call it wc this would be the word count so we can have it be the counter for um all the words right this will give us basically if foo is occurred twice it would be like this if barrow carried once it would be like this um and you get the idea so if we have that then so once we have this then what we need to see how many words we found all right so initially it's zero and at the end we want to return if we found how do we check if we found all the words right well as long as we have the size right let's say we have here five we need to make sure we have five of them so if we have five of them that means we found them so this would be it needs to be equal to the length of words now how do we check we have an index right in s and we want to check if it's a if this is a valid substring that contain all the words so let's just go through each chunk here right of length what should be the length here the length should be the length of the word so it should be worth length so go through each chunk of size this would be of size word length this is just the length of the first world because they all have the same length and check if this is in w but because we have we may have like a double foo let's say maybe we need like we have a list of words like this well each time we find it we will need to decrement it from the counter right to determine that we exactly have that many words right so to do that here what we can do is just do a for loop um and go through the range remember we are looking black by black here so we need to go from the first index we are looking for and each time look at the entire block here which we said it's um so we need to each time look at one block but we need to look at all the length of a possible candidate which is the length of the of this here what we said is the potential the size that we are looking for and so size here and each time we want to look at a block of word length okay now what is the substring for this here the substring would be equal to s from j to j plus the word length right because remember this is just one of these blocks right okay and now what do we want to check if it exists in the list of words because if it's sky it's not in the list of our world so we can exit so we want to check if it is how do we check with the counter we just make sure this substring count is bigger than zero but if it doesn't exist right or maybe in the substring we have four let's say three times but we need it only two times so now the count would be minus one then we want to exit so here we want to exit if that's the case so that we would check the return no need we need to proceed because we know this substring is not valid right but if it is then we want to subtract it right because once we found foo we want to subtract that we found it and so we want to decrement by one let me just leave some space here okay um the other thing we want to do because we found this substring so we're going to increment how many words we found because at the end we want to check that we found all of them okay and that's pretty much it so again to reiterate we'll do the first loop that checks it goes through every index in s from i to n minus size right because those are all the possible sub substring values of string so we'll check let's say the size is maybe five so we'll check this and then we'll check this until here because there is no possible uh string of length uh size right and size is all the word the length of all the words combined right and to check for each individual candidate if it's a valid concatenation we take the word counter for it and we count all the words we find but in order to count it make that to make that more efficient we look black by a black and the black is just a possible word right and we check if that word exists if it is we count it and we subtract it so we don't count it again and if we don't find it right that means that substring is now valid so we can just exit and then this will fail right but if we go all the way to the end of the substring and we found all the words that means um it's a valid content concatenation so would it check if it's the length would be equal to the length of words and we would return that it's valid um yeah so that's pretty much the idea here now let's score it up and make sure in delete code and make sure it passes test cases um okay so let's write the full code that we are expecting here so um we want to return the indices the possible start so we check all the possible starts here and this is n minus the words size or what we called size in the overview we do plus one here so that we look at this as the last in possible index right and we need to define a couple of things we need to define n as the length of the string and we need to define words size as the number of all words right so that's like this and now we check uh presence or of all the words starting from that index if we found it that means this index is a valid start of a for valid concatenation and so we add that index and then at the end of return and so now it's just about writing the um the check function and we already wrote that in the overview so we can just use that here and so overall what we are doing here we use collections counter for um for the world so that we have the count of each world and then we check the found um and then at the end we check that all the words found is the length of words which means we found everything so here this is just the length of faults okay and then we here we just to reiterate again the check we are doing we start from i and each time check a block of length the length of one word right and we do it until all we traverse all the string we are looking at so word size i know this sorry i know this is a little bit confusing so world size is actually the length of the first word so that's word uh yeah let me just make sure so this is the length of one word right and this is the overall world size so let's just make this named size um so this would be the length of all number of words multiplied by this so this is the size candidate um and that's what we are looking for here and we have this is the world's length so this is the number of falls we have overall so this is the this is what we are multiplying by okay let's maybe make this easier to understand by naming it number of words okay and then check this here um and here just make this super clear single word length um so this would be single word length here right that's what we are looking for um and here we go through the counter if it's equal to zero or less than zero that means this is not valid either the words is not there or it's there more times than needed and so we break and then we subtract once we found it and increment the words found so that's the main idea here um now one thing we can optimize here is we are doing counter forwards each time right and so what we can do is define it here so what count color but the problem is that since we subtract from it once we do it for one iteration here we do we don't want to carry over the what we deleted right we don't want to carry that over so we need to use a copy so here we use a copy like this okay um yeah so that's the main thing here i hope this was clear so let me run this make sure it's it works properly um so we need to define this function with the same name okay let's try to submit okay so there is one error here um let's check what could be wrong um yeah so the problem is that this should be the length of one word multiplied by the number of folds right so let's run this again okay so that looks better okay so that passes test cases um yeah so i think that's pretty much it what i wanted to cover for this problem um you can also solve it with the sliding window technique where the idea here is that each time here we do we go i one by one right the one by one but the there is a lot of information lost like maybe say for example let's take this here right if you take a look um we first do this right there is the information that this one is present right and so we could just start looking from here we don't need to repeat from this index and also like with this here um let's say maybe we are we have um i don't know like a word sky in the middle here right um once we find that sky is not there a character s is not there then y like sky there is no k and y so y um check k next to it right so it doesn't make sense so basically take advantage of the information you have so far to make the implementation more uh performant and you could use that do that with a sliding window technique but i think that solution is slightly more complex so i would go with just this simpler one um yeah so that's pretty much it for this problem please like and subscribe and see you on the next one bye
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**. A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated. * For example, if `words = [ "ab ", "cd ", "ef "]`, then `"abcdef "`, `"abefcd "`, `"cdabef "`, `"cdefab "`, `"efabcd "`, and `"efcdab "` are all concatenated strings. `"acdbef "` is not a concatenated substring because it is not the concatenation of any permutation of `words`. Return _the starting indices of all the concatenated substrings in_ `s`. You can return the answer in **any order**. **Example 1:** **Input:** s = "barfoothefoobarman ", words = \[ "foo ", "bar "\] **Output:** \[0,9\] **Explanation:** Since words.length == 2 and words\[i\].length == 3, the concatenated substring has to be of length 6. The substring starting at 0 is "barfoo ". It is the concatenation of \[ "bar ", "foo "\] which is a permutation of words. The substring starting at 9 is "foobar ". It is the concatenation of \[ "foo ", "bar "\] which is a permutation of words. The output order does not matter. Returning \[9,0\] is fine too. **Example 2:** **Input:** s = "wordgoodgoodgoodbestword ", words = \[ "word ", "good ", "best ", "word "\] **Output:** \[\] **Explanation:** Since words.length == 4 and words\[i\].length == 4, the concatenated substring has to be of length 16. There is no substring of length 16 is s that is equal to the concatenation of any permutation of words. We return an empty array. **Example 3:** **Input:** s = "barfoofoobarthefoobarman ", words = \[ "bar ", "foo ", "the "\] **Output:** \[6,9,12\] **Explanation:** Since words.length == 3 and words\[i\].length == 3, the concatenated substring has to be of length 9. The substring starting at 6 is "foobarthe ". It is the concatenation of \[ "foo ", "bar ", "the "\] which is a permutation of words. The substring starting at 9 is "barthefoo ". It is the concatenation of \[ "bar ", "the ", "foo "\] which is a permutation of words. The substring starting at 12 is "thefoobar ". It is the concatenation of \[ "the ", "foo ", "bar "\] which is a permutation of words. **Constraints:** * `1 <= s.length <= 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 30` * `s` and `words[i]` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Hard
76
138
foreign problem of deep copy of a linked list which has two pointers welcome to my video let us begin we are given a linked list which has two pointers in addition to the next pointer we have an extra pointer named the random pointer we are to make a deep copy of the list it means that all the nodes will be copied into new memory locations in the first method we will consider a recursive solution to this problem consider the linked list as a graph this means the two pointers of every node are the edges of a graph node as we Traverse in depth first manner we will clone all the new nodes because of random pointers some loads are visited again this indicates the presence of Cycles so we will keep track of all the Traverse nodes in a dictionary we convert the given list to a linked list to obtain its head we can see that in addition to the next pointer each node also has a random pointer for which values are given in the list copy random list is a recursive function it Returns the memory address of the clone of a node in the original list head is the pointer to the beginning of the given linked list so this function will return the head node of cloned linked list we Define cloning dictionary to keep a mapping of memory relations between old and new memory nodes memory of the old node is the key and memory of the new node is the value in the dictionary relations suppose a b c and d are the memory addresses of the four nodes of the given linked list our aim is to create four more nodes named a prime B Prime C Prime and D Prime such that they have similar links as ABC and D ictionary is empty to begin with and in the first iteration head is a if head is none its clone is also none however in the first iteration head is not none so this if statement is skipped if a node is present in the dictionary it means that it was already cloned and the address of its clone can be obtained from the dictionary without going further however in the first iteration head is not in dictionary so this if statement is also skipped therefore we create a new node called clone with well same as well of head let us suppose that the memory address of this node is a prime we saved the sphere in the dictionary for later use this entry means clone of a is a prime the function should now return the Clone but before that we need to set next and random pointers of the Clone corresponding to the original list a next is b and a random is C which means that a prime next will be B Prime and a prime random will be C Prime we will create these links one after the other first we create clone of head next and save it in Clone next this means we will recursively call this same function once again to get the clone of head next is B so B becomes head in the next recursive call remembers the position from where a recursive call originated and later continues the execution from the same position we indicate this by white arrow in the program in the new recursive call with b as head execution starts from the beginning B is not none so the first if is ignored and B is not in dictionary so the second if is also ignored so we create a new node with value equal to 8 and save its memory in Clone let us call this memory B Prime we save this pair BB Prime in dictionary which means for node B its clone is B Prime during this iteration also we reach the statement marked with white Arrow where we make another call to the function with B next as the argument in the call the head you see recursive position is always saved in the call stack we skip the two if statements once again C is not none and is not in the dictionary so we create another node in the available memory which we name as C Prime we save it in local variable clone and save it in the dictionary against C next entry in the call stack is for head equal to D and we get This tabular Record now that head next that is D next is none the next recursive call is for head equal to none first if statement of the function returns none which is received by the previous call at the statement with white Arrow so none is stored in Clone next which means D Prime next becomes none but D Prime next is already none so it has no effect next statement after white arrow is the statement at orange arrow to assign clone random in another call to the function with head random as the new head D random in the original list is a so a becomes the head in the new recursive call made from Orange position as a is not none first if statement is skipped however a is present in the dictionary it means that a was cloned already so we look for the value corresponding to a in the dictionary which is a prime so clone random becomes a prime which means that D Prime random gets the value a prime in other words D Prime random points to a prime for which the link is shown like this now that both the links of D Prime are set we return D Prime which is received by the previous call at White position and C Prime next gets the value D Prime which means that c Prime next points to D Prime after setting the next link of C Prime we move to the statement with orange arrow to set its random link and we may call to the function again with C random as the head for the next call C random is B in the original list which me which is present in the dictionary so it promptly returns B Prime and therefore C Prime random points to B frame last statement of the function that returns C Prime which means that b Prime next now points to C frame next statement which is at the orange Mark makes another curl with head equal to B random but B random is none so return value is also none and B Prime random remains none last statement of the function returns B Prime so a prime next becomes B Prime next statement is at the orange position in which we call function with head equal to a random which is C is present in dictionary and it returns C Prime so a prime random becomes C Prime which is shown like this last statement is return clone which means a prime which is the final head of the cloned list time complexity is of the order of n because every node is cloned only once each node makes two entries in the call stack space complexity is of the order of 2 N which is same thing as n now we consider an iterative solution to the same problem this time we Traverse it as a linked list and not as a graph consider the same linked list we again Define clone dictionary get clone is the function that gives us the clone of a node if the node is none its clone is also none otherwise we look for the node in the dictionary if it is not cloned we create it and save it in dictionary both its pointers are none at the moment now the Clone is present in the dictionary waiter return its address we are now ready to start with the main function to copy the linked list for which head is given if head of the given linked list is none we return none as the output also otherwise we copy head in node and start a loop to process all the nodes we call get clone for the node is not in the dictionary so get clone creates it and returns it its address this address is saved in Clone we know proceed to set its pointers node.random is denode with Val equal to node.random is denode with Val equal to node.random is denode with Val equal to 4 for which we call get clone as it is not in the dictionary get clone creates it and saves it in the dictionary before returning its address which is saved in clone.random which is saved in clone.random which is saved in clone.random we repeat the same process for the next pointer create the clone of node.next and save create the clone of node.next and save create the clone of node.next and save its address in Clone dot next in the last statement of the loop node moves to its next position in the next iteration we get the clone of the new node it is present in the dictionary so new node is not created its value is returned from the dictionary and it becomes the new value of Clone as node.random is none clone.random also as node.random is none clone.random also as node.random is none clone.random also remains none node.next is the node with Val equal to node.next is the node with Val equal to node.next is the node with Val equal to 4 for which clone is already present its address is obtained from the dictionary by get clone function and is saved in Clone dot next lastly node.next becomes new node.next becomes new node.next becomes new node in the next iteration clone shifts to its next node next statement sets its random pointer for the next pointer clone of node.next for the next pointer clone of node.next for the next pointer clone of node.next is required it is not yet present in the dictionary so it is created in the get clone function and its value is saved in Clone dot next in the last iteration node and clone move to the next nodes the random node of Clone is set while its next pointer remains none finally we obtain the address of the clone of the head from the dictionary and return it to the main program every node is processed only once so time complexity is of the order of n each node is saved in the dictionary so space complexity is of the order of n thank you for watching the video next week I'll upload another solution of the same problem in which we will have constant space complexity please stay tuned
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
72
um hello guys so we're back in the game right um obviously as you know I started um a new job in Sydney and um it's super cool the company you know has got me in a brand new like MacBooks and this and that which I reckon is you know it's pretty dope you know brand new Mac I do like these and um I am pretty thankful right but um the problem is we wouldn't have as much free time as you know we would like in terms of you know grinding Lee codes because you just don't get you know the free time that you wish other things to learn so we're going to be reducing our lead code on because back in like August last year we're doing like two three hours a day right that's when we quickly improved and uh you know I was able to hit some of the mediums obviously if you don't move forward move backwards right so I don't go right now I would be to hopefully stay at you know the same sort of level so we're going to be reducing lead code to probably um three questions three new questions a week so I'll make you know like I want to say make a video right I mean we're going to be attempting this problem right live you know like on Camp like right now if whatever we get stuck on you know it is what it is right so without further um at a distance is always one of the questions that I really wanted to do right um I'm gonna be approaching this problem using DFS with memo I already know this is a DP but you know just in case if you don't know um you can use DFS and then you can catch some of the results that you've calculated before into a map to the array whatever and later on use that um you know I don't have a problem with that so we will be um using that and um we'll be using BFS memo and later on maybe if I have time I'll see if I can put the DP solution right I roughly know this is you know similar to like the longest common subsequence but given that I've never done that problem either so it's a pretty new problem to me and um the sometimes people can say oh Lincoln number 72 it's you know only it's not even hard is it's like one two four should be medium right I agree but if it's your first time seeing the problem it has to be hard right so let's just get it given two strings world one word to return the minimum number of operations required to convert word one two or two you have the following three options middle of a word insert a character deleted character and replace the character that does kind of looks pretty interesting so based on the case they're giving us okay I know the DFS will have three choices right either delete or replace or remove right delete our insert right so we need to convert word one to word two right so word to would remain the same we're changing word one okay obviously the termination condition for this DFS as you know I mentioned sort of before would be that right because if you're if you want to has no links because as we're moving right okay so what we're doing is basically we're returning integer right so let's say if word two I mean Ward one word two are the exact same sure this algorithm will just slice them one by one right and two word two becomes a null and whatever word one has left will just be delayed right so that's one termination one term ination conditions right to be honest guys this to me does seem hard like it is difficult right um so what we'll do is I mean let me look up how to look for the last chart um a tale of a string yes actually we're looking for example right you're gonna look it up last index of strange allies okay we are kind of stuck on how to return that but you know what whatever so we'll just say you know that's a should be the last character equals to you know or two dot chart at word to the links if the character are matching right or just go um this is one of the options right so obviously what we'll do is we'll ride the DFS first and then we'll add them or whatever um I've also got to keep in mind the time because after half an hour we have to go to bed regardless no matter how much you know I love the code so poor DFS um okay thank you oops substring I think in Java excludes the um whatever you've got to be careful with that and uh can you interview yeah I appear hard to look it up begins at the specified begin index and extends to the character at in N index minus one so with that being said that would be like or to stop string I mean we're starting from zero technically because that won't include this I'll include everything before this which is what we want right foreign I will return an integer right yes right um we haven't thought about what body to initialize this yet but um if you don't assign a value to it I'm pretty sure actually no you know what let's get rid of this here right in the partial answer equals to DFS so what would what so what we do is we'll just call the DFS right here right so that's all good it will try to terminate based on the condition actually now one other if word one dot lines equals to zero right so just let her have to return word to domains right because if we think about it right if we have an empty word one we no matter how you're gonna muck around your like your base case would be you have to um insert right you have to insert all the characters from one two to word one um yep that's it so that's that so I have three choices so we either foreign otherwise we delete a character delete for sure this is like the delete option right so what we'll do is we'll remove a character I want to make sure it stays what it is option out and obviously we know that we're going to be choosing the minimum betweens after we just get the DFS right I think adding the cash wouldn't be that hard right I believe python actually even hasn't built cash right fine guys I may switch to python right because for my new work we might use Python right if we use pi to write our Stitch Java right because just for the benefit to you could BFS so that's um your delete option right what other options do we have right we have insert right I always suppose obviously for the replace would be similar to that but I believe we can do this right yeah I believe we can do this or just go one because we've used one sort of move right so insert would be if we think about it right if we're missing a character right all those four current character will add one on top of it right what are we going to be adding though no if we let's say um let's just go through some cases right um remove is easy right um insert so insert right if we think about it we insert we're not done right we wanted to match that index exactly with work too right so um insert would be similar to deleting incense but word one would remain the same word too I believe would get shot hopefully that will work and um that's insert and what's the other one again replace oh shoot right so replace would be the same as well right kind of hopefully one plus DFS reply so after replacing because you wanted to replace a character for both of these get straight right so um yeah hopefully this really works for this to work right thank you brah It better work um I don't know I wish there is a job where I get to do this I get paid to do this every day right it is kind of fun like I already wish I like the most part I enjoyed about getting a new job is you know the data structure and algorithms interview right because you just grind these problems super cool and uh honestly you just work them out right so this is a basic DFS kind of run this because it's never going to work cannot find symbol oh I cannot type for crap right lane and lanes and what we'll do is just call it DFS word what foreign laws I can see why oh shoot so answer obviously um we wanted to go like that and then we wanted to okay I did pick up a bug was in my own code so hopefully this DFS already works because yeah otherwise we're not going to bed tonight cannot find symbol yeah let's try that man what ow oh bro that is more right that's bad guys that is really bad okay the DFS does not work well I don't think we expected right so without the DFS there isn't really much we have to um in regards to you know um doing you know the dpfs with memo because the base case DFS doesn't work must try something you know try to fix the stuff right so it's pretty good or two right see what it does hopefully you will do something so um guys let me grab a pen and pencil right and you know we'll come back with what analyze this right because without a pen it's kind of hard hey okay guys we're back in the drink right so word one shows hrsc or two shows Ros right Ward one somehow go becomes h o r s right there's nothing wrong with that word to do Ros right word one becomes h o r word two is Ro what who's Arrow or chose our reward one is a child okay I don't think we're ever supposed to talk because I think through um so there's nothing wrong with this part is all sweet all this is correct as well I think this is really the delete option right word one with deleting I don't think there's a problem with that yeah aha is string passed by reference I think it is damn you know what or just go like that or go like that right and you this could be why if we're coding C plus I would be able to um definitely pick this up right see if let's run that Raw you're joking right let's you know let's just write that I don't know what is wrong with my own code I can't even write a bloody DFS guys I'm so useless right yeah ready to be laid off oh man that sucks what we're getting some twos are what we're getting we're not getting any threes so um let's try that so we already know this one is a five right let's see oh man it's first of all it's like super slow like not gonna lie like right uh so let's run the code yeah man I don't know what about the other one right like yeah that's great we're stuck on this problem on day one right we're stuck on this problem on day one this is really ideal oh I don't like it man I don't like what we're seeing here I think we're gonna be going with easier cases right I swear if the characters are equal we just return DFS we return DFS is there a problem with that no there isn't right because we don't know if they're equal right like let's say Ross or and Ross right that should return zero right rosk what brah how did we forget to plus one yeah oh what okay that's my bot guys that is really bad right do not learn oh I forgot to do the OnePlus because that counts as one operation yikes so the bloody stupid DFS works right so coming up with the DFS solution we're already halfway there oh we just need to convert this into a DFS with mammal right but um first of all I just wanted to see if we're gonna over time I know we are definitely going to be overtime like there's no doubt about that like there is no bloody absolute freaking doubt about that wow we timed out on like case 25. Yates okay um well let's work with that right um what should we be storing though because with you know a DFS was mammal right EFS plus memo what are we trying to memorize you know what just gonna go hash map right I was thinking of just concatenating the two words yeah two words and then chucking that into a hash map and you know trying to memorize obviously memo the bloody thing right because if we look here this might get caught a billion times right if we don't memorize you know um what's it called um let's call this map May over time right guys it could well be over time right no this could you know practically happen um so what we're gonna be doing yeah so I really hope there are no white spaces right because we're screwed if there are right so yeah that's what we're gonna just return what are we returning um we're returning this value right app dot get we could whilst the overtime because man look at how many bloody cases these Busters are running on this right that's ridiculous man yeah it's bet you they must this may not work and we had we'd have to really use something else but okay this one okay guys do not name um do not name like this right if you do this during a coding interview right you're getting like you're done right you're done basically we're doing this because first of all we are a Savage you know and we have YOLO swag right so we're doing this I do not suggest you to do this right do not do this name your things like in better way right and make sure you write your code in need away as well because this is garbage code this is more lead code for fun you know lead code for interview at this stage because yeah I don't know it'd be key yeah I'm doing one leeco every day I reckon Keith my brain just moving right oh I feel like we're doing a lot of redundant stuff I don't want it to be cutting that foreign so what we'll do is we'll go did we call this map wow this is so classic right map. key to store and it's the exact same thing right keto store and then we'll just go like that right oh without a white space this is gonna turn out to be a major disaster yeah I'm such a genius I figured this out on the point right guys like without a white space I made this in front jump right this mistake and yet we're so dumb we're gonna be making it again right this is not okay but copy that Chuck it here and um oh shoot scoot yeah okay whatever would copy that um okay a one thing I am confused do we store the new or at least thought the old because if we look there are three options right yeah broth yeah because do we store the auto do we store the new man I'm so Rusty right I suck a coating but okay it's not like that's the thing we if we store all three of these next time we'll know if we see them again but if we catch what we have I've been okay I don't think of mine I don't think it makes a difference right key to store keto store you know what just be award one yeah this should work map. yeah that should be right let's go return map dot get eat a store right because hmm yeah I mean that return should never capture anything from this cannot find symbol please work because I want to go to bed like I don't want to be stuck here okay whatever let's get rid of that I knew that was gonna be a ritual let's do very slow though yes we passed yeah bro we're out of here yeah using this hochy just TFS with mammal cash like we're at the we are practically at the like bloody bottom five percent of like leeco Solutions guys I can't believe like we were so slow because we're using a hash map you're supposed to use something like a 2d array but um let's have a look at the solution right oh man yeah I bet you yeah they're using yeah oh wow like they're using this right we're just throwing the string like no wonder why we're not beating them right but um I'll investigate into the better solution obviously but this is it for this video right we're out of here peace out I managed to described this problem in one go and um like you know I don't wanna you know think about that because I really need to go to bed like you know screw this we're out of here
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
444
hello welcome today I try to solve another L problem 444 sequence Rec construction so we are giving a array of sequences so inside of the sequence it's just a subarray so for example for this one inside the sequences there's a sub this one too yeah it means if you were to take cost two you must finish c one first so let's see the representations yeah we are just giving a integer number array yeah we want to check if there's only one unique numbers so this unique numbers uh yeah let me see uh let me tell how can I explain it so this unique numbers just yeah for example this is a subset set it is one two another subset is 13 yeah so it means we have two combinations one is 1 2 3 another is 132 because inside 1 2 3 we can find one two and 1 three inside 1 3 two we can also find those two subsequences one three and one two but we would two find only one members only one at the moment there are two that is why it is false we need to find only one so this is a typical top political s problem basically we want to find a unique combinations so let me yeah make a drawing of what does it mean yeah so it means so for example this is a one we want one to connect two and connect three we just want to have this unique top political structure so for example there is another three maybe also connected to uh there's another number four may be also connected to this number two so it means there are two uh different sequence it can be 4 2 three or can be one two three yeah but we want to find only one unique only one two and three yeah so this means for the to political s let's try to use another example maybe we can use this example yeah 1 two three we have 1 two 1 three and two three let's use this example so we have one two 1 three and 2 three yeah so if we have this kind of a structure so we want to find a r which have those two three subar so there's only one result it is one two three because this one two three it include one two it include 2 three it also include 1 2 3 but it there's only one unique result so this is why the to political thought works yeah we're going to start the toal BFS from the not one because there the ingree for nde one is zero now we're going to go to This n two and not three because for not three the in degree is two while we take out this one the integral is one but while we take uh this integrate for the not two it is zero so for the next one it will go to two and then for the next one it will go to three but for each of the step it can only go to one knot it cannot go to two KN or more than two KN yeah so this means this is the unique result if it can go to two KN for example from one to two or from 1 2 three at the same time it means the result is not unique so that is why the toal S works but we need to do some tricks to solve this unique problem let me prepare two variables the graph and ingree so the graph would be a default dict inside it will be a list and the ingree would also be a default di because I'm not sure how many not it is always dependent on the sequences so inside I'm going to put a integer now I'm going to prepare a unique set this going to check how many not inside of the sequences so the unique would be equal to set inside it will be n for s in sequences and for in s so this basically attck how many unique not like one and two and it can be others yeah now I'm going to prepare the integre so for in unique the ingree and for this no would be set to Zero from the beginning now I'm going to start yeah start the graph preparation at integrate preparation so for here I'm going to prepare this graph so for array inside the sequences yeah and for let's prepare another two not u in pair wise a yeah so for example this sequence it is one two the pair wise will be one and two yeah so if it is longer maybe one 2 three and four yeah I will always prepare the pair wise because it has up uh it has a sequence it will first finish one and then two and then three if there's another three after it yeah now I'm going to prepare the graph so for the graph it would be du. append this V because it will start from U and then to V and for the integr it will be the V so the plus equal to one now I'm going to prepare a q actually it is like a stack but I'm going to yeah defy a q so q i for i d in uh in degree do items so f d equal to zero now I'm going to check this CU I also need to prepare another variable result I need to check the sequence of the no so the result would be a empty aray now I'm going to check this Q so if the length of the Q is more than one yeah so this means inside there are two no at the same time it can you can choose either maybe there are two n one two you can choose either one or two so this means it going to be a falce it means there are at least two different cases but we need to return only one unique cases that is one two and three so we can return a force immediately otherwise we are sure the Q there's only one not inside the Q it should be equal to q. pop and we're going to text the neighbors should be inside the G not now we can prepare the integr neighbor should be minus one and we're going to check this integr neighbor if it is zero we just put it inside the Q yeah actually this is the entire code if we didn't return a force we going to have a result so this result should be equal to the nums if it is equal to the nums it means it is unique if it is not it going to still be return of false for example this one the sequence is one two and for result it should be one two but the num says 1 2 3 it means it going to be a false if the num is just one two it going to be a true now let me run it oh there's some mistakes and number three and four let me just have a attack it's going to be false yeah it seems I always return a false I didn't even return a true uh let me check what is the wrong so this is my ingree and this is a parir wise a and du the first one should append this way and the integrate of this V Should plus one and this is the Q yeah this is the Str I just solve it I solved it I think it should have no mistakes because while I'm solving it there's no mistakes but now I have a mistake I have to check why uh let yeah let me first check uh from here to check if the queue is right so for this example three let me check what's inside of the que it should have a one inside the que it means it is the right yeah because for this one it going to be one two and three now let me check this uh nums and check the result yeah let me just check what is the result inside yeah it is the empty yeah it is empty y because I didn't put it inside yeah I needed to put it inside so here while I pop out the no result should I pend the ND I think this is why now let me just run it yeah as you can see it works now let me just to delete to the print and submit to check if it can pass all the testing cases yeah as you can see the pass all the testing cases and it's pretty fast now let's analyze the time complexity so let's check the value of n is 10 to power of 4 and this n is the num. last so let's check from here so for this unique basically it is a yeah it is the sequences and inside of the sequences it going to times how many n let check the length of the sequences it is a 10 to the power of four and for each of the lens it is a 10 to the power of four yeah so this one actually it is n Square already yeah but it can pass uh yeah because while we are use uh I'm using this unique and for this set and for this R basically I'm attack all the sequences and the length of the sequence is 10^ 4 and for each of the sequence it is 10^ 4 and for each of the sequence it is 10^ 4 and for each of the sequence it is still 10 to^ 4 it means this is still 10 to^ 4 it means this is still 10 to^ 4 it means this is already in Square from here yeah and I cannot avoid that and for this one actually for this unique it's just inside of the set it should be yeah smaller than that uh it will be 10 to^ of 4 it will be o n but here it 10 to^ of 4 it will be o n but here it 10 to^ of 4 it will be o n but here it is a o n Square now let's check from here so for inside of the sequences and pair wise it going to still be o Square now let's check the last BFS so from here uh while we are checking this que if it is only one we're going to still Tex the next if it has more than two so we're going to not analyze the false because false will be smaller we're going to always check this true so for this is true it going to be uh it going to be o n yeah so the final time complexity it is the o n square and the o n square is coming from this unique actually from here yeah because this y Loop is just o uh yeah let me check it is not o n it is a o n Square here is also o Square because for Neighbors basically we're going to check how many edes and the edes will be maximum n Square yeah uh yeah because this for this BFS actually it going to Che each of the vertices and all the edges it is all e plus V and V can and this e can be v Square it means n Square so the time complexity is o n Square thank you for watching see you next time
Sequence Reconstruction
sequence-reconstruction
You are given an integer array `nums` of length `n` where `nums` is a permutation of the integers in the range `[1, n]`. You are also given a 2D integer array `sequences` where `sequences[i]` is a subsequence of `nums`. Check if `nums` is the shortest possible and the only **supersequence**. The shortest **supersequence** is a sequence **with the shortest length** and has all `sequences[i]` as subsequences. There could be multiple valid **supersequences** for the given array `sequences`. * For example, for `sequences = [[1,2],[1,3]]`, there are two shortest **supersequences**, `[1,2,3]` and `[1,3,2]`. * While for `sequences = [[1,2],[1,3],[1,2,3]]`, the only shortest **supersequence** possible is `[1,2,3]`. `[1,2,3,4]` is a possible supersequence but not the shortest. Return `true` _if_ `nums` _is the only shortest **supersequence** for_ `sequences`_, or_ `false` _otherwise_. A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,2,3\], sequences = \[\[1,2\],\[1,3\]\] **Output:** false **Explanation:** There are two possible supersequences: \[1,2,3\] and \[1,3,2\]. The sequence \[1,2\] is a subsequence of both: \[**1**,**2**,3\] and \[**1**,3,**2**\]. The sequence \[1,3\] is a subsequence of both: \[**1**,2,**3**\] and \[**1**,**3**,2\]. Since nums is not the only shortest supersequence, we return false. **Example 2:** **Input:** nums = \[1,2,3\], sequences = \[\[1,2\]\] **Output:** false **Explanation:** The shortest possible supersequence is \[1,2\]. The sequence \[1,2\] is a subsequence of it: \[**1**,**2**\]. Since nums is not the shortest supersequence, we return false. **Example 3:** **Input:** nums = \[1,2,3\], sequences = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** true **Explanation:** The shortest possible supersequence is \[1,2,3\]. The sequence \[1,2\] is a subsequence of it: \[**1**,**2**,3\]. The sequence \[1,3\] is a subsequence of it: \[**1**,2,**3**\]. The sequence \[2,3\] is a subsequence of it: \[1,**2**,**3**\]. Since nums is the only shortest supersequence, we return true. **Constraints:** * `n == nums.length` * `1 <= n <= 104` * `nums` is a permutation of all the integers in the range `[1, n]`. * `1 <= sequences.length <= 104` * `1 <= sequences[i].length <= 104` * `1 <= sum(sequences[i].length) <= 105` * `1 <= sequences[i][j] <= n` * All the arrays of `sequences` are **unique**. * `sequences[i]` is a subsequence of `nums`.
null
Array,Graph,Topological Sort
Medium
210
1,704
hey guys welcome back to Hustler's algorithm today we are gonna be solving this daily record challenge so determine if string halves are alike you are given a string s of event length split the string into two vowels of equal length ability with the first half and B with the second half two strings are like if they have same number of vowels okay so here we have to just divide this trick into two or such that the number of vowels in each of the house is equal okay so let's start so I'll create a function it will basically keep a track of the number of vowels in a particular string foreign character is a vowel so if it is a vowel then we will just increase our vowel count and then just return this count okay so let's check if it is available or not foreign all the cases for the character to be a woman foreign matches then we have to just return to else just return false okay so here we are calculating the number of points let's divide the string into two parts so the first part will be from 0 to half length where this upper bond is not included and the second part will be the remaining string okay so now just check if this account of vowels is same in both of the strings foreign okay divided by two great yeah so it runs fine so yeah it gets accepted so subscribe to the channel for more such videos thank you
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
75
hey what's up guys I'm Nick white that is my name you might be able to see that in my channel name or whatever but I am doing the although a coding hacker ranked problems please subscribe check the description for my information I do the premium problems on my patreon and I got a discord this problem is called sort colors so it's got a lot of likes so I'm given an array with n objects red white or blue colored red white or blue sort them in place so in place sorting so that the objects would the same color are adjacent okay so all the red ones are next to each other white ones are next to each other and blue ones are next to each other with the color is an order of red white and blue okay here we will use integer 0 1 &amp; 2 to represent red white integer 0 1 &amp; 2 to represent red white integer 0 1 &amp; 2 to represent red white and blue 0 1 2 red white blue bars okay now you're supposed to use the you're not supposed to use a library sort function okay that makes that's fair so what's an in-place that's fair so what's an in-place that's fair so what's an in-place sorting method I mean we got you know merge sort is not in place but quicksort is so yeah it's good I mean I already did it its like quicksort related it's a little bit of a twist but we'll just go through it and I'll explain it basically the idea is move all of the zeros to the front move all the twos to the back and then the ones will automatically end up in the middle if you follow those two rules yeah that's basically it so it's not too hard you should be able to get this pretty easily so for if gnomes dot length oh yeah here's an example 2 has to go to the back because they want them all touching so they want the zeros at the front the ones in the middle and the two twos at the back they'll have to be touching there okay there you go there's your example so numbers dot length is equal to 0 or nums dot length is equal to 1 we'll just return there's a void method so very nice we're gonna says to pass algorithm using counting sort now we're using one pass we're faster than that we're gonna be doing this okay so we're gonna need an index pointing to the start we're going to need an index - the ending element and we're gonna - the ending element and we're gonna - the ending element and we're gonna need an index I for our current element okay so I'll explain this we could use the word index so like that so while index is less than or equal to end meaning we're not at the last index and star is less than end meaning we're in the right boundaries here and we're not you know shrinking our array what we're gonna do is we're gonna use start to keep track of you know putting zeros at the front we're gonna use end to keep track of putting twos at the back and then index will just move along to the current number it's R it's pretty easy so pretty easy honestly so if nums of index is equal to zero then we swap to the front so we say nums of index is equal to nums of start so we swap those and then we do nums of start we would say numbers of index but if we just know what's going to be a zero and then start plus index + + so what this does is plus index + + so what this does is plus index + + so what this does is you have your starting point err at the first number and if we see a zero at any point we will just so when we see index is just moving along we have an index moving we're going number by number through this array when we see a zero we have this start variable that's just going to sit and wait to move zero so it's going to sit at the beginning of the array and we'll just swap to the beginning great else if nums of index is equal to two then all we have to do is nums of index is equal to nums of end is equal to two and end - - we're not gonna equal to two and end - - we're not gonna equal to two and end - - we're not gonna move the index forward for this and I'll explain that in a second and if it's a 1 we move our index forward okay so this is it I mean that's it's pretty easy there you go faster than 100% great one there you go faster than 100% great one there you go faster than 100% great one pass solution very simple you just have a pointer so what it what are these variables going to be doing the starting index is going to sit the front of the array so here's a sample the starting index will sit at the beginning of the array and it will move along whenever we see a zero right the ending index will be at the end in the ending index will move towards the middle of the array when we see a two so these variables keep track of the next place a zero needs to go if we see one so start would be here but we see it we see a zero right away so star gets incremented right now start is here starts it's at the next spot a zero should go at the beginning of the array if we don't see a start if we don't see and then what we're gonna do is we're gonna see one then we see a new zero we swap with start so start always just sits where the next zero should go and always sits where the next two should go so right here we see here's the reason that we don't do index plus right here is because for example when we see the zero we will or when we see a two I had this in my head a second ago I don't even remember now I was blank when we see a two we want to swap it to the back and then oh yes all right when we see a 2 we want to swap it the end stays here but we swap it and then we don't increment because we could swap twos from the back here's the reason we could swap twos you know when we swap to the last index it could be a two it could be a zero it could be a 1 it could be anything we have not seen that yet so we're it's the unknown so we don't want to increment the index because we want to do another loop and check what we swapped you know you could swap a zero here so if we swapped a zero to the end we see a two we swap the two and the zero we don't want to keep moving because that would be wrong we want to stay here make sure we swap that 0 up there so that's why we don't increment the index we already know III is moving faster than art so we already know what we're swapping eye for a one if we saw it - it would have been a one if we saw it - it would have been a one if we saw it - it would have been put in the back we're either swapping for we're just swapping for a one so I gets incremented here index keeps getting incremented here because we're putting the ones in the middle but at the end we don't increment the index because we don't know what we're swapping so we have to wait do another loop and make sure we're not swapping back into a zero or you know whatever so you know hopefully that makes sense you guys you know what I mean I think I explained it pretty well sorry about the pause I just I have like brain pauses sometimes I think it's cuz like I'm like you know I just want to finish this video and then I think that in my head while I'm doing it I'm like please don't mess up and then you mess up so I got a stuck get out of that but thanks for watching let me know if you don't get anything but yeah pretty good problem pretty cool pretty easy for medium see you guys later
Sort Colors
sort-colors
Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers `0`, `1`, and `2` to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. **Example 1:** **Input:** nums = \[2,0,2,1,1,0\] **Output:** \[0,0,1,1,2,2\] **Example 2:** **Input:** nums = \[2,0,1\] **Output:** \[0,1,2\] **Constraints:** * `n == nums.length` * `1 <= n <= 300` * `nums[i]` is either `0`, `1`, or `2`. **Follow up:** Could you come up with a one-pass algorithm using only constant extra space?
A rather straight forward solution is a two-pass algorithm using counting sort. Iterate the array counting number of 0's, 1's, and 2's. Overwrite array with the total number of 0's, then 1's and followed by 2's.
Array,Two Pointers,Sorting
Medium
148,280,324
1,614
hey everybody this is larry this is me going over the weekly contest two tens uh q1 maximum nesting depth of parentheses uh so i think this is just um a normal parenthesis problem uh with stack usually implemented and you have all these things but it really just saying that what is the level within which is the max step right and all you have to do because this is a well-formed string this is a well-formed string this is a well-formed string well from parentheses string you just have to keep track of the left parens and the right parens and as soon as you see a left paren you increase the dab and when you see the right parents you minus the depth and then you just keep track of the max depth that is available and that's pretty much it um yeah let me know what you think and we can watch the contest video next q1 okay okay ap between the nesting cup this is straightforward it's maxed lasting depth right why is this two and a three on a score i'm really confused a little bit but okay a little bit slower because i'm making silly comments but uh did i whoops noob oh yeah uh 331c okay that looks good let's admit computer's a little slower than usual but okay maximum hey everybody thanks for watching uh hit the like button hit the subscribe button join the discord and i will see y'all next contest bye
Maximum Nesting Depth of the Parentheses
maximum-nesting-depth-of-the-parentheses
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or * It can be written as `(A)`, where `A` is a **VPS**. We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`. * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s. * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**. For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s. Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`. **Example 1:** **Input:** s = "(1+(2\*3)+((8)/4))+1 " **Output:** 3 **Explanation:** Digit 8 is inside of 3 nested parentheses in the string. **Example 2:** **Input:** s = "(1)+((2))+(((3))) " **Output:** 3 **Constraints:** * `1 <= s.length <= 100` * `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`. * It is guaranteed that parentheses expression `s` is a **VPS**.
null
null
Easy
null
1,930
Saurabh Essay Welcome to this video NH10 Video Will Explain The Problem Undhiyu Subscribe Medium Size Question Solve This Problem Clearly And Will Be For Developing Approach And Subscribe Media To Solve This Problem Is Going To Be Used With Which You Will Find The Number Of Subscribe The Left Side Right Side Subscribe Do The Sole Supposes Dualism Character X Here So What Will Happen That You Can Find They will see channel like this is the right side 20 thousand 283 for 20,000 1570 right side 20 thousand 283 for 20,000 1570 right side 20 thousand 283 for 20,000 1570 1234 500 600 Current Affairs Facts Behind the Number of Birth Right will decrease welcome to the number of but less soy sauce will see to be absorbed in the left side of the Rebellion in Right Side Roles on Some of the Worst Thing Will Welcome Beads of Suffering from Nothing Can Be Made Here Forward -Forward Subscribe 2 -Forward Subscribe 2 -Forward Subscribe 2 End Subscribe 100 CR in K Official Fan Subscribe My Channel Subscribe Vikram Subscribe Quote C Roli Present One Left Side Me Off But Now He Will Move To 10 Software Avengers Update Account Soen Vikram Three And This Will Give One And Will Celebrate It Makes Old Baby Hair Soft Convenience Of Being Run Over By Road Wife Year I Like You Know Why Not Interested Baby This One More thing for roof bun hair from this point to my channel like this is not consider this string will be used for eggs and welcome to right to do the details of the black presentation liquid okay first things first make a s vector in liquid co full screen ok vector print left with 6 characters ajay ko ki wo ke vector and have a few tests to approach please like this video and subscribe the channel and rally motivate me to make for the videos and will make a nodal set n order rt satire just avoid Unwanted Staff Strength Will Not Be Difficult Daily Set The Volume To Be Coming Don't Want To End Opposition Will Be Returning subscribe to The Amazing But The Question Is Not Done Will Make Sure The Will Initially Is On The Right Side Of The Ride Point 800 i10 Sportz Price That I Plus And Travel Se Z - 1 That I Plus And Travel Se Z - 1 That I Plus And Travel Se Z - 1 A Plus Shyam Just Increasing Account For The Characters Saneshi And Sainik Election Video Point Is Equal To My Life Is My Tablet Size Plus Overtime Subscribe Minus Plus Remove Novel Travels The 2012 0 Subscribe [ __ ] That Shovels Se Debit Is Left Jis [ __ ] That Shovels Se Debit Is Left Jis [ __ ] That Shovels Se Debit Is Left Jis Grated 104 And Right Jogging Residency Sudesh Basic Elements Subscribe 1000 Subscribe My Channel Subscribe Plus Navel Maker String Re Rom-Rom Navel Maker String Re Rom-Rom Navel Maker String Re Rom-Rom Equal To Torn String So I Will Do Table To Start Palan Room Plus X Subscribe Button Room Plus David Such Android Operating System After A Long Time Know What Happen When Writing Subscribe Thank You Can Configure Please Comment Will Dare Attack You Check If One Rome A Particular Is Platform Time Getting Brightness President And Note It Is True Representation More Continue And Defeated Not Present and Insulted Cotton Shirt Paint Room Rent Room 210 The Problem And After Doing All This Possible Due Respect To Follow Current Affairs And They Will Just Here May Quickly Set The Current Character * Left Is Like That Current Character * Left Is Like That Current Character * Left Is Like That - A Plus Form In Preventing - A Plus Form In Preventing - A Plus Form In Preventing Account Update Current Character Divorces President 1609 Hair Removed From Left To Right And Left In The Will Return For His Work On I Am That We Thing Wrong List Mean Just See What's Wrong Hair Soft The Mosae Real Estate Festival Didn't Be Placid - - So That Was No Problem No It's Wrong Placid - - So That Was No Problem No It's Wrong Placid - - So That Was No Problem No It's Wrong In Me Use Night Is Running Knowledge Submit Aaye Ho Fit Submitted Ye Soch Validating Submitted For Watching This Is Not The Best Method But Time Complexity Is Going To Were Desperately Home Made Into The Thing Successful Operation On Thursday But It's job subscribe my channel thank you
Unique Length-3 Palindromic Subsequences
maximum-number-of-consecutive-values-you-can-make
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "aabca " **Output:** 3 **Explanation:** The 3 palindromic subsequences of length 3 are: - "aba " (subsequence of "aabca ") - "aaa " (subsequence of "aabca ") - "aca " (subsequence of "aabca ") **Example 2:** **Input:** s = "adc " **Output:** 0 **Explanation:** There are no palindromic subsequences of length 3 in "adc ". **Example 3:** **Input:** s = "bbcbaba " **Output:** 4 **Explanation:** The 4 palindromic subsequences of length 3 are: - "bbb " (subsequence of "bbcbaba ") - "bcb " (subsequence of "bbcbaba ") - "bab " (subsequence of "bbcbaba ") - "aba " (subsequence of "bbcbaba ") **Constraints:** * `3 <= s.length <= 105` * `s` consists of only lowercase English letters.
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Array,Greedy
Medium
330
205
hello everyone and welcome back to another leeco video so today we're going to be solving the lead code question isomorphic strings so in this question we're going to be given two strings s and t and we need to determine whether or not they are isomorphic so two strings s and t are considered to be isomorphic if all the characters in s can be replaced to get t okay so now this over here says all occurrences of a character must be replaced with another character while preserving the order of the characters no two characters may map to the same character but a character may map to itself so this over here is pretty important and we do need to take note of that okay perfect so now let's look at a few examples to actually better understand what this is actually saying so over here we have let's just call all these strings s and this over here t so we have the string egg and add so is it isomorphic or not so to see whether it's isomorphic or not let's see whether we can replace the letters in s to make it equivalent to a so one thing we could do is we could go to e and make all the e's in the string s equal to a so now we would have something like a g since all the e's become a and again we're maintaining the order so agg is not equal to add so what if something else we could change all of the g's to d's so in this case we would have a and then this g becomes d and this g becomes d as well so this over here now equals to the value add right so add and add right so this over here is isomorphic and we're going to return true but now let's just add a small condition all right one second all right so instead of having the words egg and add let's just make up another verb so let's say over here the word we actually have is egg e so egg e and the word over here is a d s so adds okay so now let's check whether it's isomorphic so let's do the same thing so the e is going to map to a and again this means all the e's map to a so this becomes an a then the g stay as it is so this becomes g and now this e over here also becomes an a so you can kind of tell that this over here is a problem both of the e's have to map to the same letter so this is kind of going to be the basis of how we find our solution so let's just go through this again so the g's become uh ds and we would have a d a but again add a is not equal to x so one way to look at this question which is pretty simple is that both of these values must map to the same thing so what it means is the first e we have over here at the same index for the string t we have a now the second e which is at the last index corresponds to an s so since they correspond to different things no matter what we change e with no matter what we replace it with we are not going to get the same value since we can only replace it with one letter so that's going to be how we find a solution we're going to create a mapping right and keeping that in mind we can just create a dictionary or a hash map right so in python it would just be a dictionary so let's see how we do that with this example over here paper and title so what we're going to do is we're first going to iterate through both of them at the same time so first we go to p and then we go to the same thing for t right so we have p and t so in this case we're going to make a mapping saying that for this to be isomorphic all the p's in string s must be mapped to a t okay so this is the rule that we have set perfect so now let's go on to a so at a we have the rule which is all a's must map to i so a maps to i perfect so again now again we came across a p and now this p also maps to t so that's not a problem because the previous mapping we had also maps p to t but just for the sake of changing it uh let's just say this was t i t-i-s-l-e tyler t-i-s-l-e this was t i t-i-s-l-e tyler t-i-s-l-e this was t i t-i-s-l-e tyler t-i-s-l-e okay that's the word so in this case this p now would map to an s which means that our value or words are not isomorphic since the first p of maps to a different letter altogether so let's just go back and continue with this example so now we have a e which maps to l so e maps to l and finally the r maps to e so in this case this value s can be replaced with some letters to give us the string t so this over here is isomorphic as well and one thing to note is the p both the piece do map to a t and still work out perfect now there's one small condition which i skipped over when i first did this question which is this over here no two characters may map to the same character but a character may map to itself so the main thing is that two characters cannot map to the same character so keeping that in mind let's look at this example over here so b a d c is our first string and then we have b a so let's just do this so b over here and the b over here they map to each other so b maps to b and that works right so you can replace the characters to map to itself so that's not a problem now let's go on to the a and over here we have a again so that tells us that the a maps to a which is also correct now we go to the d here and we have a b here so that tells us d mapped to b which is incorrect but let's just finish this first and now finally we have a c which maps to a so the c over here maps to a now this over here is actually incorrect and the reason for that is b over here maps to b and a maps to a which is correct but now the d also maps to b which is incorrect since each letter since b already exists and it cannot be repeated so both of these mappings this one and this one over here cannot exist and because of that this makes it not isomorphic and we have to return a value of false so now let's see what this looks like in code all right so we're going to start off by defining our dictionary and it's just going to be an empty dictionary let's call it d so now we need to iterate through our strings now one thing i forgot to mention earlier is that this is not going to work when the strings are of different sizes obviously right so to actually ensure that the question by default make sure that t and s both have the same length okay so that's something we don't need to worry about so now keeping that in mind we're going to iterate through this so we can just do for index in range and then we can take the length of f or t doesn't matter okay so now let's get both of the characters so let's have something called character one and character two so character one would be whatever is at the index of s so we will just go to s and go to that index and for character 2 you would go to t and then go to that index so now that we have the two characters we first need to check if whatever is in character 1 already exists in the dictionary so if character 1 or we're going to check if it's not in dictionary sorry so if it is not in the dictionary we need to add this character to the dictionary so the way we do that is we go to our dictionary we make character one a key and its value is gonna be character two that tells us that character one math to character two now there's something that we do need to add to this but we can get to that later so else so this is not the case what that means is that character one is already inside of d so in this case what that means is that we need to check if the current the previous mapping we had still holds true so already character one has some sort of mapping and we do check if that still exists and the way we do that is we go to character one right and we get its uh value right so this is what it's being matched to and this has to be equal to two now if it is sorry not to uh to character two right so if this is not equal to character two that means that both the same letters have different mappings now in this case we can just directly return false and instead of having it like this we can just make it a elsa statement okay so there's that now one thing that we didn't account for is this condition over here no two characters may map to the same character so now keeping that in mind we can write a small condition here so we can check if character 2 is in any of the values and we can do that by doing d dot values now if character 2 is in any of the values that means that there is a repetition of the same mapping in that case we're going to return false so finally this is going to be it and um outside of this if we get through the entire string and we don't end up returning false that means our answer is true so we end up returning true and as you can see our submission was expect accepted so the space complexity of this is going to be constant space because in the worst case we're going to have a dictionary with 26 alphabets and obviously it's not going to get past that so that's the worst case scenario and that is constant and the time complexity is going to be big o of n since we're iterating through our strings so thanks a lot for watching and hopefully this video did help you thank you
Isomorphic Strings
isomorphic-strings
Given two strings `s` and `t`, _determine if they are isomorphic_. Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. **Example 1:** **Input:** s = "egg", t = "add" **Output:** true **Example 2:** **Input:** s = "foo", t = "bar" **Output:** false **Example 3:** **Input:** s = "paper", t = "title" **Output:** true **Constraints:** * `1 <= s.length <= 5 * 104` * `t.length == s.length` * `s` and `t` consist of any valid ascii character.
null
Hash Table,String
Easy
290
879
hello guys welcome to deep codes and in today's video we will discuss little question 879 that says profitable scheme so guys this question is a bit difficult to understand at a far side but we will take multiple examples and multiple test cases uh so that you guys have clear understanding of what this question is trying to tell so uh continuing with the question understanding part you hear you are given some crimes now a crime consists of two things it consists of people it require a number of person or people it require and a crime has some profit associated with that okay so crime has two thing number of people it is required to perform that crime and it has some profit associated with it okay so here this group and this profit error tells what the it I index or the group Theory tells to perform the ith crime you need this number of person and you will earn this much of profit so let's say I value is zero so for uh the crime where present at the zeroth index you require uh people that means two people is two and profit you will earnings two as you can see for the zeroth index group and zeroth index profit so if I equal to one that means uh you if you want to perform a crime at the index one for that you require two person and for that you will earn three profit of three okay so guys we have to return the number of schemes or number of subsets you can say that can be chosen from the given number of crimes right the number of ways uh to perform given number of crimes by choosing some of their crimes satisfying this condition that the number of criminals are not greater than 5 and minimum profit that you earn is this okay now for each profitable scheme uh you need to generate profit at least minimum profit means it must be the profit you have generated must be greater than equal to the minimum profit and also the total number of members participating in that subset can be at most end right total number of members or criminals you can say that participate in the subset must not be greater than five clear that is because the member can give a member participate in one gram then that member cannot participate it in another crime right so member participated in only one crime and that's why the total number of members in a subset must not be greater than n okay clear so this might have given you some understanding what the question tries to tell now look at now let's go through the test cases so here in the first test case you are given five criminals that you have five criminals you need to earn minimum profit of three okay now you hear you are given two schemes to perform a crime one scheme required two person and you will earn a profit of two another scheme require two percent and you will earn a profit of three there are two ways to perform a crime right now uh let's say you need to find the number of ways by which you can achieve this minimum profit and not using this many greater than this many criminals right so what is one way so let's say if you took only this scheme 2 comma three so this is one crime scheme right so if you perform the crime by using this scheme then you will earn the profit of three so that is uh equal to the minimum profit and you use only two members right then now two is less than equal to five so this is one valid scheme right now another way what you can do is if you perform this scheme and also you perform this game so you perform both the crimes now here what is the total person required for and what is the total profit you earn five now four is less than total number of criminals you have right so you can perform this scheme and five is greater than minimum profit so this is also valid scheme so guys as you can see that there are two valid scheme right and so we're written two as our answer correct got it now let's look at this example so here you are given three different scheme uh that is index 0 index one index two now you need to perform a crime such that you earn a minimum profit of five okay so guys uh if you can observe the profit that all the scheme profit are only are greater than fire right so you can perform all this all these crimes individually because that will earn you uh profit or file like this uh crime time at the zeroed index that will give you profit of six then the first index will give you profit of seven and the third index will give you profit of it yeah so yeah you can perform all the crime individual then also you can satisfy the minimum profit right now if you perform this crime 0 and 1. so how many person will require it is three plus two five people will require so five is less than 10 yeah you so you we can perform this and the overall profit will also be greater than minimum profit if you perform this 0 and 2 0 is index and two second index the total members require five plus two seven is less than ten yes correct so yeah and profit is always also greater than minimum profit so it is value one and two that is um five plus eight is less than ten so yes we can perform this now zero one into this or how many members do we require if you want to perform this scheme that is five plus three plus two so ten members are equal so it is less than equal to the given number of members right so thus we can perform this so there are total seven varied ways to perform crimes such that it satisfy both the condition of the members as well as the minimum profit right so that's why we return 7 here now in the same example if you have something like this so let's say if you have so instead of 10 if you have 5 assume that n is 5. now how many different possible subsets of crime possible so let me give you index here okay so for this you can perform crime with zero zeroth index crime that is to be two uh two people and profit of six this is valid you can perform this uh crime of the index one that is with three people and seven of profit you can perform the crime at index two that will contain and that will require five people so it is it doesn't access the number we have and the total profit is eight now we can also perform 0 and 1 right because the total people required here is R5 and the profit is ten plus six thirteen right so this 5 does not access the total numbers of criminals that we have but if you try to perform this 0 and 2 then the total members require would be 5 plus 2 7 right and the profit is 14 but the seven members we don't have so we can't perform this so furthermore you cannot perform any of the crimes uh with a different subset because that will exit the total number of uh criminals that you require and you have only five so it will exceed it in that case so that's why here we written four as our answer because we can only perform four different crimes right got it so yeah I hope you guys have now some understanding of what in this question that we are trying to do we are trying to find the different subset or different ways to perform the uh the given uh crimes right such that each uh satisfy the condition of a total number of person that you have as well as the profit that we gain should be greater than equal to minimum profit okay clear so guys overall what we are doing we are just trying to select some of the crimes and such that the satisfy the condition so what we are selecting crimes that satisfy given condition so we are just trying to select the crimes that satisfy the given condition right we are trying to select the sum of the crimes right now from for this so what we can see for a crime of the ith index for that what we have two choices either to select or not select right now if uh if we can select that crime if members is less than n less than equal to n if the total members require is less than equal to then only we can select the crime right as uh the else we won't select it okay clear so guys as you can see that there is a choice for each crime we have then based on the choices we can write recursive solution we can easily write recursive solution because we have choices for each column that we perform right either to perform that crime in the current subset or not to perform that crime in the current subset right so yeah based on the choices we can write recursive solution easily and if you can write the recursive solution then we can further memorize it okay clear till here so guys it was a bit difficult part to understand the question now once you understood the question then the further coding part and approach part is very much simple that we are simply either selecting the current crime in the current subset or we are not selecting them so these two are the simple choices that we have to perform and to get the answer right so based on the choices we can write the requires the solution and then we can memorize it okay also you can try to develop the diagram that is a recursion tree or you can say decision tree diagram so let's say you have this so let me just take this let's say you have group equals to let's say 2 3 5 and profit area equals to 678 now how you will generate the decision tree or you can say recursion tree so let me name number this so first check for the zeroth index based on the index you have to do not select and select two option here we are checking for the zeroth index right so if you not select this then the current subset is empty if you select this the current subset we will have ah two person and with a profit of six right now take a look at a second at the index one so for the index one also we have two choices right not select and select so if you're not select it then the subset is empty if you select it then you have you currently have the three people and seven profit see we can select this because here n equal to Phi and minimum profit required should be uh how much it was also 5 yeah so we can select this is number of person is less than 5 we can see like this now from here also you have two choices right North select and select so if you don't select this then you have only this in the subset if you select this so here we are talking about the index one right index one so if you select index one then how many people will have in total five people it is it okay yeah it is okay so one is two comma six and another is three comma seven so total number is five but it is okay right now check for the third index uh a third crime or that is present at the index two at index two so for from for each state we have again two option not select and select non select that means empty selectedness we have only this ah this crime present in this in the subset right here also we have two choices not select and select so if you're not select this now if you try to select this then whenever we try to select we will check for the condition whether the number of person or members in the current subset exceed the end so here it is five plus two seven exit then so we won't perform this so this won't be performed okay again not select and select two options so now select will have a two comma six and select a When selecting two plus five that will access the end so we won't perform this select operation right and again not select and select so if you not select this then the subset will have this and if you select this then the total number of person will also access so we won't perform so at the end so this is the recursion tree we will form right so and then you will check how many of the final State have profit greater than five so this is first this is second this is third and this is four so there are four states so guys that's why we written four here right so guys this is how we can perform the visualization of the recursion solution that we are going to write right so this is this was just the visualization by the recursion tree this is the root and from that we have generated a different state and at four and for each node we have two possible state that is not to select and select so that same thing we will write in our code okay so let me explain you now the coding part so if any first I took this dpu so now how many different changing states are there in our solution so one changing state is the index or the ith crime right the second changing state is the member selected or the total number of members present in the current subset in the third state is profit the current profit or the profit in the current subset so these three are the changing variables and now if you look at the constraint then this trade can have maximum of 100 can be maximum of 100 so that's why we took DP of size 101 and this so on so this is 3D DP as we have three Changing State okay clear so we initialize this DP with minus one and then we call the solve function now the solve function has some of the parameters let us discuss that so the first parameter is member selected or it contains the total number of members selected in the current subset then this is the current profit or the profit uh total profit in the current subset index the current time that we are checking right the ith crime that we are checking now these are some other variables like and minimum profit group N profit Vector so that we already received from this now this is our base condition or terminating condition that if index is greater than group plot size then group dot size or you can say uh there are no more crimes remaining so at that point you will check the current subset profit is it greater than or equal to minimum profit if this condition is satisfied then we will return true or we can say 1 and the else condition we will return false or you can say zero so if this condition is satisfied we will return one that is true else false okay now we will check this to remove the overlapping ah sub problems yeah so that's we will check that if the sub problem is already calculated and stored in this DP array or not if it is stored in this DPI then we will return the answer now as we discussed that we have two choices not to select and select So based on that I code so if you're not selecting the current crime then we make no changes in the member selected current profit we simply increment the index or the ith Index right we don't make any changes here but guys if you are selecting the current grain then for that first we have to check whether the total number of members that we have in the current subset plus the in the group of index the ith group or the I crime required this many number of person so on addition does it uh satisfy the condition that total that is less than equal to Total members that you have total criminals that you have this is satisfy this condition we check if it's satisfied then what we do we call for this solve function again and add the answer inside this select so for that what we do we change this member selected by adding the total number of total creaminess in the current group right we also change the profit now here what we did is we choose the minimum of minimum profit and current profit plus profit of index then why we did this see guys the minimum profit can be at Max 100 right now the but the current profit can uh can be see the current profit can grow above minimum profit right can go above minimum profit but since our DP size has is one zero one that means it can store at 100 number F Max so that's why we choose this condition so that we do not go out of the Bound for the for this DP size we choose minimum of minimum profit and current profits plus profit of index see overall if the current profit increases the minimum profit then it is only beneficial right we don't have to maintain this how many it is greater we just want to satisfy that it must be greater than equal to minimum profit that's the only condition that we have to satisfy so yeah instead of processing the actual profit we will pass the minimum of both then also it is fine we just need to satisfy the condition right then we incremented the index in this other variables would remain the same and at the end before the return I stored the answer inside this DP right clear till here so the coding part is very much simple if you have understood the select and not select part and understood the question right now talking about the time space complexity the time complexity here would be because of number of um number of person into the minimum in the minimum profit in multiply the index so it would be nothing but 100 into 100 why this because as you guys can see this is the size of the DP and we are just trying to fill this DP now in order to fill this DP we have to uh we have to call the function this many number of frames correct so yeah that's why this is the time complexities and the space complexity is also obvious it is 100 into 100 as you can see and observe the steeping also it will take some recursive stack because of this recursion that we are calling but mainly you can say this is the space complexity so yeah guys that's all for this video if you guys have still any doubts then do let me know in the comment section make sure you like this video And subscribe to our Channel thank you
Profitable Schemes
maximize-distance-to-closest-person
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these crimes that generates at least `minProfit` profit, and the total number of members participating in that subset of crimes is at most `n`. Return the number of schemes that can be chosen. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 5, minProfit = 3, group = \[2,2\], profit = \[2,3\] **Output:** 2 **Explanation:** To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1. In total, there are 2 schemes. **Example 2:** **Input:** n = 10, minProfit = 5, group = \[2,3,5\], profit = \[6,7,8\] **Output:** 7 **Explanation:** To make a profit of at least 5, the group could commit any crimes, as long as they commit one. There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2). **Constraints:** * `1 <= n <= 100` * `0 <= minProfit <= 100` * `1 <= group.length <= 100` * `1 <= group[i] <= 100` * `profit.length == group.length` * `0 <= profit[i] <= 100`
null
Array
Medium
885
33
can't i just undo the rotation and search in a normal way well you can but then you will lose out a lot of time just trying to undo the rotations we will try to solve this problem using a modified version of the binary forge in the rotated array itself hello friends welcome back to study algorithms a place where i simplify programming for you with animations visuals and some really easy to understand examples today we will be solving a problem on lead code the problem is first in a sorted rotated array first i will explain you the problem statement and show you some sample test cases next we will try to solve the problem and see what limitations we may run across going forward we will see an efficient solution to the problem followed by a dry run of the code so without further ado let's get started the best way to understand a problem is to understand the given sample test cases as per the problem it is pretty straightforward you are given an array that has some sorted integers but the catch here is that this array has been rotated by an unknown number of times and in this array you need to find a target value if you can find that value return the index is just return a minus 1. so you can assume that your initial error was something like but this array has been rotated and you do not know how many times it has been rotated after rotation this becomes like this and in this array you need to find out if 0 exists or not if it does in this case 0 exists at index number 4 so your answer would be 4. in test case number 2 you need to find if 3 exist in the array you cannot find out 3 anywhere in this array right so in this case you need to return a minus 1 because you were unable to find out the element right in a test case number three you have just a single element in an array that is also a valid test case right because there is just one element and it has been rotated any number of times the array would still remain the same right and you're trying to find zero in the array you can't find it right so once again your answer would be -1 if once again your answer would be -1 if once again your answer would be -1 if you understand the problem better now feel free to try out the solution on your own otherwise let us dive into the solution a good developer always tries to come up with a brute force solution first that is because approved for solution ensures that a solution to a problem exists so how would the brute force solution to this problem look like i have this array is sorted but as you can see it has been rotated by some amount of times now we don't know how many times it has been rotated one way to solve this problem would be i can simply unrotate this array so when i un-rotate unrotate this array so when i un-rotate unrotate this array so when i un-rotate this array this would become something like now my array is a normal sorted array and there are no rotations if you have to search for the number 7 in this you can easily apply the binary search algorithm and come up with an answer and voila you just solve the question but do you see the problem with this approach you could say that hey i was able to find out my number in order of log n because of binary search but we are also unrotating the array and unrotating the error takes up an order of n time in this case the actual time complexity of this solution turns out to be order of n in that case you might as well just do a linear search and iterate over the entire array and that would be faster right so intuitively if your array is very large then your time will increase and we are never taking any advantage of the fact that this array is already sorted so what can we do about it let us try to solve this problem using a binary search we know that we cannot apply binary search directly on this array right because it has been rotated but can we find out the pivot using binary search i think we can what is the speciality of this pivot element if you see the pivot element the element to the left of pivot and the element to the right of pivot they both will be greater right you can see that none of the other elements in this array have this property using this property what you can do is you can try to search for a number in the array that has the left element greater and the right element greater so you would be able to narrow down the pivot element once you have narrowed down the pivot element what simply happens is you have divided the array into two parts one part would be the right array and the other part would be the left sub array if you look closely both of these arrays are now sorted and it is very easy to apply the binary search algorithm in a sorted array right so given the target element 7 you can just look at the first element you see that 7 is smaller than 9 so you won't find it out in this sub array correct and you can apply the binary search algorithm in your second array because 0 is less than 7 and hence there is a chance that you might find 7 in this sub array if you apply binary search on this sub array ultimately you will find the element 7 and then simply you can return its index in this approach we take a order of log and time to find the pivot element and then we again take a order of log and time to search our target element in the sub array so hey that is a very good time complexity and ideally you were able to solve this problem in order of log and time complexity this solution is good but can you even further improve it over here we are applying binary search two times first to find out the pivot element and then once again to find out the target element in our sub array could we just apply binary words on the original array itself and somehow arrive at our answer let us see how we can do that i call this method the modified binary search but before actually diving into the solution let us try to understand what happens when you do a binary search whenever you do a binary search you are separating the original problem statement into two halves right you can also check out my video on binary search in case we want to brush up your skills so we are always separating the array into two halves right and then based upon some condition we discard one of them and we are ultimately left with just one half right so why not we try to apply a similar technique on this problem what happens when i let's say divide this array into this half this would give me two half of the array right a left sub array and a right sub array let us see how do they look so you see i have divided the problem into a left sub array and a right sub array the beautiful part of this problem is that the array is sorted so no matter wherever you divide the array you will always get one array that is sorted in itself and other array that is unsorted if you look at the right sub array this is a sorted array right so if your target value is between 2 and 7 then you can simply apply the binary search on this sub array right and you will be able to arrive at your solution correct however if you don't find a target value in this half let's say i was trying to search for the number 9 in my array correct so then i am remaining with my left sub a if you look at the left sub array i know that we have divided it but it still remains a sorted array that has been rotated by some number of times right so once again if i divide this array into two parts let us see what do the two parts look like if you see again i have a left sub array that is sorted and a right sub array that is not sorted once again you can check your target value if it lies between 8 and 10. if yes you can simply apply binary search on this half else once again what you can do is you are left with a write sub array now i think you're getting the idea you can again recurse over this array and again divide it into two at every iteration you will be able to discard one half of the array in which you can't find your solution so using a recursion-based algorithmic using a recursion-based algorithmic using a recursion-based algorithmic paradigm you can apply a modified version of the binary search to ultimately arrive at your solution let's say for instance even at this moment we weren't searching for 9 and let's say we were searching for 11 what would happen is you would again divide this array into two parts and you would get 11 as one half of the array and 0 1 as the other half and you will be able to ultimately l if you could find or not find the number in the array the time complexity of this solution would just be order of log n that is because we are just dividing the array into half and then again applying the binary search on one of the sub errif if the solution is now clear to you let us do a dry run of the code and see how it works to understand the dry run i am taking a sample array and i am trying to search for the target element 8 in this array on the left side of your screen you have the actual code to implement a modified binary search the array is passed in a parameter you have the target value also passing in as a parameter the value of left is the starting point of the array in this case it would be 0 and the value of right would be the ending point of the array since you are just starting the loop the value of right would be equivalent to the length of the array so in this case the value of left is 0 and the value of right is 9 that are pointing to each of the indices next we have our terminating condition if we are unable to find out the element going ahead i try to find out my middle value now the middle value is left right divided by 2 right because we are bisecting the array into half so right now the value of mid would turn out to be 4. that means we are dividing the array into 2 halves right over here next you check if your left half is sorted in a rotated array if the first element is smaller than the last element of a sub array that means this sub array is sorted right so you would see if 7 is smaller than 1 it is not right that means this left sub array is not sorted so we skip this and we immediately go in our else part that means our right sub array is sorted and as you can see 2 is less than 6 so this right sub array is sorted now we will try to find out a target element in this part the value of target element is 8. so i check if is my key in the right half since 2 is also less than 8 and 6 is also less than 8 that means i won't be able to find out my key in the right sub array and hence what i do is i simply recurse and i would recurse in my left sub array so i recall the same function again with the same array and the same target value the left value is also same because we are searching in the left sub array but this time my value of right becomes mid minus 1 so i recurse this array with the value of right as 4 minus 1 that is 3. so that means i would be only looking in this part of the array right once again if you see my recursion starts i would try to find out the middle value in this case 0 plus 3 that would come out to be 2 that means we are bisecting over here and once again we would see if my left half is sorted or right half is sorted so this time the left half is sorted and we will try to find out my target value in this half this loop will go on and ultimately we will be able to find out that yes 8 exists in an array and then you can return the position as its answer i hope i was able to simplify the problem and its solution for you this is a very important question that is asked in a lot of interviews and you will find some of its applications in a lot of programming challenges as well so congrats you leveled up a little bit as per my final thoughts i want you to start thinking what other methods can you come up with or rather what methods did you try and what problems did you face were you able to reduce the time complexity even more let me know your thoughts in the comment section below and i would love to discuss all of them with you would be also glad to know that a text-based explanation text-based explanation text-based explanation to all the content of this channel is available on the website so if you're still facing doubts or if you want to read more about this problem feel free to check out this website i am including a link in the description below as always you can find the sample implementation and the test cases to this problem in my github repo as well the link to which is again in the description below once again if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you until then see ya
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array `nums` sorted in ascending order (with **distinct** values). Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`. Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 0 **Output:** 4 **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 3 **Output:** -1 **Example 3:** **Input:** nums = \[1\], target = 0 **Output:** -1 **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * All values of `nums` are **unique**. * `nums` is an ascending array that is possibly rotated. * `-104 <= target <= 104`
null
Array,Binary Search
Medium
81,153,2273
523
okay so lead to lead code practice time continuous separation so two goals in this video the first one is to find a solution for this specific question do some coding work and the other thing is to go over the interview process given the specific example so let's take a look at the question itself so given a list of the non-negative so given a list of the non-negative so given a list of the non-negative numbers and the targets integer k write a function to check if the array has a continuous array of size at least two that sum up to a multiple of k okay so let's say given example 1 23 2 four six seven as the input array k is equal to six returns true because we definitely have a sub array which are two four okay that sum up two six all right so i think i mostly understand the problem let's think about the ash case so the ash case from the top of my head for example if k is illegal for example if it is zero or if it is smaller than zero some negative integers or zero then what should we return so suppose the interviewers say that those are illegal inputs and it won't appear then that would be good and the other thing i can think about is what if the input array is empty or contains only one number then of course that one is going to be uh we are going to return false for them so let's say we so first of all we add these those ash keys checking at their beginning so if number lens is smaller than two or k is smaller than zero then we definitely return a false here and if k is equal to zero then we define to return for sorry return true here okay so those are the ash cases let's step into the next thing which is to find the solution for this uh specific question so how to do it so the first thing which is quite brutal is we enumerate all the subs sub arrays and the sum of them up and to see if it is uh n times k so this one is going to take n cube for the runtime if we want to optimize it let's say we try to start from each point within this array try to extend as much as possible and during the time we do the extension we will see whether the current sum is n times k um that one is going to be n square for the runtime um so let's see if there's any other option for us to do to further decorate the runtime um sure so it makes me feel that it is something like a dynamic programming question but not sure how to do that yet um let's think for a moment okay so i think i quite got it so suppose um so suppose we keep the sun okay so let me explain it in this way so first of all we will define a map so both key and value are of integer type so the key of the map would be um sum of sub array uh between zero to the end to the current into the current index modular um k and the corresponding value is the index so let's see let me give you an example by taking the first example provided here let's say if suppose we have the input area looking like this we will initialize the map with zero minus one as the first pair so y is zero minus one because we let's say we are going to take a placeholder so if there's no number so like we think before we iterate through this uh this specific input array we see that uh before it the sum is this because there's no number the sum of course is zero and then we put a placeholder for the value which is minus 1 out of range of this input array and then we will put 23 modular sex so here it is going to be 5 and plus and the corresponding index is 0. and then 23 plus two which is 25 modular uh six so this one it is going to be one and uh the corresponding index is one and then we have 23 plus two plus four and then modular uh modular sex so now it is 5 and the corresponding index is 2. so now it is a time we find there is already a pair within this map with key as five and the corresponding value previously is zero so since it has the same value for the modular of k then we can say that between index 0 and index 2 it is a sub array that is sum up to n times k so that's that so at this time we can safely say um we find a sub array regardless the start index and the end index because this question is not asking to asking us to return the specific index it's just asking us to return true or false so in this case we are going to return true okay so that's pretty much about the solution and regarding the runtime um it is going to be linear uh to the so linear suppose the length of the input array is n then the runtime is going to be all of n and space wise it is going to be 11 as well so let's give it a shot by doing some coding work after we find the solution it's time for us to turn our idea into solid code let's do some coding work on top of it so like i said we are going to define a map both key and value or integer let's say it is sum to index map so we are going to either iterate through the um the array okay so before that we are going to put a placeholder pair which some index mapped output zero and the minus one into it so as we iterate through this i is smaller than nonstop less plus i um so sum is initialized is zero so sum plus uh equal to nums i so if um so if so okay so we are going to has to find the modular if mode so we define the mode here mode is defined as sum modular um k if some index map already contains the key already contains chemo key of the mode we are going to see whether the sub array size is larger than one if years then we just return true for it if it contains key so if some index map dot gets a mod minus i uh is larger than the is if it is larger than zero so if it is larger than zero then it means let's see so the sum of it if it is larger than 0 then it means that it means it is a sub array but it can it may not make sure that uh it may not be able to make sure that it is a separate with the lens to be larger than one so if the sum index map effect contains the mode it means we already have something in it okay so let's see if this one we are going to return to here but we are going to fix this one after this because i haven't considered very well about this part and but if it's not that we are going to continue otherwise we are going to just put this so you're going to put some index map that puts the mode as a key and the corresponding value which is i in here okay and finally we are going to return false but let's try to decide if this one could be a solid condition so i think it might not be solid because if the size is larger than zero you cannot make sure that uh if it's larger than one i would say it's good but if it's larger than zero uh okay so let's take a look at this example if we have that as okay so when we find 20 so 23 2 and 4 so we find twenty three two four so okay so that's the time we find another five there if you find another five it should be larger than one okay um okay yeah it should be larger than one then it should be good then let's go through this so after we finish the code it's time for us to do some testing so for the testing part we are going to go through a example uh to do some sending check and at the same time we are going to explain how this piece of code is going to work so we have already explained that the ash cases and let's directly go into this general logic by using this piece of code by using this input example let's say we have the input as 23 2 4 6 and 7 and k is equal to 6. so at the very beginning we are going to initialize some index map the same as 0 and minus 1. so uh so when as we iterate through this iterates through this input array um we are going to insert new things into this some index map so currently when i is equal to 0 the sum is equal to 23 and the mod is 23 mode six which is five and it since the index map is empty we are going to put five zero into this map and continue we have we are going to put one and one into it and when we encounter the second the third element in the input array we are going we see that the sum is uh 29 so 29 mode 6 is equal to 5 again so we encounter another 5 and we see the current index i is equal to two is equal to zero one two is equal to two so two minus zero is larger than one then we return true okay so i think it should work in general as other test cases we can set up other test cases um for example we can set test cases like those ash cases and also uh something like if you only contain a number uh we if we only have a we can if for the input array there is only uh there is only single number separate that can be n times k so for example if it is five and the six and k set up as six is it going to return true or false this would be another good task cases to set up so other than that i think we should be good to go so let's give it a shot by running this visa code okay some compile some typo here okay so it is wrong answer so 232467 uh why it is giving us false let's see um so first of all we are going sum is plus equal to nums i let's go through this visual code again so at the very beginning we put zero and minus one here sum is equal to zero so sum plus equal to nums i which is 23 so 23 modular 6 um which is 5 and mode is 5 and this the map is empty here now we put the five and the zero into it and then when i is equal to one then so now sum is equal to 23. so when i is equal to 1 the sum is equal to 25 so mode is 25 mode k which is one of course is not in the map we are going to put one and the corresponding value as one here okay so now we when i is equal to 2 we are going to have sum as 29 all right so 29 the modular 26 mod 6 29 mode 6 is equal to 5 so mode is 5 and we already contain 5 in this one uh oh sorry i this is a typo here it should be i minus this one yeah so this is uh yeah so i think i was i wasn't typing as what i was thinking so now it is accepted let's submit this visual code okay it's another wrong answer so what if it is minus six so if it is minus six output is false oh okay so that's i think we just misunderstand um what we define as ash case so actually uh for minus 6 we also consider it to be some valid input so that's our misunderstanding and also if uh output if the okay so if the input is zero then okay so if k is equal to zero then we shouldn't return true for it okay so that's another uh misunderstanding about it um all right so how to okay so if it is zero then we are not going to return uh we are go not going to blindly return true for it so instead we are going to return okay so if it is a zero then we should maybe you should return false based on the uh cons based on this decision so if it is zero then um we should return a okay so if it's zero as the input array and the return value is and the case defined as zero the output is we should return true for it uh oh um okay so now i think i understand how to deal with when k is equal to on zero so in sum is equal to plus one into mode is uh k if k is equal to zero if it is equal to zero then mode should be uh zero yeah so in this case i think let me see if it is going to work so if some index we put 0 as value minus 1 is here okay so sum is always equal to 0 if k is equal to 0 we just put zero instead that modulate and we if i is equal okay otherwise we continue uh otherwise we just continue okay so let's take give it another try okay yes so it is a misunderstanding about what return in some ash cases so in this case it is still returning uh the wrong answer i not why it is because um okay so this is become becoming uh more confusing to me so if so 23 2 6 and 4 7 and the return and the given k as equal to zero currently we are giving the output that's true but actually it is expecting uh false that is because oh okay so if there's any sub rate that sum up to zero it should be that's essentially uh what it is asking us to do hmm um interesting so if it is equal to zero then essentially we need to see um if there is any continuous zeros there okay so if it's equal to k is equal so modular sum so actually uh if k is equal to zero we need to do some special things if k is equal to zero um we will see if there is any continuous thing so int um so it's i is equal to zero i smaller than nums dot plus minus plus i so if um nums i plus because it's a non-negative plus because it's a non-negative plus because it's a non-negative integers plus i plus 1 is equal to 0 then we return true otherwise at the end we should return false okay so let's submit this again so now it is accepted okay so actually um we misunderstand the special task case which is n which is k equal to zero so if it's k equal to zero it has to do something like if there is a sub array sum up to zero we return to otherwise we return false so that's exactly what it asks what we are trying to do in the first within the first step to think about ash case we need to clarify the ash cases clearly with our interviewer so in the at the very beginning we just think that we can blindly return true but it's not true based on the setup of the test cases in this specific example um yeah so that's um that's a lesson we learned um but it's a good thing um because we notice how to we notice the importance of to of clarifying the ash case at the very beginning and uh sure so that's it for this coding question um i hope you find this uh a little bit helpful during the time you prepare your technical interview so thanks for watching it and i'll see you next time
Continuous Subarray Sum
continuous-subarray-sum
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_. A **good subarray** is a subarray where: * its length is **at least two**, and * the sum of the elements of the subarray is a multiple of `k`. **Note** that: * A **subarray** is a contiguous part of the array. * An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`. **Example 1:** **Input:** nums = \[23,2,4,6,7\], k = 6 **Output:** true **Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6. **Example 2:** **Input:** nums = \[23,2,6,4,7\], k = 6 **Output:** true **Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer. **Example 3:** **Input:** nums = \[23,2,6,4,7\], k = 13 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `0 <= sum(nums[i]) <= 231 - 1` * `1 <= k <= 231 - 1`
null
Array,Hash Table,Math,Prefix Sum
Medium
560,2119,2240
119
hello and welcome to another video today we're going to be doing Pascal's triangle 2 which if you haven't done Pascal's triangle one it's basically the same thing except instead of getting one single cell we're getting a row now so given an integer row index return the row index row of the triangle and Pascal triangle each number is the sum of the two numbers directly above it and so basically the way Pascal triangle works is the left side is all ones and the right side is all ones and then all the middle values are the sum of the two numbers above it so like this two is the sum of one and one this three is a sum of one and two three is one and one so we even have some more that we can fill in here so here it be three and three so it' be six and then three and three so it' be six and then three and three so it' be six and then here be three and one would be four and so on right so every row is one more integer and it always looks like this one and then you know all of this stuff so for row index 3 we'd want to return this row here for row index zero we'd want to return this row index one we'd want to return this so the rows are zero indexed where you have you know row zero Row one row two Row three row four so there's a few ways to do this um one way I'll briefly mention is you can get a number by doing DP so like let's say you want this number you would just write like this is row whatever this row is and the column would beever it is and just do DP and then you can get every single cell by doing the DP and the base case of the DP is if you have uh column zero or you have column whatever the length of the row is right so I think this a zero or one or a two or a three or a four so if you have column zero then it's going to be all of these so it'll just be one and then if your column equals your row you will also have a one right and so even for here this is row zero column Z so that's kind of the base case and then you can build it up that way and then your cursive case would be you go up a row and then it's going to be the two items these two items so for example this is at column two so we would want you know go going up a row so let's say this is row four and column uh two you would want Row three column two and then Row three column 3 add those up actually sorry it would be Row 3 column one and R three column two and so on right so that's pretty straightforward how to do that so that's how you DP but instead of doing that we're actually just going to build these up so this is kind of like bottom up DP I guess you can think about it essentially we're just going to build a rows one by one until we get to the row we want so how's that going to look well let me show you so what we're going to do is we're going to have this first thing and we need to build like for this first example we need to build three rows right we need to build so this index 0 1 two three so we need to build this row which means we need to build three rows because we're going to build row by row so for the for every row we're going to build it's going to look like this it's going to have a one at the start a one at the end and then the middle will be all the summations of the row above because as you can see for all these rows there's a one at start one at the end right so for this row Above This is row index zero all the summations of the row above meaning every two adjacent elements we're going to add those up and return the value so here there are no two adjacent elements there's only one so actually our row that we built is just going to look like this so it's going to be this and as you can see that is right for this one now let's build the next row so we're going to have the one and then the one right so one here what's in the middle well we're going to go through every element here and add it to the element after it so here there are only two elements so there's only one thing to add so we will have two and that is the third row that's what it looks like so now that we have this row to make another row once again it's going to have a one at the start one at the end and then everything in the middle will be the things ated right so 1 + 2 is 3 and then 2 + 1 is 3 1 + 2 is 3 and then 2 + 1 is 3 1 + 2 is 3 and then 2 + 1 is 3 1 is what we have so we can actually build a couple more rows even for practice because it's pretty straightforward so to build the next row once again one and then you do all the sums right so 1 + 3 is 4 3 + 3 is 6 3 + 1 is 4 and we'll + 3 is 4 3 + 3 is 6 3 + 1 is 4 and we'll + 3 is 4 3 + 3 is 6 3 + 1 is 4 and we'll build one more and as you can see every row has one more element so for this row it would be one + 4 is 5 4 + 6 is 10 6 + 4 would be one + 4 is 5 4 + 6 is 10 6 + 4 would be one + 4 is 5 4 + 6 is 10 6 + 4 is 10 and 5 so you can see like you can keep doing this right and 13 31 is actually the row we wanted but this one is also this one and this row would be down here so we can just keep building these rows and we only need to keep track of the previous row and the current row we built right so we start with this and then when we build this once we build it we can just say okay let's just delete that and only keep track of this right you only need to keep track of the row that you built and the previous row and that's it so we're not going to keep track of like this whole triangle we're just going to keep track of one row and then we're going to build up and so on and so this is pretty much like as easy of a bottom of DP as you as it gets kind of I guess if you want to think about that way so let's actually code it up so we're going to have our initial case right where the row is just one and then basically we want to build a new row index times right so for this row index like let's say want to get row index three we want to build three new rows so we can just say 4 I in range row index our row can just be one plus so we're actually going to do a list comprehension here so we're going to list comprehension through our old row so we're going to say row J plus row J + one right whatever index J plus row J + one right whatever index J plus row J + one right whatever index we're on let's add that and the one after and this ensures that and essentially we want to go through every index except for the last one because like in our picture you know when you're doing these like for a list let's say you're on this index then you add this plus this you're on this index you add this plus this index but you don't want to be on this you don't want to be in the last index because there's nothing to add so we want to essentially go this J needs to be every index in the old row except for the last one and so that's going to be 4J in range so if you think about like this needs to be so I starts off at zero right so ideally you want the last index to be the second to last element so here there is only one element so you wouldn't want to do anything so actually what you need to do is you need to say I here because let's just go through it for a couple of these I guess so let's actually finish writing and then we'll kind of see how this works so essentially what would happen here is at for it would start at index zero right and for index zero range zero is nothing right because it starts at zero and ends at zero so that's nothing so then what you want to do is you want to actually go through range one and then range one would give you only index zero which is what you would want right because the first thing you build up is like this so range one would just only do this index which is what you want and then range two would have you know we would have three items now and then range two would be this one and this one so on so essentially you can just try to like you know when you're doing these things you can also make it not like in one line you can make it bigger or you can just keep like trying to make sure your index is correct but essentially this is the index you want to make sure it all works and then finally so essentially what we're doing is we're just overwriting a row right we're saying whatever our row is let's overwrite it with a one and then a list comprehension of that row where you add every element to the element after it and then a one at the end and we need to do that row index times then finally we can return the row and looks like we have an error syntax error okay so I think we probably have an unmatch something too many PRS somewhere I think it's this one there we go so essentially we're just building this up and up until we have the right thing and about this uh time and space complet lexity this is actually as efficient as it gets um apart from there is like a math efficient solution but this is as efficient as it gets so also if you think about it doing this versus calculating every element is actually the same time complexity we're just saving space because we're only building up one row here instead of multiple rows but yeah the pretty much every solution is going to be like this where it's going to be o of like n^ s time I it's going to be o of like n^ s time I it's going to be o of like n^ s time I think something like that we'll go over it and then there is like one combinant to solution which gives you something red away I think it's like a lot faster but coming up with a Comin tox isn't like the best thing to do so but yeah so this one's a pretty good one and let's actually think about the space and time for this one so for the time if you think about it we're essentially going down like to the row we need so whatever this row index is we're building and how many rows do we need to build roughly row index like this isn't exactly n byn but it's roughly that right so like to build row four we need to fill in three elements and so on so it's roughly that so this is basically n squ for time because forever like it's not like I said it doesn't look like a square but it's roughly a square okay and for the space it is actually uh o of row yeah so essentially we only have one row now so how big is the row well it's going to be roughly row Index right so if we need to row three it'll be roughly it'll actually be like one more element than row index but it'll be the same thing so essentially roughly oen where n is like the row you're on because that's the biggest row we're going to build so if this is like three then our row is going to have four and so on so it's roughly that and yeah pretty easy uh bottom up DP problem for this one like I said you could also do it with a normalization you go through your row you get each number with a visited dictionary also Works those are the main ways of doing other than the combinatorics it's kind of hard to come up with so hopefully you liked this video and if you did like it please like the video and please subscribe to the channel and I'll see you in the next one thanks for watching
Pascal's Triangle II
pascals-triangle-ii
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowIndex = 3 **Output:** \[1,3,3,1\] **Example 2:** **Input:** rowIndex = 0 **Output:** \[1\] **Example 3:** **Input:** rowIndex = 1 **Output:** \[1,1\] **Constraints:** * `0 <= rowIndex <= 33` **Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
null
Array,Dynamic Programming
Easy
118,2324
980
A Firewall Welcome To Bank Ko DP Tubelight England T20 Beats Abe Saale Tere Ko Subscribe Video Under Subscribe Exactly One Off Kar Do Hai Zero Representatives But They Can Bhava Ko And - Preparation Of Psychotherapy That Note And - Preparation Of Psychotherapy That Note And - Preparation Of Psychotherapy That Note Book Written The Number Four Drops Participated In Obligation And subscribe The Video then subscribe to The Amazing 10 And Subscribe And Direct Debit The Great Gatsby Subscribe To This Sandwich Represented By To The Supreme Being Blessed And Love You To Front Part 2 - Beneficial Notification Adhir Which Front Part 2 - Beneficial Notification Adhir Which Front Part 2 - Beneficial Notification Adhir Which Can Go From Arresting Them Left And Right Subscribe Can Go To Disposition That They Can Go To Jaipur Sindhi Select One 's Right Direction 5120 From Noida To Darkness 's Right Direction 5120 From Noida To Darkness 's Right Direction 5120 From Noida To Darkness Drowned Skin Do Subscribe My Channel Subscribe Channel Like And Subscribe Diy Ocean Tera Member Napa By Bring All The End Research And Come Into Effect Saugand Slicer Ko Andha Vriksha To Test Dushman Pass Sunao Let's Move To The Second Edition They Do You Do Subscribe My YouTube Channel Have Not Subscribed That In Them That And They Cannot Be Reduced To Befal Covering All Episode 162 Update In This Was Not Visited Ahead AND WHEN FALL SE WEATHER IT IS QUITE A STIR WELL FACTORY PROBLEM THAT AND NOW LET'S AFFAIR WITH RAKESH KAWAR AND TEMPTATIONS AND RICHED TO RIGHT SUBSCRIBE AND SHARE AND ABSTRACT THIS POINT INSTITUTE OF GOING DOWN 512 LIGHT ON NAGIN 'S FAN 6-CELL BATTERY FOR MOTHER After Might Jai Hind Is To-Do Is Jai Hind Is To-Do Is Jai Hind Is To-Do Is Suggested By Valid Passport Software For No Apparent From This 251 Direction Subscribe To 120 Test Your Knowledge Bread Speed ​​Tonight 120 Test Your Knowledge Bread Speed ​​Tonight 120 Test Your Knowledge Bread Speed ​​Tonight And Rhymes For Kids In The Test Difficult Celebs Caught Off-Guard 102 A Side View That Govinda All Direction and with this that this fast was given 13 written on that and this is already visitor no's day it is up and dadar condition checking depository receipt to but all the mission more subscribe to members condition caste check and the Husband's condition editor and gift is that slip is how to that and all MP3 of covered all were that his sale his cover day update mere pas teri bullet again pat hu is the variable do partner oak 21000 shoes person problem solved in Photos Positive Thursday Subscribe To And From A Main Swayam Koi Murda Grade Nalu Anup Das Less Having Difficulty Stop Starting And Remembering The Great Agnivansh Settings And Select Servi Subscribe Of Track Medium subscribe and subscribe the Page if you liked The Video then subscribe to subscribe That and up to the time to go do in all four directions and 2nd this truth of the day is but e declare emergency deliver a global pathri urination increment in one side and upright conditioner officer to end gautam subscribe that alarms mathura to go varinder Grade Notification Light Sorry for the time This is grade Insomnia Row and Column Uneasiness to go a person * No till now How many MP cells a person * No till now How many MP cells a person * No till now How many MP cells and there So what is the meaning of research Tomorrow morning jogging and the great Indian fashion Any to take from Every Condition The Time Should Not Go Beyond Do Subscribe My 200 More Diseases The Great Khali The Great And Subscribe To Return Back Side In 2019 subscribe to the Page if you liked The Video then subscribe to the number on phone number three subscribe for that Red Cross Grade of Art and C Fusari Swar Madhurya Current Celebrity Indicate the Current President Sachin Pilot To Visit These Disha Set Kar Do Hua Hai This Time Ding Is Condition Hai The Great RC Fuel Karansar Pimple In That Case Return Back Yesterday Morning Evening Present Picture They Can Go In all four directions that should drink WhatsApp call to difficult close to am going in the right direction light to long ribbon to withdrawal difficult to total chinu - They remove all directions on and whoever - Kanpur Column Engine to long and whoever - Kanpur Column Engine to long and whoever - Kanpur Column Engine to long dominance in School according to Nehru place ki nau ka contribution right any to destination for water for a rich 10 l210 latke document verification this case and took a total entries use zameen subscribe this Video plz hai a lip total entries notice must investigation into return I don't verification Page Not And Condition Lights Reduce Liquid To The In This Is Not Go Beyond That Is What Was The Great Britain In His Eyes Were Rivet Upon Him But How Are You That Something Like Tubelight Means You Award All The MTS Right An Application To Interest Map That Samiti Paas Yo Honey Singh Ka Desi Subscribe Now To The Same Thing Subscribe In All Directions From All Directions In [ In All Directions From All Directions In [ In All Directions From All Directions In More Number One Number Will Be Id Subscribe To A Ruk I Think Oo Ajay Devgan RS Initially Were Going Through A Brief And Which Starts and ends well tracking homie entries the 170 sales divine calling deficit in all direction the test left right from bottom and differences and have in this condition which will not going beyond boundaries also and has investment condition to take medicine subject to return and is celebrated in return For K Din I Am Having Been Conditioned To Check Fabric The End Sandwich Is The Two Take Medicine Thapa Inspire Internship I Salute U Ka Birthday Flood Retain And Again Going After That No One In The Times When I Told You To Subscribe To My Channel And Subscribe Directly Half the points were missing Written statement 21 's personality is the 's personality is the 's personality is the thing That we pur A specific Free Ajay Devgan Monday Amazing Behind Grade A Growing And That We Can Have Declared That Seems To Be Equal To One Hate You Can Be Stopped Condition husband should be placid near data is not go back to my on english late and sohan lal dhanda photo analysis on my friend feed a pagli today cutlet time 10 i can get net speed suite 1200 at 100 cent to 8th on net time complexity for this Particular and gautam and share to zidaa time complexity lightweight that zinda map 1000 se fight hai to from this starting celebrate it can go to the best direction performance second day and doing and one for directions for lips distraction at that time i can go to 10 particular direction Distraction and destruction of can not go back to this particular direction right because I am from destruction solid 154 accurate parking only when free direction rate and in all direction subject to abs subscribe tree for directions from going on that andher nagri nm going to amritsar Two Three Particular Direction Light Swift Ministry One To End And Second The Time Complexity Will Be Three Do And Chemicals And Improves Digestion And Click Subscribe Button And Subscribe My Channel Subscribe Button
Unique Paths III
find-the-shortest-superstring
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Array,String,Dynamic Programming,Bit Manipulation,Bitmask
Hard
null
106
hey so welcome back and this is another daily leeco problem so today the problem was called construct binary tree from in order in post-order traversal so let's order in post-order traversal so let's order in post-order traversal so let's go ahead and take a look so the theme of the week has been all tree problems this one was the hardest one so far and I wouldn't be surprised if tomorrow which is Friday will be the toughest one so what we're given here is the in order and post order traversal of a particular binary tree that we want to create so we're not actually given any binary tree just the list of the order of the values of each node that you would expect if you did that particular traversal and so just to review what in order post order and pre-order is pre-order isn't part of and pre-order is pre-order isn't part of and pre-order is pre-order isn't part of this question but it's kind of one of the three traversals that you can do using that first search so pre-order is just pre-order is just pre-order is just a current node then the left node then the right node then in order is just left current then right and then post order is just the left right and then current and so the way I kind of remember these is just okay pre-order of remember these is just okay pre-order of remember these is just okay pre-order the current node is kind of the prefix to the other ones it occurs before them in order okay the current node uh occurs in between them and then post order okay the current node will be the post fix of the left and right all right so that's kind of just a quick review that's usually something that you'd learn in first year uh your first year algorithms class and some fundamental uh oh I didn't mean to I'm already showing you the answer but I'll quickly hide that so yeah let me uh get to it so first we're going to do the recursive solution for this then we're going to look at how we can optimize it'll be another recursive solution but it will go from an N squared algorithm to an oven algorithm and we're just going to be able to accomplish that by having a lookup table this is actually if you go to the solutions here it's kind of the most popular a better python solution is who I got this from so yeah he kind of reviewed what the existing very popular solution was which was the N squared one they found a way to optimize it and it's really simple and for my own practice I want to try to explain it to you so let's go ahead and do this so what we're going to do is for the initial recursive solution we're actually just going to recurse on this particular function we don't even need a helper one and so what we're going to say is okay how do we even accomplish this right like given these two arrays how do we produce a tree so we're going to make use of this tree node class which will actually be used to make the nodes of the tree and so what we can understand is okay how would we begin right and so say if we want to get three where would we get that well that's grabbed from post order because we know since it goes left then right then current the root node is actually going to appear last and so the root node is going to be the last node in the post order array right here okay and so you can actually just pop off at each iteration the root node of that particular subtree that you're looking at and so then what you can do is with that you can then say okay now that I know that if I look at the in order since in order is described as left current then right we know that everything on the left side of that root node is on the left subtree of it's a descendant to the left and then everything on the right side of that index will all be values that are in the right subtree okay and so you actually do that recursively to continue to construct your binary tree so the next thing that we would do is okay like how do we find the next node in the subtree because well we have three values and so with that since we're now looking at this we actually just step over from our post order array to the left which is kind of increment or decrement actually our pointer down this post order array and we see well okay so the 20 is now going to be our next row and anything on the left of our 20 is going to be in the left subtree and anything on the right will be in the right subtree and 15 it goes on the left and 7 on the right but say if there was more nodes you just kind of continue this recursive relationship so if that doesn't quite make sense I honestly find looking at the code itself really helps you better visualize it but it also might take you kind of whiteboarding it yourself and taking yourself through those steps so yeah let's get started so what we'll do is we know that we're going to want to return some particular node okay and that's because well in order to construct this tree and inevitably return our tree node you know we have to be returning some node at the end of it probably the head or the root of our tree at the end and so we're going to be returning a node and to build that node we'll have to say okay our node will be equal to some node constructed by our tree node all right and how do we get this value how do we get the value that we're rejecting to this tree node because well to initialize it you can simply pass in the value of the tree node and these are automatically declared as none by default for your left and right children and so to grab that what we're going to say is okay this node that we're looking at is going to be popped off of our post order array and so initially it'll pop off three so we can just and popping just grabs the last element it's kind of like pushing and popping from a stack so we can just do Post order dot paw and so that will pop it off the stack and now what we want to do is okay what about how do we grow out the index so how do we know say in this case we get three that we can say Okay 3 is here and everything to the left is on the left subtree and everything today is on the right subtree well what we can do is we can just say node index is then equal to our in order dot index and this is just an array method that Returns the index of the position where this value is located in that array and so we know that well if we pass in 3 here it'll return one since three is located at the first index or the index of one in that particular array and so that's how we get the index and so from there if we want to then continue to recursely build our subtree on the left and right we just say okay our no dot left is going to be equal to this recursive call to our method that we're creating and it's required us to pass in the in order and post order arrays and so we just pass those in initially we'll just leave them the same and so we know that whenever we're popping from our post order array it actually is modifying it so this is being modified in place whenever we pop it and so we know that this is getting updated correctly now to update our inorder array we want to do this because we want to recursively only look at say when we're doing our left the in order array we only want to look at 9 now and say if we're at 20 then at this recursive call we only want to look at 15. okay and so to do that we're just going to the python way to do it is like slicing you're just going to kind of partition your array to only include those values within that range and so we want to say okay we just want to look at the node index and if we're looking at the left then we want to say all right um we want to look at everything up to our node index and because in Python this is exclusive we won't be including the current node that we're at so to do this on the right side we do the exact same thing post or is already getting updated in place by that pop method but we want to handle the right so then we say okay we want to take our node index plus one because we want to skip it's actually inclusive on the left side so we don't want to include the current index of the node that we just visited but we want to include everything on the right of it and that's what this colon does here all right and so that's what inevitably is allowing us to recursively build our left and right subtrees but we need a base case here and so what that is we just say okay if there's no in order or there's no post order if those are both empty or if either of them are empty then we just want to return none and this is just used to handle okay as we're slicing an array eventually we're going to hit the bottom where we're hitting our Leaf nodes in the left and right we just want to be able to return none in those case and that allows us to aggregate upwards all right so let's give this a run oh there is just an arrow let's take a peek build tree is not defined ah we need in Python you have to use self because we're referring to recursively to this current method let's try running again 20 is not in the list okay dot index of node.val so we're popping off creating that we're giving its value will that particular node and we want to grab the index of that node's value oh I see yeah so the way that we're doing this because of just the relationship between like in order and building from left and right and since post order goes left then right then current as we're reading backwards we want to be building our right subtree first since we're going to be touching upon these values first okay so otherwise you're just going to be getting that error that we just saw so you really have to just to respect the order in which uh post order arrives you want to be kind of building it right then left okay so it's kind of a depth first search to the right and then to the left let's try submitting that and we got it so let's go ahead and hey if you want to stop here this great solution it's N squared because there's some performance trade-offs that you're some performance trade-offs that you're some performance trade-offs that you're giving by doing this so because this index call is O of n since you're going to have to search through the entire post or inord array so we're going to have to iterate through the entire array so that you can find like four if that's what you're searching for and then return that index okay so that's o of N and then as we're building this tree since you have to go down the height of the tree that would be N squared since with every call you're going to loop back here and then call ovan so it's N squared however we can actually overcome this by using a hash map and you're going to have the same space because well that application stack that you're cursing on takes up space and this hash map is going to be like the same size so what we're going to have is a root lookup or maybe a better word for it is host order lookup and it's going to be a hashmap and what we're going to do is we're going to provide the value as the key and the index as the value and so that's because what we want to be able to do is find the index for a particular value in of one time and so say we have 9 in this case then we're going to have kind of the relationship of 9 colon zero and then three colon 1 and then 15 colon 2. and so using a hash map we can kind of get an 01 lookup time in order to grab the corresponding index for that particular value all right and so otherwise you'd have to search through the entire array like we were doing which is ovin and so it's a v colon I for every index and the corresponding value I also spelled the entire word and then we just enumerate that array okay and so just to show you that printed out right and so that's what it looks like here that kind of hashmat lookup for that poster or in order array okay and so from there what we're going to do is I'll just expand this is we're going to say okay what we need is a function it's called as build tree and we're going to return this function call at the very end and it's going to construct our trade it builds our tree just like we did recursively with the build tree method and so from here what we're going to have is left and then right and so these are actually not going to be the arrays that we're inserting but instead they're going to be the pointers kind of the indices that we're looking at and so although before we were kind of slicing the arrays so that we're only looking at them instead it's much simpler just to have the integer pointers of saying okay we're looking at this range within this particular array and so we do zero and then we look at either length since they're going to be the same length for post order or in order and we do minus one since naturally the bounds are kind of added by one and we want to look at between 0 and the very end of that array which is subtracted by one all right and so like we did when we made our recursive solution we had to check whether either of them were none or like null if the poster array and the in order array were empty that's how we determined if we had a leaf node the way the typical Trend and this is kind of templated whenever you're dealing with a recursive problem you're kind of using the pointers for it you can just simply check okay if left is greater than right which would never really happen right is greater than right then we'll return none and this is how we know when we've reached kind of out of bounds here right there okay and so it might make a little more sense when we kind of show how we're going to recurse on this method but for now I think that makes a little bit of sense just kind of templated way of handling these bounds kind of overstepping When you subtract and add to them all right and so now what we can do is we want to use our post order or sorry this is our in order lookup I hope that didn't confuse you too much and we'll say okay the root or the node index is equal to our inorder lookup of that particular value that we want to look up and so we know that's going to be the node value and so we'll do no dot val and so let's go ahead and create that so our node is going to be the tree node and the way we get the most recent value I believe is just by popping off our post order again and so that's just kind of recursively we're going to be shrinking that post order array and just grabbing the top value as that will always be our root three in this case and then now we can actually get a 01 lookup for that particular oh there we go for that particular index okay and so now what we do is we just want to recurse while building this tree so our no dot left and our node.right and our node.right and our node.right is equal to something and eventually we just return that node okay so let's build our tree so we call ourselves again we don't need self since this is actually a function now we want to pass in the new bounds that we're looking at and so what that's going to be is our left will be let me think is just going to be itself we're not going to modify it and then we'll be the node index and what do we want that to be I believe we want a minus one there and so that's how we kind of shrink as we're looking for it we don't want to be including this current node that we're looking at but we want to keep you know in this case Zero say when we find three here we want to include zero so it's still looking from zero on for this subtree but then we want a minus one so it's really zero to zero so it's only looking at this node for that particular subtree and so that minus one is what excludes that particular three and then from there what we're going to do is say we want to build the tree for our right sub tree and we want to say node index plus one since that is the pointer to the particular root node that we're looking at so three will be one and so we'll be like okay we want to look from index two onwards all the way to our right which will be the length of the array so we'll be looking at this subtree right awesome to go ahead and we'll put right here okay so I think that's good let's go ahead and run that oh can't pop from an empty list post order dot pot Val and I vowel in order and so then we pop from post order I get that particular node ah once again that little trick I think where we have to go right then left yeah so I think this part is a little bit confusing once again so we're wanting to do the depth first search on the right then the left since post order is left right then current so you want to be looking that way right and so that's just because we're going to be popping off from our post order and that's how we say okay we want to look at this node and then the one to the right and so forth and we're just kind of navigating to our left side afterwards all right so yes that's the iterative or the recursive solution both the N squared and then this is the O of n solution since we were able to oh I don't mean to be using all these tools right now um and so we went from like o of n look up for that index to an ov1 solution so yeah I hope it helped and I think this was a great question for me to practice I've honestly pushed this one off before I saw it was too scared to try it so I hope it went great for you and uh yeah have a great day thanks
Construct Binary Tree from Inorder and Postorder Traversal
construct-binary-tree-from-inorder-and-postorder-traversal
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** inorder = \[-1\], postorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= inorder.length <= 3000` * `postorder.length == inorder.length` * `-3000 <= inorder[i], postorder[i] <= 3000` * `inorder` and `postorder` consist of **unique** values. * Each value of `postorder` also appears in `inorder`. * `inorder` is **guaranteed** to be the inorder traversal of the tree. * `postorder` is **guaranteed** to be the postorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
105
1
uh hello everyone welcome back to my channel here is vanamsen and today we are going to Taco an interesting problem from lit code the Tucson problem it's rated as an easy problem but understanding the optimal solution might be quite challenging so let's dive into it the problem statement is as follow yeah I will mark it the problem is first follow given an array of integer nums and integer Target we need to return an indices of two numbers in the array that add up to Target it's granted that there will be only one solution for each input and we can't use the same element twice so let's quickly look at examples so for example we have uh Target nine and inputs RI consisting of 2 7 11 15 and because yeah nums 0 plus nums 1 equals nine so it's two plus seven uh the output should return 0 1 so those both indices and we have also another example with Target 6 and RI three to four and we need to return indices one and two so two plus four equals six very easy but we have some trick I mean additional we are also asked to come up with an algorithm that runs in less than o and square time complexity so Brute Force approach won't work here so yeah let's think of more efficient Solutions so probably you've was thinking about Brute Force so easy one uh two loops uh yeah iterating around the ri and if I not equal J so indices are different and they sum to Target outputs both indices so yeah it's Bruce first approach but we are asked to come up with something more clever so you can pause for a second and think of it yes we will try to use hashmaps so yeah we'll solve this problem in C plus and here is the initial function that let's code give us and yes let's try to uh solve a bit so first we need to declare uh yeah we need to create an unordered map to store a previously seen numbers and their indices so we know what we have seen and because we know that we have only one solution so we know that one number is here and another will be in future and both will Target yeah number so iterate through the input array easy one and then calculate the complement so Target means current number and then we will find the current number so complement is Target minus uh nums on I so current position if the complement exists in the map so yeah we find complement and if we find a complement we can return both numbers because we know that we stored there indices and also then we are returning the last current uh yeah index so it will provide us with solution and at current number and its index to the map otherwise so in case complement not simply Target and now Maps so we're adding and if no solution Farm we just return and empty Vector so yeah return empty vector and we can now check yeah so we have here test cases as you can see and yep let's run it hopefully it will right okay so test cases were fast and let's submit the solution and see if it's go through unseen test cases and yes we did it so yeah access the solution uh and it bits 58 of uh other codes and also memory bits 35 so yeah quite good and there you have it uh there this is how you solve that to solve to some problem in C plus with time complexity of uh o n which is better than o n square and yeah remember the efficient coding is about using the right data structures and algorithm for the task at hand and if you found this video helpful be sure to hit the like button and subscribe for more coding tutorials uh Happy coding everyone yeah and 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
1,727
Hello friends welcome to my channel here I solve L Cod problems and prepare to the Cod interview today's problem number is 1727 larger submatrix with rearrangements you are given a binary Matrix of size M by n and you are allowed to rearrange The Columns of the Matrix in any order return the area of the largest submatrix within Matrix where every element of submatrix is one after reordering the columns optimally let's solve it what we can do we can calculate number of ones goes consecutive in each columns and based on these numbers calculate the area for each column let's check the example one and uh make step by step so what we can do we will go row by row and calculate number of consecutive ones for each column so for first row we have 0 and one because in first two columns we have zeros so we have one only in the last column and uh after we calculate all cons all ones we can get the area and update the result with the maximum area we can get in each row so in first row we can get one submatrix and the area is only one in second row we have three ones and so the consecutive ones have values one and two because third col column has two consecutive ones and when we have with three values so one and two we can get the submatrix with high of one and uh with uh three so the area is three for third column we have consecutive values two because it's second one consecutive zero and three so to get um maximum area we need to rearrange columns and the best way to do it is to sort so we sorted 1 2 3 or 0 to 3 so we have uh we can have submatrix with height two and uh with Al two so the area is four and uh the maximum result is four so we can return it let's do it in the code so we need some result variable with zero by default and return it also we need some variables to keep uh number of consecutive ones let's call it Max ones and it will be a list of zeros with SI size of length Matrix of zero and let's go row by row so it's Loop for Row in matx after it let's go by column and update Max ones so we need we will need indexes so use enumerate function numerator for and let's update Max one's variable Max one of current index it will be zero if current value is z equal to zero otherwise it will be previous value + value + value + one so in the example one you will see in the third row in second column we will update Max on with zeros because we have current value is zero after previous value is one so we get Max ones and now we need to sort it but else we need to keep original values for the next row so we need some new variable sorted once and save result of function sorted of Max ones and now let's go through values of sorted ones and calculate maximum area for each item so for I and the current count let's be H in enumerate sorted once and update result so result equals to maximum of current result and the area of current submatrix will be with height H and uh with equals to length of current draw minus index I so in the example one for instance uh for instance for colum two um it has length of raow is three and the index is one so the possible rectangle V will be 3 - V will be 3 - V will be 3 - 1 it's two so looks correct and that's it let's check test something wrong H yes it's we need to add some bre bra check again test pass let's submit it works and uh pretty efficient that's it for today thanks for watching see you tomorrow bye
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
139
welcome back to Uncle jest today's question is leak code 139 word break so you're given a string s and a dictionary of strings return true if s can be segmented into a space separated sequence of one or more dictionary words note that the same word in the dictionary may be reused multiple times in the segmentation So within our first example we have the string lead code and we have a dictionary containing the words delete and code and can we create the code from these segmented words and the answer of course is true and then if we look at example three we have cats and dogs we have the dictionary containing cats dog Sand and Cat can we create this string using a sequence of words from the word dictionary well no we can't right because if we use cats we get up to here then we have and right and is here but then we don't have OG it's the same if we use the other sequence so if we start off with cat we'd have sand and again we'd be left with OG so that's not possible so we return false so there are a number of ways we can solve this we can use DP we can use recursion and memorization or we can use BFS and today we're going to be looking at the breakfast search solution so how are we going to do this well as a high level overview we're going to Loop through this string we're going to start off at index of zero and we're going to check all possible strings to see if we can find a word that is equal to one of the words within the dictionary so we start with L we look to see if that's in the dictionary it's not Demi Loop across it's early in the dictionary no until we get delete once we found lead we add the ending index into our queue and then we shift off the queue the next position and we repeat the process so we check all these positions until we find the word within the dictionary and then in order to determine whether we found an entire sequence of words we are going to compare string dot length so let's put string.length which is equal to eight if string.length which is equal to eight if string.length which is equal to eight if this is equal to the last index within our search then we can return true so for this prefer solution we're going to have a visited set which is going to contain the indices that we have visited we are going to have a set dictionary so we're going to store the dictionaries from this word in a set and the reason we do this is because the set has o and lookup and we are going to constantly be referring to the dictionary so by storing it in set we can improve the time complexity here and like any breakfast search we are going to have a Q so this Q is initialized with the first index and now we can carry out the reference search so if we shift off of Q the position of zero in order to check the substring within this string right here we need to use S dot slice right s dot slice and in order to use S dot slice we need to remember that the second parameter passed into slice is non-inclusive so if we get a substring non-inclusive so if we get a substring non-inclusive so if we get a substring by passing in 0 and 1 within this string here the letter we're going to get from this is l so if we go from 0 to 1 we get l we check if L is in the set it's not so we check the Le that's not in the set we check for l e t now this using string dot slice is going from 0 to 4. we have found this within the set so now we'd make a termination check and the termination check is to see whether we've reached the end of this string so is this index equal to string dot length it's not so all we need to do is pass this Index right here into q and carry on searching to see if we find another word within this string within set so we look at lead C leadsio vco D and delete code none I found within the set so we can now add this value into visited and repeat the process so we shift off Q4 and we start here so we look to see whether C is in set nope Co nope Cod this is within set and the indices go from four to eight to get this and remember we're saying four to eight because string dot slice B is not inclusive this is when set so we can compare the index of the last value of this substring with the length of the overall string and if they're equal we can return true and that's the case here so let's have a look how this approach would play out for cats and dog so we add zero into the queue the index of the first character within this string we shift off of Q value of zero and then we start the loop to check whether the substring is found within the set so we don't find anything until we reach cat and that would be zero to three so we can add the index of three within here then we search further so we search cats zero to four that is found within the set so we can add four in here and then we search the rest of the string see if we can find cats and none of these are found within set now zero has been seen it can be added to visited and seen as Q still has values in we can shift off look at index of three so if we start at s We compare so is s found within the set now is sa no is s-a-n no is s-a-n-d yes we have no is s-a-n no is s-a-n-d yes we have no is s-a-n no is s-a-n-d yes we have sand so we can add the end index which is going to be 7 here we can add seven within our queue We Carry On so is Sando in there or is sand dog in there nope so that is three has been seen it can be added to visited then we can look at four so we shift the value of 4 off of Q start at index of four the only value from here onwards is and that finishes at seven as well so if we add seven again we have duplicates here four has been seen four can be ads visited and then we can look at seven so we shift off of Q we start at seven can we find o in the set no can we find OG in the set no we've reached the length of the string so this doesn't return us with any results so we can add seven within the visited now we shift off of Q the value of seven again in order to stop duplicate values from being checked we can add a query at the top of the BFS while loop to see whether visited has the current value we've just shifted off if it does then we can just stop this process and now Q is empty we've exited the BFS and we can return false so time complexity for this one BFS by nature is O of n but since we've created multiple Loops within this where We're looping through the entirety of this string and then we're checking every single substring this increases the time complexity to o n cubed and then space is going to be o of n where n is the value of indices that we store within the queue so the first thing we need to do in code this out is create the visited set we also need a set that contains the values of the dictionary it's a word addict and we also need to initialize the queue for our BFS then we can start the BFS so while Q dot length we shift off of Q to get the current value so current is equal Q dot shift then in order to avoid duplicates we check visited to see if it has the current value if it does we don't carry this out otherwise we'll Loop through from current plus one I is less than or equal to string.length I is less than or equal to string.length I is less than or equal to string.length because we want to go up to and including the last value of the string and now we have to create those substrings and the way we do that is we're going to slice so we need to check in set if set has string dot slice we're going to slice from the current value to I we need to compare it to s dot length so if I is equal to histor length we can return true because we've reached the end of the string otherwise we push into Q that index at the end of this we can add current intervisited and lastly once this Loop carries out and in the case of cats and dogs where we don't find a solution the queue is going to be emptied we're going to exit this while loop and we can return false let's give this a run
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
7
hello friends this is a good hacker here I'm going to show you how to solve difficult coding problem reverse integer the problem description is that we need to reverse digits of an engine for example if an input number is 123 we need to return 321 if the impure lumber ism - work one two three we need to ism - work one two three we need to ism - work one two three we need to return - three two one return - three two one return - three two one and the our function should also return zero will not reverse integer overflows so here I'm going to show the mechanism to do that reversing so let's have an example here one two three so we look at this number we can see it's actually composed of all some single digits so it's composed of a separate part that is a hundred digits tens digits and ones digits so it's actually composed by 100 multiplied by the hundred digits number that's 1 x + 10 x 2 + 1 x 3 and it's that's 1 x + 10 x 2 + 1 x 3 and it's that's 1 x + 10 x 2 + 1 x 3 and it's reversed number 3 - 1 is equal to 100 x reversed number 3 - 1 is equal to 100 x reversed number 3 - 1 is equal to 100 x 3 and the 10 x 2 + 1 x 1 so the first 3 and the 10 x 2 + 1 x 1 so the first 3 and the 10 x 2 + 1 x 1 so the first digit becomes a nasty j and the second ej remains the same at a single precision the nasty j becomes the first digit and a reverse number so our mechanism to do this reverse is that we can keep dividing this original number by 10 and the way keep track of the remainders and the way Adderley remainder to the reverse of value reverse manual initiate ways are 0 and the way keep added a remainder to the reverse value so I would these the three columns here number remainder and reversed so lumber at the beginning is a originated improve one two three remainder and the reverse both initiated with a zero value and we keep divided or Indian value by ten so 1 2 3 divided by 10 equals to tau 1 2 3 more to bite him went get straight and we added the remainder to the previous reversed value so previous reverse value here is 0 and away at 3 and we keep divides our number by 10 so job divided by 10 we get 1 and a child module by 10 we get 2 and we add a new we meander through the very worst so previous reverse number just one digit but now here we need to make it to two digits so pre where's reverse value multiplied by 10 and add the new remainder and one keep divided by 10 equals to zero and one module by 10 equals to 1 and previous a reverse becomes three digits so reverse value or multiply by 10 and we add our new remainder so one the number equal rich to the real 0 we finish our reverse process and then we should pay attention here so there's an overflow like Inc occurs so in Java and other programming languages integer value as 3 32 beads so that means it's range funk to - 31 - one two - two - 31 so it's two - - 31 - one two - two - 31 so it's two - - 31 - one two - two - 31 so it's two - 31 - one is a greatest number an integer 31 - one is a greatest number an integer 31 - one is a greatest number an integer value - two - sorry what is a minimum value - two - sorry what is a minimum value - two - sorry what is a minimum value against your value so we should notice that there's our son studied difference between the politic range and the negative range so negative 20 actually we'll wait to the reverse to survive it should be - 2/3 - 1 but a - survive it should be - 2/3 - 1 but a - survive it should be - 2/3 - 1 but a - 231 is a greater than the largest value in the positive range so we will get overflows so which the pay attention to this case and I'll handle that case okay let's go back to the problem and I will demonstrate coding in Java so first I will have a reverse value so that is our final result we want to return for this father so reverse just a start found a zero and we see here we need to have a process to keep divides our original number by 10 so keep divided original value by 10 and on cue it raised to zero and we need to when we do those duration we need to update our reversed value we need to multiply keep updated our previous reverse value class its remainder so the remainder is equal to X module by 10 so this is a concept to do the reverse and the way you should not forget about the overflow cases so for our four cases so how can we handle that a work flow cases so every time we keep updating the reverse so if it's not overflow so our newest reversed should when it divided by 10 should get the previous reversed value so we need to have a temporary variable to store the new easter reverse the value and we were used on temporary 10 who are able to check whether is overflow so if the temp value divided by 10 equals true the free werster reverse value if it is not a eCos tulip reverse while we need to just a return label so get over false if it's just a passage overflow check and the number does not overflow we should update our reverse value through the natives reverse where you okay we should finish our code and before we submit the code let's have a quick share with you some our original input to work through this process so let's assume X is equal to 1 2 3 so X 6 equals 2 1 2 3 so the time of first is adjusted remainder that's a 3 and a 3 divided by 10 should be 0 it equals to the 0 so no path basic check and the way after the reverse 2 to the 3 and X keep divided by 10k job so next time our reverse keep can update and add as a newest remainder that's a 2 &amp; 2 as a newest remainder that's a 2 &amp; 2 as a newest remainder that's a 2 &amp; 2 divided by 10 equals to the through the previous of reverse so that 10 that's a 32 divided by 10 that's a 3 so a true the traversal so we were keep I update our reverse so we get her 32 for the newest of the world and X is equal to the 1 and the next time we keep our add ticket to the reverse so that's 3 2 1 sweet 1/10 and reverse so that's 3 2 1 sweet 1/10 and reverse so that's 3 2 1 sweet 1/10 and the Year code through the previous reverse that's asserted truth so pass a check and reverse get an update to the story 2 1 and the eggs keep divided by 10k to 0 so it reached through the zero way jump out of this while loop and the way to eternal reverse okay so we should get a correct answer so let's create the submit button judging okay the solution get accepted that means our solution is a correct okay so this is a so this is the process to solve this problem so we should pay attention to the overflow and do the reverse so thank you for watching this video so I hope you learn the solution to solve this problem and thank you very much for watching this video and if you have any suggestions or comments just leave the comments under this video I will keep improved off we tortured her they say it's a good taker thank you for watching bye
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
266
testing boys colleagues uh fellow monkey lie part-time gardeners uh fellow monkey lie part-time gardeners uh fellow monkey lie part-time gardeners and computer touchers this is 266 palindrome permutation doing this in typescript i feel like uh i mean it's javascript but uh with the type the static type checking and stuff you guys are going to see the types i'm using so it's actually easier to follow hog given a string determine if a permutation of the string could form a palindrome so here we're given the input code and we see that this is false we're given a b and they return true well you look in your head and you're like aab it's not the same forward as it is backwards aab backwards is baa but there is a permutation of a b which means order the order is different so a b a which is actually going to be a palindrome so that's kind of the uh the trick here right so with a palindrome right you can traditionally do like the whole uh you know reversal algorithm you so like let uh start is equal to zero and is equal to a length of the string minus one then you can check as you're going iterating towards the center right if those characters are ever not the same right then you don't have a palindrome but you can't do this way right so how do you do this so on first thought one might think well i know how to check if a string is a palindrome why not generate all possible permutations of the string and just check if it's a palindrome on that well that's going to require a lot of space especially as your uh input size increases and uh it's just not a fast way to do it also it's very difficult way to generate all the palindromes generate all permutations you don't have to right so when you have a question like this it's easier to just kind of uh if you take the question too literally right it's a little bit tougher to figure out the answer if you just look at the input and try to figure out what's the pattern here right then you can kind of start to see and i have some stuff written here we're just going to work through it so we're going to try and figure out you know the base properties that kind of make something a palindrome right because we have to look at all permutations so there must be some structural indicators right for a string that you can kind of instantly tell whether or not it could be rearranged to be a palindrome not that its current form is or is not a palindrome right so how do we do that so what information do we have about a string well we only have the string write the letters in the string and you know how many times they are shown so working with that information what can we kind of deduce right um so here we have aaa which is just five or six a's right and so i've written here on the side right i don't know why i have a equals five here but we can see that we have aaa which is five a's right and this is the palindrome forward as it is backwards and if you rearrange it that's why either way doesn't matter any way you put these a's in right it's going to be a palindrome i believe you have a b now this is a palindrome right strictly speaking this formation of this string is not a palindrome but uh it can be rearranged to make a palindrome what does that pound or look like you have a you would have b or one version of it could look like this right bab because you have three a's and two b's so what are the properties here so we notice that in this first problem right if a is equal to five we have five a's right or if a is equal to six we have six weight a's right either way it's still a palindrome right and we see here right that a is equal we have three occurrences of a and two occurrences of b so we have a has so we have an odd occurrence of a right and an even occurrence of b well we know right that it doesn't really matter this is 2 4 6 8 10 42 368 180 right what all that really matters right is that the other no the number is even right so we know that um if a number is even it doesn't really matter how large a number is we can always split it in half right one half of the string will go on the left half and one half of the string will go on the right half and it'll be a palindrome right but we notice interestingly enough right if we go back to just b being two right so we have an even current here and we can have an infinite number of even occurrences right so we can have c equals four and d equals six right and why is that right because if you take a look right if the number is always even you can always just split it in half and place one number on the right hand side and so we don't need one letter on the left and right hand side so we don't even have to actually uh write those letters to occurrences out we can just say i'll just explain i'll just show it here right so before we had bab right well we're just gonna add a on both sides one on one c on both sides one d on both sides right one e on both sides and so it kind of goes infinitely right so we know that determining on whether or not a string is a palindrome doesn't really have anything to do with the number of even occurrences right because even occurrences will always make palindrome but in this uh following example we can see that right we have aa b c d right and this is not a palindrome but you could easily split all these occurrences up into one half on the left side one half on the right side right and it would be a palindrome and so for the second example right if we return we said a equals three and b equals two right so what's interesting here is that b has an even number of occurrences right which means that like we said one letter's gonna go on the left half one letter is gonna go on the right half right but a has an odd number of occurrences and those of you who are more comfortable with recurrence relations will know that like an odd number is just an even number plus one right and you don't even have to know recurrence relations to know that right so what does that mean it means that if we have an odd number of uh occurrences like three or five or nine or seven right you can just subtract one from it right you'll get an even number so we have two here right so you can just place 2 divided by 2 you can place one on each side one on the left hat one on the left side one on the right side and you can place the final remaining odd number in the center right but we know for a fact right with this pattern that you cannot have two letters with odd occurrences right so if we add c equals three let's do the same thing you know that we can make c we can make a proper palindrome by just subtracting one from c so we'll get two we'll place one c on one side and one c on the other side but then we try to place a c in the middle and it's no longer a palindrome right there's just no way to make this a palindrome if we already have one odd occurrence and so we're going to start to notice right is that these are examples for not palindromes we know that when we have we can only have now we notice right that we can only have one letter that has an odd number of occurrences and an infinite number of other letters that have even occurrences right because even a current is always split evenly on both sides but an odd occurrence can only split uh one half on the other side and then the one remaining level that makes it odd will go in the center so two letters can't go in the center right unless they're the same so that's why we don't have to worry about even numbers i mean even occurrences so here we have three even occurrences so i mean three odd occurrences because one is an odd number right there's no way to rearrange abc to make this a palindrome and so we have uh the same thing here we have a little bit of a different example before or except we added c here so we have aaa b and c so three is an odd number of occurrences so we can try and make this a pounder we'll place a on the first half a on the other half and then we'll place a in the center so then we have an even number of currencies for b so we'll place uh b on the first half and b on the other half perfect now we have c remaining well where do we place c because we can't play c in the middle right because a is already in the middle so this can't form a palindrome right but cobb is not a palindrome code suffers from the same thing which is our first example all of its letters have odd occurrences therefore no letter can share the middle only one letter can go in the middle right then we have carrack which actually is a palindrome why because all of its letters right have even occurrences except for one so we know that the one deciding factor of whether or not a string can be rearranged from a palindrome structurally is whether or not it doesn't infringe on the one odd occurrence's rule so once we know that a string is string could be a palindrome if it only has one letter within odd occurrences with an odd occurrence right so now we know that to be true right and so we can kind of template this greedy solution so we have this how do we uh check if a string only has one letter without occurrences right well we could use a data structure like a dictionary which is just going to store a mapping of letters to recurrences and then from there we could just iterate over our dictionaries keys right and then once we iterate over our dictionaries keys what we'll do is we'll calculate right so count how many uh letters have odd occurrences right and if any of our letters if we have one out of currents that's great but if we ever go over one we know that it's impossible we couldn't possibly have a palindrome here right so iterate over our dictionary keys right if letter is odd occurrence right then we'll increment odd occurrences right which is just some variable which is going to store how many out of currencies we've found so far right we'll have another if that says if odd occurrences greater than one then we're just going to return false right and if we make it through this whole thing and we never return false we'll return true because this is a this palindrome can permute so we can just do that here so i'm just going to delete all this stuff up here and then we're just going to say let all strings oh not all strings let's just call it let mapping just to be really general and this is going to be mapped as a string to a number right there's going to create a new map here and then we're going to iterate over these strings we're going to say for let letter of s right and then we're going to say uh if uh letter is in mapping what are we going to do well we're just going to increment the occurrences right so mapping sub letter is going to be equal to mappings of letter plus one else right we haven't seen this letter in the mapping yet right so we should add it and this is the first time we're seeing it so it must its occurrence must be one and so here we're going to declare our hat so right now we have this dictionary of letters to occurrences which is great now we need to count how many out of currencies we're going to have in our dictionary when we're iterating through right so we're going to create odd occurrences which is going to be a number and we're going to set it to 0. here we're going to actually iterate over our dictionaries keys we're just going to say let key of mapping and then oops i messed up there and then now we just have to do what we said we already wrote the scaffolding and this is why it's good to write scaffolding because it kind of helps you just make sure your logical propositions make sense and so we're going to say if letter is odd a current so how do we do that so we have to look up the occurrences for our key here and so this might make more sense if i change this out and i say let letter of mapping so for our letter right how do we check if it's an out of current so mapping subletter is going to give us our occurrence so now we have the number that we're working with how do we check if it's odd well typically you do mod 2 does not equal 0. right and so that's going to check if uh our um if our occurrences if our current number is out here because if we did mod 2 sub 0 i mean mod 2 and we got 0 that would mean that um that our occurrence was even right because two went into this number and gave us no remainder but if it's not zero that means uh it must be odd right because there's only uh the state right for numbers there is either odd or even there's no in between so we're just going to increment odd occurrences other currencies plus equal 1. now if odd occurrences right is ever greater than 1 that's no bueno right because we said if a string right if it's occurrences in a string uh for a palindrome to exist we can only have one letter right that can hold the middle spot so if our middle letter is going to be c and there's seven occurrences of c three occurrences of c we're going left hand side three occurrences of c will go on the right hand side and since we have seven occurrences the final occurrence of c will go in the center if we have an odd number of uh letters in the string only one letter can go in the center so only one letter can have odd occurrences right so we can just return false there and so if we made it through this whole thing right we made this whole thing without um returning false then boom we can just return true for free right and so we should be able to run this and they should be good we'll see i might have messed up cannot find name mapping i put one too many p's here unfortunately and so let's try our test case again oh man i said let letter of mapping that's my bound so let's say let letter in mapping yikes man boom and so our test case works and then we can just submit the whole thing and then boom so we're good there right so how what is the time and what is the space complexity of the so the time complexity of this right has to do with uh the number of characters in the string so um you could say that the time complexity is going to be uh linear time right because where um n is the number of characters in the strings or iterating to the strings to create a mapping of letter to occurrences then we iterate through our dictionary right to calculate the odd occurrences and our space here the problem solution says constant time i'm going to be honest i don't really understand why it's constant time but the intuition there apparently is that our dictionary is going to be uh only store unique and distinct elements right and so in a string uh our since our dictionary is going to be distinct a string right only has so many characters right so uh our string uh string possibilities right are going to be bounded therefore our dictionary will be bounded and so i think that's why it's constant time but i think that might also have to do with how this problem is defined uh with the constraints but that is a solution to 266 palindrome permutation
Palindrome Permutation
palindrome-permutation
Given a string `s`, return `true` _if a permutation of the string could form a_ _**palindrome**_ _and_ `false` _otherwise_. **Example 1:** **Input:** s = "code " **Output:** false **Example 2:** **Input:** s = "aab " **Output:** true **Example 3:** **Input:** s = "carerac " **Output:** true **Constraints:** * `1 <= s.length <= 5000` * `s` consists of only lowercase English letters.
Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Hash Table,String,Bit Manipulation
Easy
5,242,267,409
322
hello everyone welcome to day 21st of march street code challenge and i hope all of you are having a great time my name is santiago deja i'm working as technical architect sd4 at adobe and here i present day 694 of daily liquid problem the question that we have in today is coin change here in this question we are given various denominations of coins along with this we are also told an amount that represents the total amount of money that we have what we need to do we need to identify the minimum number of coins that are needed to make up that amount if it is not possible then we have to return minus 1 in those cases so let's walk through an example and get a good hold of the concept let's assume we have coins of denominations 1 2 and 5 and in order to achieve a total amount of 11 one way is to use 11 coins of denomination one other way is to use two coins of denomination five and one coin of denomination one that also makes up till eleven there are plenty of more permutations that are that may be possible and uh the minimum one will come out to be 3 which one this one 5 plus 1 gives you 11 and here you are utilizing only three coins so without further ado let's quickly walk through the presentation and i'll be walking you through various test cases as well as the algorithm to go about it by the bpt so let's quickly hop on to it lead code 302 coin change it's a medium level question on lead code and i also feel the same the concept that we will use to solve this question would be dynamic programming i know dynamic regarding the toughest of all the concepts of dsa and for this since placement season is around the corner i have created a dynamic programming revision sheet it includes approximately 50 questions and use this sheet before your interviews to revise various concepts of dynamic programming i've attached its link in the description below so do check that out without further ado let's get back to the problem also in case if you have any doubt understanding this question or if you want to ask anything from me in general with respect to placements jobs adobe anything please feel free to ping me on the telegram group or the discord server of coding decoded the link to is stated below let's assume we have denominations of coins one two and five and let's start with the base case where the total amount right now that we have is zero and the total coins needed for achieving sum of zero is again zero so this represents a total amount and this represents whatever in this in the bracket represents the total coins needed for achieving that amount and let's get started let's assume in the first iteration i am using denomination one so the total amount gets updated to one and the total coin count also gets updated to one similarly in the second go i am using a coin of denomination two so the total amount gets updated to two and the total coin count gets updated to one and let's use five this time and the total amount gets updated to five and the total coin count gets updated to one and let's spread the tree further so let's start from this now let's create c more branches and in the first go we will use denomination 1 second go we'll use 2 and third we'll use 5 so what do we get the total sum of 2 and the total coins needed happens to be 2. let's proceed ahead next we will get the total sum of 3 total coins needed is 2. next we will get 6 the total coins needed is 2 great so far so good let's proceed ahead and let's create branches for this portion so one will be using one other one will be using two and third one will be using five so one plus two gives you three so the total amount gets updated to two and the number of points use happens to be two let's proceed ahead two plus two gives you four the total coins used is two plus five gives you seven the total points use gets updated to two and let's create more branches for this particular branch which is five and here again we will create three more sub branches so one for one other one for two and the third one for five so one plus five gives you six the total coin count is two plus five gives you seven the total coin count is two and the next one is five plus 5 which is 10 the total coin count is 2. and now what you can do you can further create more branches so for each node you will create three more branches and continue doing the processing what you will see that at 10 when you are creating more branches so one would be for one other one would be for two and the third one would be for five so ten plus one gives you 11 and the total coin count will be updated to 3 which all of you will agree with me in the question the total amount that was given to us was 11. therefore what we are gonna do we look out for all those instances where the total amount of 11 is getting generated and we will be selecting that one which has the minimum number of coin associated present in the brackets so here in this case it would turn out to be 3 and 3 becomes the answer so this is a brute force way of solving this question where from each branch you are creating three more branches and further increasing the breadth of the tree where can dynamic programming come into picture let's shoot for it but this forms the ground foundation for dynamic programming if you have understood this then you will understand data as well how let's move to it here i've created a dp array of size equal to amount plus one y amount plus one because array starts from an index zero therefore here in this case the amount was eleven i have created a dpr of size 12 and when i say what does dp at the is index signify its represents the minimum number of coins needed to achieve the total amount of i for example when i say dp of i dp of ir dp of 5 what does it represents the minimum number of coins needed to achieve total of five amount as five so the this represents the minimum coins needed let me just write minimum coins needed and let's try and understand this equation now so what does it represent it says that dp for this particular amount is equal to math dot minimum and the first part is dp of amount minus 1 plus 1 so what how can i analyze this equation it means that i since i have three denominations 1 2 and 5 so i go to the amount minus 1 position which here in this case is 4 and i add i extract that value i add 1 to it so whatever value is stored over here i plus 1 to it and this would be one possibility for answer so the minimum number of coins needed for amount minus 1 plus 1 is one possibility of answer what is the other possibility of answer would be since i have denomination 2 with me i go 2 steps back i reach dp of 3 and i check its value i add 1 to it so this will give me the second possibility of answer in order to reach the total sum of five let's proceed ahead and the third part is amount minus five plus one y minus y because the other denomination is of five so i go back to the 0th index i check its value and i add 1 to it because i can use the coin with 5 denomination in order to reach the total sum of 5 from that position so out of these three possibilities whatever gives me the minimum month that becomes my final value for this particular amount which is dp of amount let's start the iteration so let's iterate from i equals to 1 and we'll go up till i equals to 11 so what is the first possibility of answer we'll go back to amount minus 1 gives you 0 so we'll go to this position and add 1 to it so 0 plus 1 gives you one so one possibility of answer is one let's look out for this equation now amount minus two so one minus two gives you minus one it is negative so let's skip it similarly amount minus five one minus five gives you minus four so let's skip it so the answer here becomes one so let's update it to one let's proceed ahead next we have two i equals to two so let's go one step backwards so what do we get one from it so one plus one gives you two so one possibility of answer is two let's shoot for the second possibility of answer let's go two steps back so it gets go two steps back we get zero plus 1 gives you 1 so out of 1 and 2 which one is the minimum one so this gets updated to one and i have skipped this because this will go in negative for i equals to two so let's proceed ahead next we see is three so let's go a step back uh what do we see one so one plus one gives you two so one possibility of answer is two let's go two steps back now so what do we have one plus one gives you again two so the other possibility is two and for the third possibility three minus five gives you minus two so it's negative uh we will not consider it out of two comma two which one is a minimum one two is a minimum one so this gets updated to two let's proceed ahead next we have four i equals to four so let's go one step back what do we see two plus one gives you three so one possibility of answer is three let's shoot for the other possibility let's go two steps back we have one so one plus one gives you two so the other possibility is two and uh let's shoot for the third one amount minus five four minus five gives you minus one which is negative so i'll skip it out of three and two which one is a lower one two is a lower one so the answer here gets updated to 2 which is in sync with our expectation because you will be using two coins of denomination 2 in order to reach a total sum of 5 4 let's proceed ahead and let me just change the color of pen for better understanding and now we have i equals to five and let's go one step back at four we have two plus one gives you three so one possibility is three let's go two steps back we have two plus two one again gives you three so the possibility is three and let's go uh five steps back now because five minus five is zero so let's go five steps back and at zero the value is zero so zero plus one gives you one and out of three one which one is the least so this gets updated to one which is in sync with our expectation because for achieving a total sum of five we only need one coin of denomination five let's proceed ahead next we have i equals six so let's go one step back we see one so one plus one gives you two so one possibility of answer is two let's go two steps back at four what do we see two so two plus one gives you three so the possibility is this one and let's do it for the third possibility let's go five steps back at one we have the value as one so one plus one gives you two so the third possibility is again two so out of two three and two which one is the least one two is the least one the answer becomes two which is in sync with our expectation because either you will be using one or five comma one therefore here you can see there were two possibilities with total coin count as two one represent representing one comma five and another representing 5 comma 1 let's proceed ahead let me just say in the color of n for better understanding and now we have i equals to 7 so let's go one step back here we have value as 2 so 2 plus 1 gives you 3 let's proceed ahead let's go two sets back we have at five value as one so one plus one gives you two so this becomes two and let's go five steps back at two the value is one so one plus one again gives you two so the least out of these 3 is 2 so the answer becomes 2 and which is in sigma that expectation either you are using 2 comma 5 or 5 comma 2 as coins for achieving total sum of 7. let's proceed ahead next we have i equals to eight let's go one step back so two plus one gives you three let's go two steps back at six we have the value as two so two plus one again gives you three let's go five steps back at three the value is two so two plus one again gives you three so out of all these three possibilities the least one is three so answer here becomes three let's proceed ahead we have i equals to nine and let's go one step back so a three plus one gives me four one possibility let's go two steps back seven plus at seven the value is two so two plus one gives you three other possibility is this and let's go five steps back and here the value is two so 2 plus 1 gives you 3 so the answer here becomes 3 because 3 is the least one out of 4 3 and 3. so this gets updated to 3. let's proceed ahead and here we have i equals to a 10 and let's go one step back so one possibility is three plus one which is four let's go two steps back three plus one again gives you four and let's go five steps back so five plus at five the value is one so one plus one gives you two so out of four two the least one is two so the answer becomes two which is in sync with our expectation because at ten you are using two coins of denomination five let's do it for the last case and at i equals to 11 let's go one step back the first possibility is two plus one get which gives you three the other possibility is you go two steps back three plus one gives you four and the last one is you give go five steps back which is i equals to six at six the value is so two plus one again gives you three sort of four three c which one is the least one three is the least one and the answer becomes three with this i have i iterated over the entire matrix finally whatever stays in the last becomes your answer and here in this case it's 3 which is in sync with our expectation from the previous analysis that we did now it's time to shoot for the coding section here i've created a dp array of size equal to amount plus one i have filled in the dp array with integer dot max values and as a default case i have updated my dp array at the zeroth index to zero what do i start an iteration for the amount starting from i equals to one going up till the amount value and with each iteration i'm incrementing the i pointer here i've created an inner loop so uh whatever set of coins do i that i have i check if my i minus that coin value so el actually represents the coin denomination so let's update it like this i minus coin is equal to greater than 0 if that is the case and dp of i minus coin is not equal to integer dot max value in that case what should i do i should consider dp or dp of i equals to dp of minimum of mass dot minimum of dp of 5 comma dp of i minus coin plus one and once we are out of this loop what do i check if my dp at the last index happens to be equal to max dot minimum then that means it's not possible to achieve that total target using the denominations that we have and we need to turn minus 1 in those cases otherwise we return our dp at that particular amount the time complexity of this approach is equal to order of amount into the denomination the total number of coins that we have and the space complexity is equal to the order of amount that we are looking for so let's shoot for it accepted 50 times faster which is pretty good and 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 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
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
502
hello guys welcome to deep codes and in today's video we will discuss split code question 502 IPO so this question is a pretty much complex to understand at first such but I will make sure that I will divide this question in small bits so that it's easy for you to understand so this is some story that you are given here I will explain you in simple terms same here you are given one profit serum and each for each profits of Phi there is some capital of I related to it now initially you had W Capital initially you had W amount of capital and at Max you can do K uh projects right you can do K projects correct so and at the end we need to return maximum uh Capital at the end right and it will be auditor always been integer okay now there is one constraint so the constraint says that in order to take a project I you must have the capital of Phi okay now uh okay but before that let me tell you that what you need to maximize this equation tells to find to get maximize Capital C what is capital is just initial capital c in this Capital understand it as a money it is the initial money that you have plus all the profits that you have obtained all the profits that is obtained will be added to your total Capital means Total Money Right profit is also money in one case yeah so here you have this uh profit setting in this Capital Area so uh so understand see understand this profit as money let's break down in some button right and this is what w is what initial money case or total projects you can do or maximum possible projects okay now there is something known as capital and this is bit confusing here because the answer also because you need to return maximum capital right maximum capital you need to return so think of this maximum capital as maximum money you can get now that is one line in the problem that says in order to do a project of 5 you must have capital of I so that means see uh if you forget about this Capital let us say there is nothing it's like that's a thing like capital and if you want to do two projects which two projects you will choose two maximum projects that is the project with the profit three and project with a profit two correct if you have nothing like Capital then you will choose maximum profit projects simple as it is now since you have Capital that means that says that if you want to do the project of this profit three you must have at least this capital of one correct this question says that in order uh to do a project I you must have current Capital should be greater than equal to Capital of I so this is the condition see if you don't have Capital then you will choose the maximum profit project but since your Capital then it is the constraint to choose the profits right so initially see let me write here current capital okay so initial the current capital was what was zero so what uh so and here are I will write choices so here what choice you have only choice of zeroth index Choice only you have the project at zeroth index okay now so you will do this project because it requires zero capital right so you do this project and you earn one profit so you earn you do plus one so afterwards you have one profit so uh so this profit now become capital for another so since you have one profit what other process you can do you can project do project of first index and second index you have choices right you have two choices now you can do either of this project right now which project you will choose from both objects you will choose a with a one with the maximum profit correct simple as it so here you will choose the second index project and do plus three now your answer becomes 4 and you have done two projects so four is our answer got it and if you check here U S 4 is your answer so we here the question is simple that we need to choose maximum possible profit in order to return the maximum final Capital we need to choose maximum profits but to choose a profit of 5 we must have that capital of I simple as it is so I hope you guys understood the question what we are doing here if you look at this example since we have k equal to 3 uh and so see here initially we do this uh project our project at zeros and zeroth index because it requires zero Capital so after doing this you will gain what see after doing this you will gain capital of uh or capital of zero will be increased to one right after doing this now this is done now with Capital One what project you can do you can only do this project right so you will do this so Capital One one will increase to what you will add 2 to this so it will be increased to three now after this ah since the current capital 3 is greater than equal to two so yeah you can do this you will do this third project so the capital with increase to from three to six because we each have three profits so six is our answer so what we are doing here we are doing initial Capital plus profit one Prof plus profit two plus profit three we are simply adding the profits and we need to maximize this correct got it so let now let us now understand this with one another example see you have this Capital given you have this profits and let me take here k equals to 2. right so here let me write down current capital and we will do a dry run okay we will do a dry run and we I have I will write choices okay so initially your current capital is two your current capital is 2. so with that what choice you have only uh one choice uh with a capital two right this is only that is only one choice so you do this project with a capital do and its profit is what how much three you do this project right this is capital and this is its uh profit so yeah you do uh plus three and your new capital u current capital becomes 5. okay so your current capital is five so you can take this project the first project with the capital three and profit four and the second project with a capital five and profit three okay now after doing this uh you have means after uh getting your choices what you will select the project with the maximum profit yeah so you will do plus three so your answer will turn out to be eight so after doing um after doing this you will know that means you have K projects and you got a answer now instead of K is equal to you have if you would have three then you would have only choice means after getting it you will have only choice that is 5 comma three correct so you will do this project and get your answer 11 right this would be answer if your K would be 3. so I hope you guys understood that we are simply try doing what we are simply doing initial Capital plus profit one plus profit two plus profit frame we are simply maximizing this what we are doing maximizing okay now based on this uh we need to find uh some intuition see till now we have understood the project and what we have to do now what would be our approach and uh so from this uh from this condition we need to find some intuition and based on the intuition we will find some approach so what first thing you need to do is um we need to get these choices right in order to get choices from of this capital what we have to do we have to uh something we have to do sorting like thing so that let's say you have some Capital like this so after doing sort it we can keep an eye on the window that from here to here it is possible to choose a capital then from let's say after we have increased the profits then from here to here it is possible so we are just increasing the size of the window as you can see we are increasing the size of the window whenever our current capital increases so in order to check that uh what how much amount of capital or what all capital projects we can buy we need to sort it correct and now after sorting for each window what we need to choose maximum profit for each window we need to choose maximum profit right so how you can choose maximum profit from each window we can use we can do that by using or by further doing some sorting okay we need to also choose a maximum profit from each window size correct so yeah what we would do our approach would be we would store Capital comma profit in one area and we would sort Accord with the capital we would solve this with the base on the capital and for each uh possible Capital we can take we will do we will use one priority queue what priority queue or you can say maximum Heap and this will store what this will store profit or so this priority queue will store maximum possible profit with a current capital maximum possible profit with current Capital so yeah this thing will be stored in this priority queue and how this maximum RC how this what how this you will data possible profit based on this window so this many possible profits are there this many Professor profit possible profits are there and you will choose maximum from it so this is why priority your maximum yield will work here so I hope you guys understood this that what we are simply doing in this question and based on that we simply did our approach to the solution correct so yeah let's move on to the coding part where we will gain more understanding of how to solve this equation uh so here uh this is the quotation that this is the code that I have written let me just initials okay so initially I took n as the total profit size then as I told you that I am sorting uh based all the projects based on the capital so sort based on the capital then I am taken I have taken one priority queue for profits and one pointer chain now as I have told you that I will keep a window from I to J correct so let's say two three four five six seven eight nine so let's say this is the capital item okay your initial uh capital W is one let's assume and let me and let's say this is the profit error so this is cap and this is profit okay so initially W equal to one okay so initially what window you have only this window right you have only this window from I and because uh this for 2 it will be out of means this project will be the capital there is Project J DOT first would be greater than W that is a current this is what this is the current capital we have so yeah this uh loop will break for J equal to this one index one okay yeah and then so after that we took the profit what we what I have already told you we are just doing W plus profit one plus profit two plus profit three up to profit n we are just taking maximum profit at each uh loop right for each project so yeah we took the profit dot top so what does stock will continue this will make contain maximum possible profit okay this stock will contain maximum possible profit and we pop that happens once the project is taken we can't take it again correct so yeah uh now our eye comes to here and our J will be what our window will increase till here right up till this same because our W was initially what initially one then it was changed to 1 plus 2 that is three now our current capital is three so our Windows has increased so what we will choose maximum profit because this stock will give maximum profit it will it helps both three and four but it will give maximum profit less four so four plus three that is seven okay and we pop this out we pop this and this also so currently we all do we do also have this 2 comma three and our window size will increase to up till 7 right so we will push all this into this priority queue profit and we will take maximum profit out of it okay let's just make some profit so seven plus eight how much is 15. so we will do all this up till K that is K number of projects that are there so this is how this code works that each time we keep increasing our J right that is the maximum possible Capital we can take and from that maximum possible Capital we are choosing the profit maximum profit okay so yeah I hope you guys understood the question the intuition as well as the approach for this question and if you are still any doubt then do let me know in the comment section not talking about the time and space complexity the time complexity here is Big of n as you can see that we are sorting as well as this priority queue both will take bigger friend time complexity sorry uh sorry not big often it's big of n log n both the sorting and the priority who both will take we go fan login and the space complexity here would be big of n as we are storing n this a vector is of size n as well as the priority Queue at Max it goes to n elements in the worst case so yeah you can say the space complicity is bigger fan so that's all for this video uh make sure you like this video And subscribe to our Channel and I if you find this really helpful then do comment your feedback so it will help YouTube algorithm to promote this video so thanks for your support thank you
IPO
ipo
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. The answer is guaranteed to fit in a 32-bit signed integer. **Example 1:** **Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\] **Output:** 4 **Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. **Example 2:** **Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\] **Output:** 6 **Constraints:** * `1 <= k <= 105` * `0 <= w <= 109` * `n == profits.length` * `n == capital.length` * `1 <= n <= 105` * `0 <= profits[i] <= 104` * `0 <= capital[i] <= 109`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
1,480
Ajay Ko Hua Hai Hello Everyone Welcome to New Video in this video is absolutely traditional problem list code problem wave problem only problem running from 10 return running here we will be told after that we will call it running return Running has to be done right, running has to be enriched Meghnad, we are given something like this want to three and then what will be its running time like running but if I see then it is hot from zero to that place because if till the time I reach there then subscribe like and Subscribe now to 12428 If this is our running Always appointed for running fix This and all the other queries of running So for this one plus one day test For this two plus one two three For latest 5 minutes five plus one [MUSIC] SUBSCRIBE FOR NEXT Running and we have this problem, after that what do we have to do, what does our Till there we have to take it, what do we have to run a hotel there, where did I request to 06 sexual I plus, okay there are 10 to I'm sorry pimples inside it, do n't push it hard and plus will do it and after that which What will we do with that, we will keep adding to it and this is our as if all this is over, then we have Jaag which returns our online, so what do we do here instead of Yara, number or now if we use this problem. Subscribe for time complexity, he is running this of books and if this is ours, then subscribe to our channel, subscribe the size which we had made by answering, which we are making of Banaras, we are making this, so how much was the extra of it? That's not our Subscribe Loot Mize because time complexity omega wait which Myspace complexity of now we follow us on Twitter that on Twitter follow us that can be converted here and can now convert school here to us here anyone New, here we have this lace till plane and inside this we have come our number, this is our name plus and minus one quad and as this out will end then we will get our solution, we will grate it so this is our simple service if Let's look at the time complexity for this. There will be time complexity for this. That time complexity for this will be soaked. Thank you all subscribed and subscribed will be ours. Subscribe to ours to appoint here. Now if we are 1234 then quarter inch plus from here. Plus minus one is alarm set one minus one 3101 so our two plus one will become this so here instead of two update which is our this is our three four now our i will become like value two plus minus one two if we our three ES - 1313 6 Subscribe for 6 Finally Bigg Boss robbers and this is our answer that if we return then they will anoint our solution and let's see before that subscribe those people 9 - This will be our basic values ​​and - This will be our basic values ​​and - This will be our basic values ​​and this is ours till date So by subscribing to both of them, let's solve this problem. First of all, what you have to do is to run it from 106 Sexual K to End Tak Aishwarya Equal to One, that as we will do it, this is our element - - Verb this is our element - - Verb this is our element - - Verb - If it doesn't then it will give an option because of which - If it doesn't then it will give an option because of which - If it doesn't then it will give an option because of which it will not be ours then like here but but we will open this and do village plus this - 1m - 1m - 1m Now this is our simple what can we do other than that, we can remove this so this Our plus equal to two, we will have to write this plus equal to two then our SIM solution and as soon as this follow is finished, we will click the button 'What's finished, we will click the button 'What's finished, we will click the button 'What's our name' which was our simple solution and then our name' which was our simple solution and then our name' which was our simple solution and then submit and while doing that, once more our solution is needed here. But if we did not do any pan, then if we do some work instead and keep watching our Ghaghra, let's do six pieces for this post and see if it subscribes to us and if we did less than eight people, then I hope you. Here we have made some changes in understanding the solution, we have turned off Omega of time complexity of Meena Megha, we have given Omega of her and space complexity of her solution. If you want to practice regularly, then you can join our channel, the link of which is in the description. Thank you for watching my video
Running Sum of 1d Array
movie-rating
Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`. Return the running sum of `nums`. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[1,3,6,10\] **Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\]. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** \[1,2,3,4,5\] **Explanation:** Running sum is obtained as follows: \[1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1\]. **Example 3:** **Input:** nums = \[3,1,2,10,1\] **Output:** \[3,4,6,16,17\] **Constraints:** * `1 <= nums.length <= 1000` * `-10^6 <= nums[i] <= 10^6`
null
Database
Medium
null
307
hi everyone it's Oren today we have a problem when we are given an array let's say that array of 4 7 8 and 10 and we need to implement two functions two methods one is update and another one is sum range for the update we are given an index and we are given a new value updated value for example let's say that for index one we are given the value of 12 so we are updating for index one we are updating this value to 12 and another one is the sum range so we need to find the sum between the given indexes so for example let's say that we are given index zero and uh three right and we are updating the value which is we are returning a value for the between one and the three which is 28 there are several ways how we can solve this problem and the easiest and the straightforward is that we are taking the value of the left index and then we are keep adding the values until we find the right index value of the right index and then we are returning uh returning the total sum so in this case the time complexity of this solution is of n can we do better than that here for the sum range yes we can do another method is that we can use a prefix sum so we pre-calculate all the values pre-calculate all the values pre-calculate all the values before so let's say for example here we it's values three 3 + 4 gives us 7 and U it's values three 3 + 4 gives us 7 and U it's values three 3 + 4 gives us 7 and U 3 4 + uh four 7 + 6 gives us 13 and so 3 4 + uh four 7 + 6 gives us 13 and so 3 4 + uh four 7 + 6 gives us 13 and so on so in this case the time complexity would be constant that but the problem is here that the update function is the for the update function if we are updating the value let's say here to instead of four we are updating the value to 10 then we have to update all the values that's that comes after it so in that case again the our time complexity would be ofn for the update so another method is that the where we can achieve the time complexity for log of n for both for sum range and update is to use binary index tree so what's the binary index tree so biner index tree that the let's start with the very simple so for our array for our initial array right let's call it nums for our initial array instead of setting indexes to values 1 3 4 five so we are setting the binary numbers for them so we are setting in binary numbers and we are constructing a tree based on the rightmost value of our indexes so what's that mean so for example the rightmost value of our binary numbers where the value is equals to one it's here and here right so for this values we are just taking the values as it is for example for the first one we are taking the value of three for the three we are taking the value of six for the for five we are taking the value of five and for the two we are taking the value of two and that is the kind of bottom of our tree like lowest leaves of our tree let's say so five and two so what's the next one we are taking where our second rightmost value is equals to one second rightmost value for example it's here and it's um it's here the value of it is the sum of the current value and plus the whatever comes before it so for example in this case 3 + 4 gives us s so right in this case 3 + 4 gives us s so right in this case 3 + 4 gives us s so right gives us seven and uh in this case 8 + case 8 + case 8 + 8+ 8+ here it's eight actually it's 8+ 8+ here it's eight actually it's 8+ 8+ here it's eight actually it's eight here so 8 + 12 gives us 20 right eight here so 8 + 12 gives us 20 right eight here so 8 + 12 gives us 20 right so 8 plus gives us 20 so value is here eight 20 and the last one is that the we are taking where the rightmost value is third right so here we took the first one so the second one right where the rightmost value is equals to one and the rightmost value equals to rightmost value is third is here the value for this one the all the values that comes before it again the all the values we are calculating here and it gives us what it gives us 10 so and uh this is our this is kind of our binary tree it's not exactly the binary tree but um we are so it looks like a binary tree so resembling a binary tree so what we do here so how it's going to help us to achieve log of n time complexity so for example let's take the sum is equals to 7 right so what's the what is the how we are going to calculate that sum is equals to 7 and for the sum for seven the value for the seven is two and we are taking the binary value of it so we are taking the binary value of it 0 1 and uh we are flipping the last set bit of it so for example in this case we are flipping this one gives us 0 1 0 which gives us which is the value of 6 + which gives us which is the value of 6 + which gives us which is the value of 6 + 12 and the plus we are again flipping this value which gives us 0 1 0 which is this value + 10 and In Sum gives us is this value + 10 and In Sum gives us is this value + 10 and In Sum gives us 32 which is the sum of seven right so and we are flipping the last one which is 0o and 0 is equals to Z so and we are going to for the range sum we are going to calculate the right sum and the left sum and in both of these cases the time complexity is log of n so it's a two log of n we can take that as a log of n so this is the sum right this is the sum function and how about the update function let's say that we are updating let's say the value of two to 11 right value of two we are updating to 11 so what we do here first thing that we do we are updating the value itself in the nums right in the nums we are updating value to 11 and the next step is that we are taking a difference the difference is uh 11 minus 4 gives us 7 so we are changing the value first here two 7 + 7 gives us 14 and we are doing two 7 + 7 gives us 14 and we are doing two 7 + 7 gives us 14 and we are doing the exactly the same operation as we did before now in this case we are not flipping the last set bit we are adding the last set bit so we are adding to our what is what was what's the what's our binary number here is 0 1 and zero so we are adding the last set bit and our now value is 0 1 0 which is here right so which means that we are going to also update the value here we are also adding the seven here right we are adding the our difference so 11 minus 4 we are adding s here it's 14 and we are adding seven here which is now 17 and also again our update function the time complexity of our update function is also log of n first thing that we do here we are creating two variables nums and bit for nums we are setting our initial array and bit is our binary index tree so we are taking the size of it as num nums length plus one because our binary num start from zero not from one and that's why we are setting plus one here so the next one is we are populating our binary index tree so for each index we are passing the value and in our binary in our update bit method or function what we do here so we are setting the so we are incrementing Index right away because again our binary um our bit array starts not from zero but starts from one so we are updating the value and the next one is that we are adding the last set bit and we are doing this operation and the propagating the value adding to all other indexes and until our index is exceeds the bit length the another one is that our sum range function what we do in our sum range function so we are calculating from for the right sum and we are calculating for the left and again for each one it's uh log of n it's and in total the time complexity is two log of n we can disregard the two parts so it's a log of n so what we do in the get sum function fun so in the get sum function we again incrementing Index right away and we are adding to our sum the values of from our bit index array so we are adding then we are flipping our last set bit and we are adding the next value until our index is more than zero and we are returning some in our update function it's the same as we have seen earlier right we are taking a difference and we are updating our nums index with the initial value right away and then we are adding the difference we are adding to all the all to all indexes in our binary index Tre so we are calling again the update bit method that we have seen earlier okay uh what's the time and space complexity of this solution again the time complexity is log of n for both function for update and the sum range and the space complexity is determined by this these two data structures in both of these cases the time space complexity is they are taking n values so the space complexity is two of n so we can take it as a space complexity as o of n okay uh that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Range Sum Query - Mutable
range-sum-query-mutable
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `void update(int index, int val)` **Updates** the value of `nums[index]` to be `val`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "update ", "sumRange "\] \[\[\[1, 3, 5\]\], \[0, 2\], \[1, 2\], \[0, 2\]\] **Output** \[null, 9, null, 8\] **Explanation** NumArray numArray = new NumArray(\[1, 3, 5\]); numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9 numArray.update(1, 2); // nums = \[1, 2, 5\] numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-100 <= nums[i] <= 100` * `0 <= index < nums.length` * `-100 <= val <= 100` * `0 <= left <= right < nums.length` * At most `3 * 104` calls will be made to `update` and `sumRange`.
null
Array,Design,Binary Indexed Tree,Segment Tree
Medium
303,308
231
hello hi guys good morning welcome back to a new video in this we're going to see problem power of to it has been asked by Amazon Bloom wobi Snapchat Apple Google General Motors Uber qualcom and GP Morgan so although it marked as an easy problem but it will teach you a very important skill which is actually used in your f victores a lot like it's the prime um thing or base of fct trees spr says that you are given integer n and you have to return true if it a power of two and you know what's a power of two let's say 2^ 1 2^ 2^ power of two let's say 2^ 1 2^ 2^ power of two let's say 2^ 1 2^ 2^ 3 2 4 all the other power of two which means 2 4 8 16 and so on and so forth now otherwise you have to return a false and integer N is a power of two if there exist an integer X such that s same n = exist an integer X such that s same n = exist an integer X such that s same n = to 2 x now it simply means that whatsoever integer n we have only two divides that specific integer and we can just simply check that what the problem is saying simple force that a simple n for us if my n is zero simply return a false because then it is not a power of two else I can simply go and check if my n mod 2 is zero keep on dividing that keep on again while loop is keep on dividing that number by two and ultimately if I have reached one which means okay it was a power of two for example if we just do a small dry let's say n was 8 yeah n 2 is 0 okay divide my n by 2 okay n will become four again n 4 2 is 0 okay divide my n by 2 again my n will become a two uh 2 is 0 yeah again divide my n by two so n will become a one now with that case you can simply see that your n has finally reached to one and again 1 is also power of two which is 2 0 right so I can simply say that yeah I have reached my base case and simply this is a power of two for example if it would not have been the case which means n = 12 then I can case which means n = 12 then I can case which means n = 12 then I can simply say Okay 12 m 2 yeah it is divisible by two simply divide that by 2 6 m 2 again it is divisible by two divide that by 2 3 mod 2 is not oh sorry bro my last thing which I can have is three so n equal to 3 it is not equal to my 1 which means I did not reach my base case so the number n whatsoever I have started off with it is not a power of two so simply return a false so I can simply sa my base condition as if my n finally becomes equal to one after doing a complete division by two then okay it's a power of two else it's not a power of two so you can simply see it is doing a simple division by two at every step which means I can simply say okay I have a log I can I'm dividing by two then again by two and so on and so forth It's a simple login operation right as you have simply seen and space we are not using any extra space so space is of one but can we improvise that now improvisation of log n is only o of one so we have to think of improvising that to O of one now for the folks who have watched our fenic tree video again if you not watched it I highly recommend go watch it is a complete fenic tree guide and it's a very short and simple code just one lineer code and in that we have completely again this portion right here you see right I use exactly same code so in that what happens is okay if we start visualizing how a power of two will look like in the binary form then I can completely reach to a conclusion that let's power of two which means 8 it will look like that my third bit will be set from the right side if I have power of two which is four then my fourth bit will be set from the right side and the same way you will see that this binary representation itself says okay what is the power of zero power of one sorry as in uh a 2 to power 0 a 2^ 1 one sorry as in uh a 2 to power 0 a 2^ 1 one sorry as in uh a 2 to power 0 a 2^ 1 or 2^ two so this indicates this or 2^ two so this indicates this or 2^ two so this indicates what all powers I have for that specific two now ultimately if something is a power of two which means it is just a 2 power x so that X the bit will be set that's it while if it is not the case which means if the number is 12 so it will be a mixture of a power of two which means a 2^ 3 plus a 2^ two which means a 2^ 3 plus a 2^ two which means a 2^ 3 plus a 2^ two which means two bit will be set so I can simply infer one thing that if I have a power of two then only one bit will be set if it is not a power of two then more than one bit will be set in that number so I just have to figure out that in the binary representation of my number n if only one bit is set then it's a power of two else it is not a power of two now how I can do it there are multiple ways there are two ways but again we have to just figure out an O of one way again I'm saying there are two ways to do it in O of one way but we will go on with what helps us and what we have been using so far so in this we remembered that we removed the last set bit if you go and look at this exact same screenshot of the code then in that we removed in this you will see that we flipped the last set bit and if I just simply say one thing that I have only one set bit if I even flip that specific set bit again I know I have just one set bit if I just flip that set bit it will simply become a zero so if I apply the same operation on this number n and I flip the last set bit or basically I know that it will have only one set bit I will flip that bit then the number should become ideally zero then if it BEC zero then it's a power of two else it is not so I'll do the exact same thing I'll remove the last set bit and the number should become a zero let's see what happens in that case so basically let's say we have a number n again I have used exact same piece of information here I have a number n i can represent that same in the normal binary form again I'll explain dry running that but I also take the minus n now minus n is nothing but the negative of the previous n how to get a binary form of this minus n again it's a very standard technique which is called as two's complement and how to generate the two's complement of a number n it is nothing but flipping the bits of the number n in the binary form and then adding a one if we do that we will generate the two's complement and two's complement represent negative of that number again now what we do is we have got n and minus n we'll simply do a and operation between r n and R minus n then what will happen is we will get only the last set bit with this operation we'll get only the last set bit but if you remember my operation was to remove the last set bit so from this nend I'll remove the last set bit this was the last set bit I'm removing that from my n thus I am removing or flipping my last set bit and with this if I do something like this operation ultimately my n ultimately if I just assign that to n OB basically this operation should turn out to be a zero if this is zero then for sure I had a power of two for example take an example okay number is seven you can visibly see it is not a power of two right it is not a power of two number is seven I have three set bits so for I apply the same operation ID is 111 again everything is in the binary form then minus of ID again as I showed you I'll take this is a two compliment and how to generate that simply flip the bits okay flip the bits and then simply add a one so I'll get two compliment now as you remembered I'll do and operation between them by doing a and operation between them I can simply see that I will only have the last set bit so in this operation after doing the and operation I only had the last set bit now I've have just removed the last set bit from my actual input which was the ID in this case so again if you might have seen AR what is this query and stuff it is the exact same piece of code which will help you in actually your F Victory that's the reason I have related that with the F Victory because see fan Victory is a hard concept but this is a easy problem so I just want you to relate everything so that you don't have to study or you don't have to think that okay what why I'm studying this why it is useful all that stuff so you saw that okay this is the last set bit now you just have to remove that from your ID so ID was simply 111 which is number seven I have the last set bit I'll simply remove that simply subtract which means remove that now you will get an value in this you can see your last set bit is flipped but again as you saw after flipping the last set bit the number did not become to zero equal to zero because for sure it was not a power of two so let's see another example so if I had the number six again it should also not ideally become to zero when you remove the last set bit and we'll see the same exact same stuff that we had an ID we'll do a minus ID again we had an ID like we will again do this operation entire operation and subtract it then my ID will actually become a four you can just try it by yourself also but yeah this can actually become a four so I know simply my ID has become a four now same way uh this did not this after doing this operation ID again you will see that this did not actually reach to a value zero so again for sure this was not a power of two but let's say we take this example now we know by number we see it is four which is power of two so it should ideally by removing the last set bit as you can also see by removing this last set bit and making it a zero it should ideally become equal to a zero so I do exact same operation that I have my number four I'll get the ID and I'll do ID and minus ID what will happen ID is equals to A 0 1 0 minus of ID firstly getting the two getting its two's complement so flipping the bits okay flip the bits 1 0 1 again every bit will be one no worries now add a one so what I will get I get a 0 1 sorry 0 1 0 and all that stuff now this is ID and this is minus ID so after we do the and operation what will happen is ID and minus ID which means 0 1 0 I'll do a and operation I get a 0 1 0 now I have to subtract this last set bit from the ID itself so I'll do a ID minus ID and minus id was a 0 1 0 minus I like this idus ID is actually nothing but a 0 1 0 I subtract that I simply get 0 this is the reason I have removed the last set bit I have got the value zero does my ID was a power of two and th I can simply say that I had a power of two itself thus I can simply the exact same code that X and Min - x let's say my input was n or and Min - x let's say my input was n or and Min - x let's say my input was n or I can say x anything now you will add in why you used long because you can see that my n is actually minus 2^ 31 see that my n is actually minus 2^ 31 see that my n is actually minus 2^ 31 which is out of integer bounds because integer has a limit of 31 to 2 31 so this is out of my integer bounds so if you use that so you will exactly get the error at this runtime error so I used a long to convert that to a long because of this just value and then I used the X and minus X to actually get the last set bit remove the last set bit from my number X and after removing that I should get a value zero if I'm getting a value Z which means I had only one set bit which means I had a power of two cool that by that you can simply Solve IT time o of one and space of O of n cool bye-bye thank you so much goodbye
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
378
hey what's up guys this is john here so today uh let's take a look at this elite code problem here uh number 378 uh case kate's smallest element in a sorted matrix okay given like an n by n made 2d matrix uh which each row and columns are else they're all sorted in a standing order basically each row and the column they are sorted it asks you to find the case smallest element in the matrix and note that is the case smallest element in the sorted order not the case distinct element so what does this mean it means that let's say we have a one two three four five and six and seven uh so let's see if this is the sorted array right basically and if it asks us to find the let's say if the k is equal to four okay in this case it's one two three four that's four right then the answer is four how about when equal when the k is equal to five it's still four right because it asks us to find the k smallest element okay so k equals to six is also four and k is equal to seven then it's five okay basically that's what this uh this sentence is telling us cool so um what's this first solution right since they're all sorted okay they're all sorted you know i think the first approach will be uh try to make maybe find the row correct row and then try to find the next card next the next uh element but this is like a 2d array right and they're sorted on two directions so that won't be that easy i mean a brutal force way right what's the brutal force way of course the brutal force way will be uh we need to sort the uh the entire matrix okay and then we just find the case element that's going to be the brutal force but for that one we have to basically uh that's going to be a n square right to sort uh to sort like the uh m by n like matrix the total element is n square and to sort that we're going to have like n squared times uh log n square right that's going to be the total uh time complexity which will be uh a lot basically right we're going to sort everything and then we find the case element from it okay that's the brutal force way to sort element but then we're not utilizing the case that each row and column they are all sorted so what's the an alternative way of what's a better way of sorting right the dual sorting i mean if you guys remember how can you sort like two sorted lists let's say if we have like sorted list here a here and another sorted a list b we have a one two five seven here we have a three four six eight so how do we sort this two sorted list right we just have two pointers basically right we have two pointers here and every time uh this if this pointer is has a smaller value than the other pointer we okay so this is the current this is the smallest number among those a and b and then uh we will have like uh when we move this pointer to the next one okay and then we keep comparing that whoever has a smaller number that's then that's the current the next smallest number and then after that we move the pointer to the next one so but so in our case right it's actually since every each column under and uh each column and the rows they all sorted basically it's just as if it's like we have unsorted list okay either way we can treat like the rows uh the rows that sorted the list or we can trade a column as a traded list it doesn't really matter we can do it in either way so now the problem comes down to the uh i mean we need to sort like as at unsorted list and then and while doing the sorting as you guys can see right so while we're doing the sortings actually after we after doing this the case sortings then word the k minus one or the k minus one sorting then the next one the next result will be our sorry the next smallest number will be our result which is the case smallest so and how do we sort uh unsorted list it's a common way to do is using the priority queue okay so how do we use the priority queue the source this unsorted list let's say we have a sorted we have list a let's say we have c here and we have d and we have e okay so the way we're doing this uh the uh what the priority queue is that we push each rows i each erase the first element okay into the uh into the priority queue we have a priority queue here okay so while we're pushing that we also need to push not only the numbers but we also need to push like the which uh which array this number belongs to the right so that when we pop that number out we know who is going to be the next number of that number right so and basically we you we just use the priority queue to maintain the current uh smallest number and after pushing each of the elements uh after pushing each erase each list uh first element then we just keep doing the hip pop and every time we do a hip-hop we know that's our hip-hop we know that's our hip-hop we know that's our current that's the uh the current the smallest number right and after popping that uh we're gonna use the uh the informations uh along with that number like in this case it's going to be the identifier of which list that number belongs to and then we're going to move that uh the cursor or the pointer to the next one and then we're going to push that one back to the priority queue and we when we leave we will need the priority queue to tell us after pushing this one who is going to be our next smallest number and we just do keep doing that until we finish all the uh until the priority queue is empty right then we have a sorted list but in this case since we only need to sort case k minus one times we can simply store uh you can simply uh like uh save some time but that's basically that the idea and yeah and when it comes to this problem and how can we a lot besides the number itself how can we uh know like which list it belongs to right we just need to store the uh basically the current numbers uh the coordinates that the row and column and depends on like uh depends on if we use if we treat the row as a sorted list or the column as the sorted list we can just move that numbers uh either one to the right or one down okay cool i think that's pretty much the basic idea of the first solutions uh let me try to implement that okay so the first one is the length of the matrix okay and let's see and then uh we need the priority queue here okay so that's a priority queue and then like i said uh let's push each of the elements uh the first element into that in the particular so in my case uh i'm going to use the uh i'm going to use like the column i'm going to treat each column as a sorted list basically so this is a sorted list this is also a sorted list so that uh when i push the first the starting point the first element i'm going to further do basically push the first row into the uh into the priority queue here uh for j in the matrix sorry in lan in range sorry range n here and uh pip q dot hip push okay priority queue and matrix zero dot j okay yeah like i said uh like i said you know we cannot simply push the number itself because uh later on when we pop these numbers we need to know uh who is the what who is that going to be the next number of that one so to be able in order to get that one we also need to store the index along with the number itself okay so that's the current the index of the card number and then uh we just need to do this uh this sorting right or the uh the hip hop k minus one time so that the next one will be our case number right so that's why i'm doing a k greater than one to do a k minus one loop of this so i'm gonna have a card number dot i dot j right equals to the heap q dot hip pop prodiq basically every time so now every time i have a hip pop here this number will be our the current smallest number right and uh okay and then like the uh we need to keep push hip q dot keep push the next number but before doing the next numbers uh we also we need to do a like the check right basically if this one if the current uh index has reached the uh i mean if the current uh current i right has reached the last row basically that's the last element we cannot uh there's no point of basically we cannot there's no more like uh next number to push into the queue so that's why we have to do a simple check here basically if the i is smaller than m and minus one okay then we uh we do a and then we do a heap push here uh priority q so the number will be the matrix okay and the current i plus one dot j so this means that let's say for example if we pop the one out okay if the card number is one and the index is zero and zero so the next one basically we know this i minus one means that okay since this i is built up belongs to the j column right that's why we only we're only going down this means we're always going down by one which is the 10 in this case okay and also the index along with the value okay yeah and of course we need to decrease the case by one cool yeah so i mean after k minus one uh hip pop so the case time will be the case smallest number right which happens to be our answer right so we can simply return the priority queue dot 0 that will be our answer because this now this one will be the case smallest number right after the k minus 1 hip hop cool i think that should work oops oh sorry yeah since it's uh we're storing like a table here uh it's the first element okay cool yeah see it's pretty straightforward right yeah i think it's a beautiful solution basically you just we just need to like utilize that uh sorted case k sorted list unsorted list and then while doing that sort source it's easier it's very easy to find the case smallest number so and the time complexity for this i mean it's the uh actually you know we can even do a small like improvements here because you know actually we don't need to push like uh all n elements into the uh into our heap q here right because whoever is smaller it's fine i think it's we can even do this right because uh miners uh n and the k this will also work let's say we have a huge end here let's say we have a huge list here it's very big but the k is like let's say we have a hundred like uh by a hundred but the k is like what k is like uh five okay so in this case we just need to push at the most five rows that's the most rows we need to uh to be able to find the case smallest right it kind of makes sense so uh let's try to run i think it should work yeah but even though it's it i mean it didn't change a lot but this thing i think is because the test case the k and n they are pretty close okay the k and n squared i think they're pretty close so yeah basically the time complexity for this what's the time complexity that's going to be uh whoever is smaller for this one and the heap push is like uh oh of k you know what actually let's assuming we use n here okay let's make it easy we're just assuming we're using n here so this one's gonna be a n times log n right yeah to maintain like a heap yeah plus what plus d at this one that's the k uh times log uh log n i think yeah assuming we're using n here right so that's going to be n times log n plus k times log n which will be the n plus k times log n okay cool so basically that's our first solution here but just by utilizing the priority queue to simulate the uh sort unsorted list and then we can easily find the case smallest number and okay and second another solution is by using the binary search you know since they are all sorted i think it's kind of like natural to try to think about think of like a binary search solutions yes and it is true that this one can also be solved by the binary search and let me try to write that function here the solution here basically you know for the binary search you know since um like i said this thing this matrix is sorted in two directions so we cannot simply use the uh the index binary search or the bisect right to find the uh that the element okay so which means we have to uh using like the uh hyper functions to do it and to search the answer you know so again the left will be what will be the matrix will be the first one so we need to have a range first matrix uh so the left will be the uh the first one okay that's gonna be the zero okay and the upper bound is what is the n minus one and n minus one because the top left corner one is the smallest and the bottom right corner is the biggest that's our like search range here because the uh the case smallest number has to be high so between those two numbers okay and then the other template here basically the left is smaller than right and then we have a middle left equals the left plus right minus left divided by two so now we're going to have like hyper functions here right and i think one of the tricky part it's not like tricky but one of the things is kind of a little bit confusing is the you know when we do the middle here right so the middle could not may not be in the matrix okay so then if the middle is not in the matrix right how can we make sure the ones we find is the is one of the answers here uh that's because you know uh it deep because our or how our helper function here that will guarantee that we will the final answer is it has to be one of the numbers in the in here so basically uh the hyper functions we're gonna define here we're gonna count uh less or equal numbers with the middle okay and i think i'm going to try to implement this one real quick i think for this one it's not that hard to implement this right and then for j in range uh n here okay basically if the matrix uh i and j uh is equal smaller than the middle right we just simply uh increase the count else as we well we can just break here okay and then we simply return the uh the count here i mean we can also like break earlier like the uh i mean here right i mean if the matrix dot zero uh j uh i sorry i zero is greater it's greater than the uh than the middle right then we can simply break here okay because there are also they're both sorted in two directions i mean this is like optional but it doesn't affect a lot but it's simply a discount right and the tricky part is let's say so why where why we are first why we are like uh counts the equal here it's because you know if we have one two three four five okay uh yeah and let's say the k equals to five okay and when the middle is four okay so when the middle is four and when we count four here right so we have like how what's the count of four here we have one two three four five six basically the count is equal to two to six okay and so when the count is equal to six and which is equal or greater than the then the k here we know that okay so this number the middle could be our one of our answer here okay so like this so basically if the count uh count smaller or equal less or equal okay i use this less or equal uh okay i'll do this if this is smaller than k if this one is smaller than k then we know okay it's definitely not one of our answer right else we do a middle sorry we do a right equals to middle and then we simply return the left basically that's the idea here i that's the basic the code here you know so this one you know every time when you have like a right equals to middle this one is as if you're like you're getting uh like the smallest uh number that's satisfying this condition okay so which in our case that's happened to be our i think that's exactly what we need here because we need to find the case smallest number so the k smallest number it means that uh it means that you know whenever you have like a range of the of this the four here let's say for example you know the uh so the four is in range one two three four five six so it means that you know the k right when the k is eq when the k is between 4 to 6 our answer is always four right yeah so basically you know this is i as if like we're trying to find the smallest answer sorry the smallest number that you know the smallest number whose uh the count the last the count uh less or equal to that number uh is equal or greater than k okay and about the uh how about the uh the case let's see the middle that does not exist in our array here let's say we uh for example this one right let's say we have a 1 5 9 10 11 13 12 13 15 let's say the middle is equal to 14. okay and so the count for 14 is so is what is one two three four five six seven it's eight okay it's eight and okay and our input our case is also eight okay cool so our input is also eight okay so which means i mean we're okay we're trying to find the smallest number that satisfy uh this count is equal to eight right then since 14 is not there instead and who and things are count you know it's also is including the middle itself so which means the 13 the 13th count will also be eight right because 14 is not in our list in this not in our like matrix that's we then makes that the 13 always satisfy the count equals eight and since the third both thirteen and fourteen they're both satisfying our conditions here that's why our answer is thirteen so see so this is like is exactly the purpose of doing the right equals to middle basically we're trying to find the minimum number that satisfies this count here so and this then this one plus the uh the last or equal plus the hyper functions that both of them are is are guaranteeing that our answer will never will always be the answers that will always be the number that is part of our matrix i think i haven't run the second the binary search code yet oops okay cool so the test case passed submit cool yep so it passed right so and yeah i mean this binary search is a little bit like confusing but still it's like a standard like a little bit of violation but it's not even vibration the template are exactly the same right it's just that you have to think of like uh with this template how can you utilize the uh how can you make the uh the helper functions to help you uh navigate either to the left or to the right and also the uh why we're using like this uh the minimum answer template right because i think that's because we are trying to find the uh we're trying to eliminate the candidates that's that does not exist in our matrix okay that's why we're using like the minimum templates here uh so for this like binary search one i think the uh so the time complexity for this is like the what so here we have a uh this one i think that the range for this is like it depends on the biggest number so what's the biggest number here right that's gonna be our range it's gonna be a log a max number right a max number here times what times the uh times how the time we spent to do the search here i mean i think the search here is like um i mean we can it's possible that we'll stop early here so i mean the worst case scenario this is like the uh the un square right but since we're search it's all sorted i think um yeah this one i'm not sure what's the time complexity for this doing the search here um let's see i think here is something like a an n here yeah it's close to n yeah i would say it's like uh it's like a n here so here actually so the maximum is a log maximum minus minimum right that's the uh one and here is the uh yeah i would say it's a close to end here because we have this like early terminations and every time we search like n numbers yeah we search numbers at most that's why we have a n times log max minus minimum here for the binary search yeah cool guys i think that's yeah that's setting pretty much for this problem it's uh i think it's an interesting problem especially i think for the first one i'd be i think i highly recommend encouraging you guys to uh understand at least the first solutions you know this is a very useful technique uh to not only solve this problem but also like to basically sort and sorted at least in general by using the product queue and regarding the second one i mean it's not the ideal case ideal problem for the binary search you know it's we have a few like confusing point here if you still don't quite understand it's fine you know because we have a way more other very good uh binary search problems unleash code where you can practice you can just uh maybe skip this one okay cool guys thank you so much for watching the videos guys and stay tuned see you guys soon bye
Kth Smallest Element in a Sorted Matrix
kth-smallest-element-in-a-sorted-matrix
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_. Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element. You must find a solution with a memory complexity better than `O(n2)`. **Example 1:** **Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8 **Output:** 13 **Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13 **Example 2:** **Input:** matrix = \[\[-5\]\], k = 1 **Output:** -5 **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 300` * `-109 <= matrix[i][j] <= 109` * All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**. * `1 <= k <= n2` **Follow up:** * Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)? * Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
null
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Medium
373,668,719,802
392
hey and welcome today we will solve is subsequence interview question let's get into it here is the first example we have a source string as ABC and the Target string is this one now we need to start removing non-matching characters start removing non-matching characters start removing non-matching characters from Target to see if we are going to end up with Source string or not in the same order we get it and if we do we will return true for it second example if we do the same process again and remove non-matching characters we will remove non-matching characters we will remove non-matching characters we will end up covering only a and C characters and not X so we will return false for it let's see how we going solve this problem the idea for this problem is simple it's just two pointers problem if we have a pointer for each string and start toate through them both at the same time as soon as we see two matching characters we would increment both pointers and if we see a mismatch like in this case here we will increment only second pointer because we are looking for Source characters within the Target string and this cycle will continue so at the end when we are finished with ortion if we happen to find all characters of sorts in the Target string then we might return true for it otherwise false and you may ask how we are going to detect it is simple if the pointer on the source string has been incremented as same amount of characters count on it then we are good to return true because then we are sure that we have scanned all characters from source of string now let's jump into the code to implement this solution here we are in lead code first we need to Define our pointer then we will do a v Loop to check if P1 is less than length of our source and P2 is less than length of our Target and if both of them are true we will keep doing our job okay what we need to do first we need to check about matching point between source and Target string if they match we will increment only pointer one we only increment pointer one because the pointer two is the one that we are searching within that string so we might increment it anyway but remember if we increment pointer two within that if Case as well in this scenario we will skip some characters checking in Target Str because in that case pointer two will increment it two times then we have a matched character and finally we need to see if P1 incremented has the same lengths of or Source string because if so that means we already found all characters within Target string now if I run this test case start passing and if I submit we are in a good shape here but let's explore a bit more options now okay that was a super good answer to come up with but let's take this further it may seem a bit dumb but the solution that we are about to go through is the core principle to many other Dynamic programming's problem too so let's cook since this solution is based on dynamic programming we might look into break this problem this whole problem and to soloft problems and for that we will start from ground up or better say bottom up dynamic programming solution so the idea is we will have a two dimensional Matrix of M byn where the vids is the characters from Target string and hate is the characters from source and this Matrix will hold states of how many matched characters are in between these two strings but how first of all we will have a dumb row and column for both axis of this Matrix that will be filled with zeros initially because in order to calculate the values for actual cells we need to rely on those empty values we need a starting point right so that will be zero for us okay for the value of each cell in these coordinates we will have two scenarios first is in that coordinate if the character from source and Target matches what we need to do in that case is take whatever we have directly from bottom left of that cell plus one just because of we found a match here the second scenario is of course if the characters are not matching in that coordinate what we will do we will take the max of the cell below and the cell to the left to that coordinate and we will follow this rule until we fill up the Matrix cells and finally since each cell represents the Matched characters count up to that cell's coordinate then we can easily conclude that the most coordinate cell will hold the total matched characters count between these two strings and the interesting part is if that number is exactly the same as the length of our source string we know that we have the answer and we might return true for it as I said this method is super important in dynamic programming and mostly referred to as tabulation now with that being clarified let's jump into the code to implement the solution but before that I want to mention how encouraging it is to see you like the video and subscribe to the channel it really supports the work and effort I put into these videos and makes me happy and motivated to make more now let's get into it here we are in lead code again for dynamic programming solution initially we need to store the lengths of strings for both source and Target because we will use them several times then we will create our DP array remember that we need to have an extra Dum row and column and initially they has to be filled with zeros okay now we need to do an ntion over rows and columns and build up our dynamic programming states keep in mind that we will start from row and column number one because first row and column are just dummy rows and columns also keep in mind that we are traversing vertically instead of horizontal now within this Loop we need to check two states number one is if characters in the coordinates we are matching together if they match we will take the bottom left cells data and add one to it and scenario number two is of course they are not matching together if they don't match we will take the bottom cell and the left cell to that coordinate and choose the max value between them finally if the state in the bottom right corner of our DP Matrix is equal to the length of our source string then we have the answer otherwise false now if I run this test case are passing and if I submit we are in a kind of good shape here but I want to show you one more thing about why we looked for bottom right corner here the reason is if I lck the DP Matrix here and run this one more time as you can see this one and if I just pry this yeah it's going to look like this and this is the DP state that we made like this row and this column are zero and we are iterated vertically through these and we ended up in this corner and this is like not the same as what I showed in the slides but I just wanted to show you this because I draw the illustrations in a different way and how the arrays and matrices has been built in here is kind of different and acts different but you get the idea you need to look into the corner in your DP Matrix that holds the latest state which in this case is bottom left corner I hope that was a bit helpful for you to understand now let's talk space and complexity so the time complexity will be o of n for two pointer solution but it will be o of s by T which s is the length of source and T is the length of Target string and as you see it is not efficient compared to two- pointer efficient compared to two- pointer efficient compared to two- pointer solution but I just wanted to explain the tabulation in dynamic programming since this is a perfect example for it and the space complexity will be o of one for two pointers but it will be o of s by te for tabulation because of our Matrix States so that was it for this video thanks for watching and please leave a like comment and subscribe to the channel I will put a few more links about different playlists in the description for you to check it out and finally hope you enjoyed this video and stay tuned for the next one
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
258
hey everyone nitish side so let's start with the question so the question is add digits okay so you are given an integer num so you have to repeatedly add all its digit until the result has only one digit and then after that you have to return it okay so let's see with an example so let's take an example as 38 so you need to do some of this basically 3 plus 8 equal to 11 till then your digit is length of digit s1 so we need to do it sum of this again 11 basically 1 plus 1 equal to 2 so now the length of this digit is 1 so this is our final output okay let's take one more example let's take 2019 so if we calculate the sum for this 2 plus 0 plus 1 plus 9 which is equal to 12 so again the length is greater than 1 so we need to make it a single digit number okay so we do the sum again 1 plus 2 equal to 3 okay so this will be our final output okay now let's see how we can approach for this question is basically we can just do a simple loop over a number basically let's do like this we will do while our number is greater than 9 then what you need to do calculate the sum of number and whenever you calculate you just need to update your number by this okay so if this and some you can easily calculate like this by if i write the sum function logic so it will be uh you just take a result variable equal to zero you do result equal to result plus n mod 10 okay and you do after that you just decrease the number by dividing the number by 10 and after that you just return the result okay so by this way you can solve this problem and if you see the time complexity for this we just using a integer an integer has a maximum number as 2 to the power 31 minus 1 so it's a constant time complexity basically if i calculate the time convexity it's big of c okay so now the question is telling us can you do without any loop or recursion or in big of run time okay so now moving forward to our second discrete approach so let's take some example so let's take the sum of zero is zero you know the sum for one you know there are some for two let's check for few digits okay let's take few more number also let's take the sum for this also 10 is basically 1 plus 0 is 1 similarly let's take 11 1 plus 1 okay so if you can see the sum for 19 it's 1 plus 9 which is 10 and we do the sum of this again 1 plus 0 which give us 1 okay so let's do it for more number also okay so i've written some few sample case so if you can see the pattern basically our some final output is basically in ranging from zero to nine okay like we never get the value greater than nine so and you also can see like let me just mark it like after every in basically multiple of nine we start again from one okay so you can see from here to this point okay we have a sum as basically you can say one two three four five six seven eight and after that we get a nine as a multiple of nine okay now if you again see 18 is also a multiple of nine okay so after this you again get the number by one two sorry this is three so as you can see and if you see in the 27 also after 27 we again get the number as one two three and four similarly it's going on like after this nine also you can see in 10 11 12 so we are getting the sum as 1 2 okay so what we observe is basically if your number is modulus 9 of 0 okay equal to 0 if it is directly basically multiple of 9 you just return the 9 as the output okay so if you can see for 27 we have 9 for 18 we again have nine okay now let's take another number let's take 14 okay so if we do 14 mode 9 this is basically if what else we do if it is not divisible just to give the remainder of this so if you do 14 mode 9 it will give you 5. okay so as you can see we are getting the sum as 5. let's take for this case 29 okay so 29 mode 9 so if you mode this after this you get a reminder as 2 and this is the sum that we are getting okay and there is one exception base case which we need to take is this zero okay because if we do zero mod nine it will give us the zero so we don't need to return nine here we just need to return zero here okay so this will so if we calculate the time complexity for this so this is a constant time complexity and we are not using any loop or recursion so let's write the code for this okay let's write the code so what we will do we will just to return we will check if number mod 9 equal to 0 then just return the 9 otherwise return num mode 9 okay uh and what will be our base case so if number is equal to 0 then just return zero okay now let's run the code and see okay so as our code is accepted let's submit it let's see so this is also submitted so thank you for watching my video
Add Digits
add-digits
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. **Example 1:** **Input:** num = 38 **Output:** 2 **Explanation:** The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. **Example 2:** **Input:** num = 0 **Output:** 0 **Constraints:** * `0 <= num <= 231 - 1` **Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
Math,Simulation,Number Theory
Easy
202,1082,2076,2264
62
hey everyone in this video we are going to look at the unique path problem in lead code so what we are given is a MN to n grid and the question is there's a robot which is at the top left corner and there's a destination which is at the bottom right corner and we have to return all the possible unique paths through which this robot can reach up to this bottom right Finish Line so and the condition is that it can only move either to the downside or to the right side we have to return how many unique paths are there to reach this particular point so they can be many so if they if we start from here we can uh straight go here then downward here or we can go downward here then straightforward to the Face line so let's see how we can do it okay so let's say we added this point and uh we need to move to this position so there is only one single path to do so which is to move in this direction so we'll just move here so there is only one unique path now if we go talk about from the here to here there's still only single one path we have to go from here to here it is single path only so here also it will be one similarly for three similarly for the First Column as well so if you want to reach here to here there's only one single part to go down one step so here it will be one and similarly for two it will be one now comes the rest of the parts so if you want to come to this particular position there are two ways to reach here either we can come here and then to this particular point or we can get here and then to this particular point so there are two ways to reach this particular point similarly if we come to this point what we are seeing here actually three different points to reach this particular to this to reach this particular point so what are the so one two and three second one is one two and three and uh the third one is one this one two and then three so in total there are three points to detail so we can see a pattern here so what we can say to reach to a particular one is the sum of uh unique Parts on the top side and on the left side so if we use the same Approach at this particular point so there will be two plus one three previous to each here if we go here then there will be four ways to reach here and if you go to this point so there are six ways to reach here and here we have 10 ways to reach the time complexity for this solution will be uh o of M into n as we are Loop creating a 2d array and looping through it same for the space complexity it will be of M into n so let's dive into the code and let's see how we can do it okay so first we need to create our 2D array so let's name it path we'll use the fill method to create this array and for each index we will put null value in it now for the columns.map cool so this will be our 2D array next we need to insert one in the uh first row and First Column because to reach from here to Here There Will there is only one single path and similarly for the first row if we want to reach to any particular point there is one single part to move in a straight line okay so for that let's start right up our Loop at I equals to 0 Y is less than m I plus and for path to I at 0 it'll be one similarly Outlet I equals to zero I is less than n and I plus perfect zero comma zero I will be one okay so we have created our 2D array and the first row and First Column contains one now comes to the rest of the part of the array so we'll write we need to write two for Loops for that so let I equals to 1 because uh zeroth index already we know all the answer already for the zeroth index so that's why we are starting from one foreign what will be the value it will be the sum of the value on above it and the value left to it so for the value above it we'll do I minus 1 at J and for value left to it will do path I comma J minus 1 okay now let's get out of the for Loop and return the value at the M minus 1 and N minus 1 position so it will be return birth and minus 1 and N minus 1. okay so if you run it yep it's working let's submit it cool so it's working so that was all for this video thank you for watching
Unique Paths
unique-paths
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The test cases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** m = 3, n = 7 **Output:** 28 **Example 2:** **Input:** m = 3, n = 2 **Output:** 3 **Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down **Constraints:** * `1 <= m, n <= 100`
null
Math,Dynamic Programming,Combinatorics
Medium
63,64,174,2192
1,897
hello everyone today we are going to discuss the problem redistribute characters to make all strings equal okay so the problem statement says you are given an array of strings so let's see the words this is our array of strings AB BC a BC and BC it asks us to perform this operation like pick any two distinct indices I and J so basically take any of these two words and move any character from one word to other word okay we can do this any number of times to any two indices and we have to return true if we can make every string in the word equal okay it means let's see this is ABC this is double ABC this is BC we take these two indices and move this a from here to here and then we will see ABC ab ABC everything will be ABC and all are equal so the answer is returned as true another example if you see this is AB this is a there is no way we can move elements from one to other and make all the elements here equal so there is no way we can do that if suppose we had another B here like a b and a then we would have moved one b and the answer would be true but for this case the answer is false so what we can do is it's easy like it's tagged as easy and it's uh code is also easy the logic is also easy let's see what we can do is we can just keep the count of all the characters in all the words okay and we will see this case check if this a has occurred three times only then it can be distributed like n if n is the size of the words then if the if any character has occurred n number of times or a multiple of n number of times only then it is possible to distribute it in all the words if it is not n or not a multiple of n then in that case it is just false it's straight away false otherwise it is true okay then let's start writing our code it's a pretty simple code I will just maintain a count array of size 26 why size 26 because if we see here we have words I consisting of only lowercase English letters we don't need to use a map here because we know that size is constant there are 26 English letters only Okay so it is equals to zero and we'll iterate over for auto ENT I over words and we will see for auto and per J over I and count of J minus character a is Plus+ and what we can do now is we can Plus+ and what we can do now is we can Plus+ and what we can do now is we can calculate the size of word okay and then we iterate over Auto ENT I over count array and we will check the account what we have to do is if it is not a multiple of n so what we can do is we can check first of all it should not be zero as well if it is zero then there is no contribution there is no point of moving anything here and there so if I not equal to zero and I mod n if I is not equal to zero and I mod n is not zero means I mod is something other than zero then in that case just return false otherwise just return true in all other cases the answer will be true if this is the case which can make it false like it is not a multiple the count is not a multiple of n so this should pass all the test gues and Yep this passed so that's all for this video thank you for watching please remember to like share and subscribe and I will see you in the next one
Redistribute Characters to Make All Strings Equal
maximize-palindrome-length-from-subsequences
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_. **Example 1:** **Input:** words = \[ "abc ", "aabc ", "bc "\] **Output:** true **Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ". All the strings are now equal to "abc ", so return `true`. **Example 2:** **Input:** words = \[ "ab ", "a "\] **Output:** false **Explanation:** It is impossible to make all the strings equal using the operation. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
String,Dynamic Programming
Hard
516
437
in this video we will solve path sum version 3 problem and it's one of the favorite interview questions asked by amazon so here we are given a binary tree and we have to find different paths just count of paths and not the actual paths which sum to a given value and the condition is that it should not start from root or it's not mandatory that it starts from root it can start from anywhere below root also or including root also both and it need not finish at the leaf so it can start somewhere in the middle and end somewhere before reaching the leaf so that's fine only thing is that we can only go downwards it's not that some part we include here and some part will include here so the path should not be like this which spreads from left going through root till right so there will be one starting node and from there we will always come down so it may be like this not branches so if we come down from here and here also then this will be branched this will not be a path so let's see how we can find that we will be given some target sum and the sum of that path should be nodes on the path should be equal to that target so here the sum is 8 and we have 10 here so if you see here you see that 5 3 this is one path which sum is 8 then we have this 5 2 and 1 if you sum them again it's eight similarly if you sum this minus three and eleven again it's eight so even negative values are there so uh there are three paths so in this case we will return three now uh how did we arrive at these solutions so what are the solutions we have 5 3 then we have 5 2 1 and we have minus 3 11. so there are two things in one case we have to look for path which includes root so if we include root in the path then the remaining sum will be uh 8 minus the current value that is minus 2 and negative is allowed since the nodes can be negative so if it goes negative it does not mean that we cannot find any path below it so we can find so case one we have to look for all the paths which including root this is case one and there can be case two where root is not included so what will happen in this case sum is updated so in this case sum is updated to sum minus root dot val and in this case sum remains same it's not changed at all since we have not included the root we are explicitly dividing it into two scenarios in one case we are including the root and trying to find the remaining sum below it in other case we are not including it at all so we will try to find the exact same sum in just this part left sub tree and right subtree so this is the difference of in one case sum is reduced or may be increased if this value was negative in other case it remains same so we need a way to distinguish between these two sums so we will have a main function let's call it path sum and it takes root and sum and now we have to divide it into two parts case one and case two so let's call them f1 and f2 in one case we will pass the sum so let's pass the sum in both of those and then while defining them we will differentiate so in one case we will calculate f1 root not left and then pass the exact sum plus root dot write and exact sum so in this function call sum never changes so this is the case where we are excluding the root and trying to find the exact sum in its sub trees so this will be done by f1 we can use path sum as one of these f1 or f2 so we will make the changes in the code so this takes care of one case then the other case is we have to include the current value and pass the remaining sum so the job of that function will be to always include the current value since breaks are not allowed so you include that and pass the remaining sum to children and there we should not mix the two things in this case it's not that we have passed let's say here we had 8 and this value was 2 so we passed 6 here as the sum the job of this function is to find a path of length 6 so in this case we have to always include this value it's not that we did not include that and here we found a path 6 and we returned its count so this 2 and this 6 cannot be included so one function's job is to always include the current value and pass the remaining value we cannot mix the two functions so this f2 what it will do uh it will include the current value so it will call f2 root dot left and sum minus root naught val plus f 2 root dot write sum minus root not val so this is the second case so the way f1 and f2 are defined is different so we can also use the original function as f1 and here what we will do so you should be convinced that this should work if we divide it separately into f1 and f2 and what we do from path sum is that we simply return f1 root sum plus f2 root sum then f1 and f2 handle it differently in one case it always excludes in other case it includes ah so in this case what we will do we can define it like this so in this case we also have to look if roots value is equal to sum so we had been including a few nodes before it and now we are here at this value let's say and the remaining sum was 3 and before it we had sum minus 3 so we had to find a path of length 3 and this value itself is 3 so we increment the result count by 1. so while returning we can add one to it so this is one more thing that we need to take care and in both these functions if root is null we return zero so in path sum we can write path sum so here path sum will act as f1 or left sum plus path sum right sum plus whatever is f2 so pass root and sum so it will start including root and passing the remaining values so this would be our complete function so let's write this in c plus java and python so i have pretty much covered everything what's given here except for this and this we don't need for our case what's the number of nodes we will not be writing anything specific to this so if root is null return 0 else return path sum the same sum we are excluding it and let's define the other function also so if this is the function where we are always including the current value and then proceeding below so if at any node we reach a node where the required sum below it including the current node is same as sum then we increment the result else we add to the result so we have not reached the sum so whether we have reached the sum or not if we have already reached the sum then we will pass 0 below it since 0 is also possible there can be positive and negative so we just increment root left and sum minus root val and the same thing for write and finally we return the result so we pass the same sum and try to find the sum in the left so this will do that thing then this function takes care of including the root and everything below it and then the same thing for write and the solution is accepted and we are right here so we are right here in the top zone if you try a few times i'm pretty sure you can reach the top also so let's write this in java and the java solution is also accepted and here we are slightly around this peak so there are a few distributions and we are in this distribution now let's write this in python so and the python solution is also accepted so what is the time complexity here if you see we are in one case we are not including it and then calling it recursively on left and same on right so that will traverse the complete tree and we have another function where we include this and again uh call it recursively on left and right so we are doing two traversal of this tree so it's off in and if you look at the space complexity then we can have in worst case a long tree and all the nodes are in the stack function stack so if you count that function stack as the space then that will be o of n so time is definitely often it's in fact heat often but space if you count the function stack space then it can go up too often otherwise if you don't count it you are only looking for auxiliary space then we are not using too many variables so it should be of one in that case
Path Sum III
path-sum-iii
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). **Example 1:** **Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8 **Output:** 3 **Explanation:** The paths that sum to 8 are shown. **Example 2:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** 3 **Constraints:** * The number of nodes in the tree is in the range `[0, 1000]`. * `-109 <= Node.val <= 109` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
112,113,666,687
931
hey everybody this is Larry this is day 13 I think of the legal daily challenge hit the like button hit the Subscribe button German Discord let me know what you think about today's Farm 931 minimum falling path sum so given an N by n Matrix return the minimum some of the following path the next one that's either direct the below or directly left or right okay so you could do this recursively you can do this um you know uh quote unquote bottoms up or just iteratively really because I think technically is still it's hard to say bottoms up when you're flying but I guess you can also do it in the other way because in this problem I believe this for this poem is um it is symmetric right meaning that you know minimum flowing path is the same as minimum wising path from the bottom uh one cool thing about this that you might not know uh is that um just I mean this may seem trivial now in a sense that if you've done enough dynamic programming problems and stuff like that um it's just like another thing right like Hey Okay um it's just another um yeah it's just another thing that you do and you try to minimum a path on a matrix of numbers right but actually when it the first time I've heard of this or at least someone's similar about this and it was kind of cool because there was um it was something that came up and I'm sorry if I'm telling a little bit of a story but hopefully you know if you could fast forward if you like but what I was going to say is that I remember there was a paper in the late 2000s or 2000 and knots or whatever like 2008 2009 maybe uh maybe I got that year wrong so don't judge me for it I don't all these years blend together now but uh but and at that time for me anyway I you know I've known a lot about dynamic programming and I don't remember programming um you know it has a very mathematical background meaning that you know um for example they use it to calculate the expected value of you know a baseball and like the state and stuff like that a lot of this Sports analysis or analytical sports or kind of you know the one of the first things is assuming and figuring out States and then mapping those states to win probability and accelerate right things that we probably take for granted now right when you look pull up you know anything there's you know there's some like thing telling you like oh uh you know Argentina has a 60 chance of winning tomorrow or something like this right also let me know in the comments what World Cup team that's left that you're rooting for if you're paying attention to this part of the story um uh yeah what I was going to say about this problem is that if it's not quite related but for dynamic programming it is related which is that if you think about instead of a matrix of numbers um or if you think about Matrix of numbers some things are just a matrix of numbers right and when I'm and the example that I am thinking in my head right now is images um images you can think about as um as a you know a way of a matrixes of numbers containing three or four values right the red green and blue and maybe Alpha um as the alpha transparency and maybe some other stuff that's like you know function of something but those are like the maybe the base components that comes up a lot and you know this is stuff that uh something say Photoshop is based off and the cool idea behind or one cool idea that I remember very rarely vividly is around um content aware resizing yeah content we're resizing right meaning that you know for a long time if you resize you know let's say you have a box this big and then you resize it everything just goes you know left to right uh everything just scales you know the Riff rise uh or height wise it just scales to some uh constant um multiple Factor right meaning that you know you're divided by or you multiply by like 60 and you want to make a 60 smaller and so forth right you know I mean I think you've removed that and the math is very easy right it's just you know uh um a scaling transformation and it's very easy to do but coming back and we're at five minutes of story time uh how is what you know what relates to the story right what or what relates to this poem well the thing that relates to this poem is that um I think this paper about content of where resizing was just like okay what if instead of doing this like ugly thing where you know you shrink and if things get squished and you know you have to dance around to get it right what if on resizing you just remove the least interesting path right and what does that mean by least interesting path so that's basically the idea right meaningful and I don't really have examples because like this is not my head everything I do usually is live and that's like I don't know I the power ran out or something but um but yeah the least interesting path for example if you have I don't know a picture of Larry like with a and a green background or not Greenback but just like me on a beach say right um if you want to remove to say let's say you want to remove one pixel line right from anywhere on the thing um if you do it naively maybe you'll be you know remove part of Larry's face which would make me very sad because I like my face as my money maker right haha no but you may also imagine that instead of removing one line like that and it a least interesting path may be like okay we move something from the sky we move something in the background from the you know like around Larry's body and it doesn't have to be a straight line it could be a jaggedly line but just around Larry's body right and then now you can maybe you know squish it by 10 pixels and you remove 10 inches uh 10 boring lines if you will right um so that's basically how content aware resizing works is that it tries to calculate the least interesting path and as it turns out the least interesting path of well I mean obviously there's a lot of different ways to Define what's interesting and what's not and obviously there's autistic interpretation etc and if you looked at my Instagram uh which you know in the link below you can see some of my pictures and my interpretation of what a good image is um you may disagree that's fine but what I was but basically it's about the minimum minimization of basically you're trying to find a path from the top Edge to the bottom Edge if you're trying to remove a vertical Edge uh that is the least path and it's and the cost of the path is the Delta between adjacent values right so it's not quite the same as this problem I guess because you're trying to find the minimum sum but you for example if you're going from black to Black you know that's not that as interesting because the colors are you know very similar wherever you have gone from like black to white there's a huge contrast so it's maybe more likely to be interesting of course there are other functions that are similar maybe like you look at instead of just looking at the two cells that you're removing maybe look at like a uh an adjacent ones and then there's some convolutions of values and they're more mathematical but when it comes down to it is just a minimum path from the top to the bottom given some cost function and you're trying to minimize it right so that's basically the cool idea that you know uh I don't know I just feel like maybe today was a little bit of a story time uh so you know we're at about eight minutes of story time hopefully that's interesting but it's also because I wanted to provide you know um you know as a geek as a nerd that I am uh you know a very common thing that people say is like okay but am I actually gonna use this in real life or where does it come up in real life right and this one was a really like I don't know like I said like that I was gonna say 10 years ago but doing the math is I guess it's actually closer to 15 years ago right so 15 years ago it's like a Josh ago or like a long time ago right so I don't know so maybe to you things that are amazing to me may not be amazing to you but these are things that you know when you have the touring you can think about it in novel ways and kind of connecting different places and you know these are just tools right tools are dead you're presumably alive and that's your open AI watching my video um so you know there's always uh one for creativity and uh yeah and just like figure things out all right actually start at The Forum like I said hopefully uh probably have a couple of videos on this so maybe it's uh you know whatever but uh but yeah but this is just dynamic programming from the band I mean yeah I mean it is shortest path in uh in a way because minimum sum is in a way to show this path you just have to Define your edges dynamic programming of course it's the same idea um but yeah okay so the one thing that I always like to do at least when I'm teaching is to kind of Define uh well let me just set the size of the things first but and then we could set a DP Matrix I know that you could also if you're uh you know what I should say you can reuse uh The Matrix and then do stuff on top of it but and I just like to be a little bit more explicit um and then the idea here is that DP of IJ is equal to the minimum sum of any following path that Force here ends here right something like that so that's basically now that we Define it then we can kind of you know set the base case is just the first row I believe so now for I and range of uh well I guess this n by n so it doesn't really matter but which it should it I mean it doesn't matter if you make a mistake until it does so I still try to get it right um so yes I as you go to Matrix of 0i right and then now we have for each row and we start at Row one right that's why I don't know but yeah DP of i j is equal to um I'm just trying to think about the best way to write it that's a uh mostly because you're minimizing like three numbers right so yeah so for each cell it can come from the top uh you know vertical or the two diagonals that's pretty much it um okay maybe I just do something like v as you go to Infinity did I submit by accident why is there a shortcut for submission I don't need to save time I think I did submit by accident because I think I've I think I will come in and I press enter add a command enter option enter something like this but I submitted by accident I don't know what to say um yeah so then here we are you girls so uh so okay I guess this doesn't have to be Infinity actually because there's always one directly on top so let's just say this is I minus one J um if um J minus one is greater than zero V is equal to Min of t uh v d p i minus one J minus one can't believe I submit by accident though I mean why is that necessary yeah but and then this is D this plus the Matrix I have Jade which you can avoid and then now we want the minimum sum so the minimum sum is going to be on the last um last row so we just return minivity sub uh or minus one oh whoops where did that I come from looks good let's give it a submit unless I feel like zero low or something yeah a lot of story time and I got a wrong answer because I hit a shortcut that really should not be there is no way to turn it off like okay oh there you go I could turn it off okay so at least I fixed that okay is there any other settings that I need to do I guess that's the only that wasn't even the setting I turn it off I feel a little bit happier okay because that cost me I mean at least that it cost me a submission Now versus on like a contest but yeah so this is as you can see this is r and C time uh because basically in a greedy way we just take the best the minimum um some of any path that force in the last uh an adjacent ones on the last row and yeah um yeah as you can see this is of our time C uh both in time and space so yeah that's what I have for this one I don't think I'm gonna do it from this question today because I got in a little bit later so um yeah that's what I have for now let me know what you think stay good stay healthy take your mental health I'll see y'all later and take care bye
Minimum Falling Path Sum
maximum-frequency-stack
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`. **Example 1:** **Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\] **Output:** 13 **Explanation:** There are two falling paths with a minimum sum as shown. **Example 2:** **Input:** matrix = \[\[-19,57\],\[-40,-5\]\] **Output:** -59 **Explanation:** The falling path with a minimum sum is shown. **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 100` * `-100 <= matrix[i][j] <= 100`
null
Hash Table,Stack,Design,Ordered Set
Hard
null
34
Hello gas myself Amrita welcome back to our channel technosis video c are going to discuss lead code problem number 34 date is to find d first and last position of element in sorted are so let's get started let's first understand d problem given and are of inteasers namas Sorted in non decreasing order find d starting and ending position of given target value so basically c will be given when are date is named and when target value will be given c need to find this particular target value in the are and c need to return d Starting and ending position of this target value so every you can see target is 8 in d input are you can see d at this d position three and four so d output should be three four and if target is not found in d are you Need you write -1 -1 so and another example you can see you write -1 -1 so and another example you can see you write -1 -1 so and another example you can see date is one and the target value is 6 but 6 is not found in this particular are so you need return -1 -1 are so you need return -1 -1 are so you need return -1 -1 and you must write an algorithm with o of people run time complexity so let's first understand d approach to solve this problem then c will write as solution for it so let's take d se are c have names are and d values ​​are five seven at and d values ​​are five seven at and d values ​​are five seven at and tel and d target values ​​8 so nine First c need you find this tel and d target values ​​8 so nine First c need you find this tel and d target values ​​8 so nine First c need you find this target value in this particular are and c need you return d starting and ending position of d target values ​​every you can see zero thundex 1 target values ​​every you can see zero thundex 1 target values ​​every you can see zero thundex 1 2 3 4 5 and target value come is present it third and d fourth index so If you need to return the output one three come 4 so basically you need to return the output in the are format so let's first take a new are let's and will take are of length because you need to return the output in the are always so first What are you going to do in the first step Are you going to search for this particular element using loop so when i is zero so see have you check 5 = 8 date is false then i = 1 you check 5 = 8 date is false then i = 1 you check 5 = 8 date is false then i = 1 7 = 8 falls i = 2 7 = 8 date is also 7 = 8 falls i = 2 7 = 8 date is also 7 = 8 falls i = 2 7 = 8 date is also false when i = 3 8 = 8 so this is true false when i = 3 8 = 8 so this is true false when i = 3 8 = 8 so this is true so date mains are first position i is three so see can say i in this particular are so see go the starting position of d target value in this are so in d Next step nine you need to search for the end index date mains force so nine you go your first position date is 3 nine this is un sorted are so you find thing date if it is there come d third position so if it exists it should be There right d next position itself so you can directly say for but date would spread in van case date is when you have only van element let's say your checking for d target value one at and you have van are with only van element date is a so When you go your first position you will clear zero in your array so you can say next position dat is van in this case but spread right because you have only van element so when you found your first position what you need do you need you check Weather there is next element in date particular are date min you can check weather i is less then length of d are if date is true then you can check weather i + 1 = target if both these conditions are true then you can weather i + 1 = target if both these conditions are true then you can weather i + 1 = target if both these conditions are true then you can increment your i and Se Date I In This Are As D Ending Position When This Case When You Saved 3 In D Starting Position And You Check D Weather I + 1 = Target And There Is Next Element + 1 = Target And There Is Next Element + 1 = Target And There Is Next Element Date Condition Becomes True And You Check D Weather Date Element Is Equal To Target date is also true so you increment your i date mains i become 4 and you found your ending index nine you will say four in d output edit and you will break d loop here go your last position so date mains see just need tu do tu Steps first when you find d starting in dicks date it you will run you are loop from d zero eight element till d last element until you found your target value once you found your target value you will say date particular index in your output are give you Will check there is next element If next element is existing you will check whether date next element is equals tu target date is also true you will just increment your i and say date in your output are ending position so nine let's try this solution For it so let's implement D method when we start it and it is going to be written and are so it should be search range and it should expect you inputs when we are and where we are target value so this target value should be Off wait type nine what was the first step c need tu run d loop but before running d loop let's take one are tu se de output so let's take a are and it should be of tu because they are going tu se only tu index date This starting position of d target value and d ending position so it would be of length tu den aate first c can initialise both d values ​​a - 1 because in case i get d values ​​a - 1 because in case i get d values ​​a - 1 because in case i get values ​​not found then c need tu values ​​not found then c need tu values ​​not found then c need tu return mines van kama -1 nine lets try return mines van kama -1 nine lets try return mines van kama -1 nine lets try are low date would start from d zero index til d length of the are i + + end index til d length of the are i + + end index til d length of the are i + + end let you need tu check weather particular element is equals tu target value so if number of i = target let you go your number of i = target let you go your number of i = target let you go your first index date is starting position So you can say a r of zero is equals to i and then you need to check there is next element date is next element exists weather i &lt; length of the are and exists weather i &lt; length of the are and exists weather i &lt; length of the are and also you need to check weather there is next element date is i + 1 = element date is i + 1 = element date is i + 1 = value if both d cases are true then you can increment your i and say date in d first position of the output are date min you found your end index today well and if you found her end index today well you can break d loop and you Can retain your are nine let's test it with d example given in d problem let's call function date is search range by name and target value let's nationalize rooms are date is 5788 10 and d target values ​​should be a 5788 10 and d target values ​​should be a 5788 10 and d target values ​​should be a let's write are print statement to check D output system dot out dot print and nine sci c r returning are so c need tu write arrest dot tu string tu c the output let's run d program and cd output so d output is 34 let's test it with another examples let's se r target Element is six nine six is ​​not Element is six nine six is ​​not Element is six nine six is ​​not existing in this particular are so d output should be -1 -1 so you can see d output should be -1 -1 so you can see d output should be -1 -1 so you can see d output test -1 -1 Let's test it with same example let's say output test -1 -1 Let's test it with same example let's say output test -1 -1 Let's test it with same example let's say c don't have other element and date particular are And See Are Searching For One Element And It Should Return -1 -1 So You Can See Her - 1 - 1 I Hope You Understand This Return -1 -1 So You Can See Her - 1 - 1 I Hope You Understand This Return -1 -1 So You Can See Her - 1 - 1 I Hope You Understand This Solution If You Have Other Questions Other Doubts Please Let Me Know In This Common Section Please Don't Forget To Like Share and Subscribe Channel Also Provide Your Feedback in Comment Section You Can Also Follow Me on My LinkedIn Profile I Mention Link in Description Box Thank You So Much for Watching
Find First and Last Position of Element in Sorted Array
find-first-and-last-position-of-element-in-sorted-array
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value. If `target` is not found in the array, return `[-1, -1]`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[5,7,7,8,8,10\], target = 8 **Output:** \[3,4\] **Example 2:** **Input:** nums = \[5,7,7,8,8,10\], target = 6 **Output:** \[-1,-1\] **Example 3:** **Input:** nums = \[\], target = 0 **Output:** \[-1,-1\] **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `nums` is a non-decreasing array. * `-109 <= target <= 109`
null
Array,Binary Search
Medium
278,2165,2210
73
hey everybody this is larry this is day 13 of the august eco day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem and so forth so i one random note before i start is that today's august 13th 2021 i started on april 1st so that means that this is my 500th video because if you include wednesday and including august 13th i have 500 days so this is my 500 consecutive video i don't know what to make of that but yay celebration 500 straight lead code daily challenge i don't know what to make of that still but uh hope you enjoyed that little tidbit anyway today's problem is set matrix zeros so given m by x matrix and element zero said it's entirely designed return matrix you must do it in place okay so yeah so i think the r um let's see right um yeah the obvious thing is that for every zero you know scan left and swing up left right up down and then set them all to zero if you do it naively it's going to be quadratic where quadratic means that it is m squared times n squared which is a little bit too slow um and well in this case you could do it in place you can do an m plus n space trivially by looking at up um by keeping track of the rows and the columns um for example you can you do one pass going okay we set column one and rows one um to zeros and then you do another pass later to just uh just check whether that's true and then set that row and column to zero um so you can do that can you devise a constant space solution to be honest i don't know if this is one of those problems where it is like weird in that you do some weird things to like because what i want to say is that there are a couple of things that are kind of uh constant space but not really because you do it in place which has the actual implementation of constant space but not in spirit and what i mean by that is that you can for example modify um well in this case this is the case but you can for example especially in python but you could modify one of the fields to kind of you know you basically embed a flag into another field but i feel like that's like kind of really silly maybe um so i don't know that's what they mean um there are a couple ways you can do that um you can maybe do either a checksum and then add something or something like that and then you know um i don't know there are a lot of ways you can do it but um but i don't know if that's what they mean by the constant space solution so uh or is there a real constant space so those are kind of the things that are going from my mind because real constant space i mean like just have variables and that's what you use to kind of keep track of stuff but we're like according to a fake constant space is like if i manipulate it uh this array so that you know like i for example i add every number by i don't know 10 billion which is all bigger than this range uh or like you know for votes that i that um for rows that contain zeros i added to a billion or 10 billion or something big right like does that kind of constant space i guess technically because you're manipulating the in place away but also maybe now because you know it's just like a really weird thing to uh operation to do so i don't know if i have that answer for this one maybe we can kind of look at the solution for or at least for a queen constant space um but let's think about it a second right um yeah i don't know i mean i'm thinking about some way of using prefix sum as well um into the array natively but i don't know but like i said all those ways are kind of like not really constant right they're fake constants like if i'm doing some weird thing where i don't know i'm effectively throwing a boolean away but within the same matrix then you know and it's not really the same um yeah i don't know let's see if there's a hint okay so that's what i was saying right uh yeah i don't know yeah i don't think that's uh that's just like a sloppy messy unmaintainable code so that's why that's a solution that i don't know if i would consider to be correct um yeah well the other one yeah okay so my i'm not going to implement this because it's not really clean code to be honest um but i mean i meant to constant quote-unquote i mean i meant to constant quote-unquote i mean i meant to constant quote-unquote constant space one but like i said like i had the idea we talked about it here before we kind of uh looked at the hints so yes i'm gonna do the queen style so yeah i mean i don't um you could do whatever you like if you want to practice you know the thing about these problems is that gives you an opportunity to practice implementing what you feel like you want to practice and get better at so if you want to you know if you want to work on like i for me do not feel like there's any value in it for myself but if you feel like you want to work on this constant uh space implementation feel free to do that so yeah but i am going to do the n plus m solution let me check that this is greater than zero okay because um this only works with them one and zero rows which sometimes is a edge case input that they give you for fun but so i always check but yeah uh okay uh rose is it rolls contains zero maybe that's really way long so i'm just gonna move zero you come um for swoops can spell zero roses but yeah so now you set the entire uh road and column to be true so that you can do another pass later to set it oops basically this is saying is there a row in this column oh sorry is there a row uh sorry given the current position um is there 0 in this row or is there a column in this world if either of these is true which is kind of like the reverse thing of this uh we set it to zero and that's pretty much it because i think that is a better thing to learn as well is that sometimes you have to learn or think about how to solve the problem in a reverse way because here the naive algorithm that you might come up with is okay for each zero that you come across do something where the reverse of that is okay i'm in this position is there a zero in this row right um so something like that whoops how did i man i think i should i was thinking about something else silly but that's fine that's a easy thing okay looks good let's give it a submit yeah so this is going to be linear time because for each cell in the matrix you know we scan over with twice and we're going to be over uh r plus c space because we just have to um two arrays right so less than linear space but not constant space anyway um that's all i have uh happy 500 to me uh if you're watching here um thanks for your support throughout the 500 days you know here or whenever and also hopefully into the future i'm still going to keep going so stay good stay healthy to good mental health i'll see you later bye uh yeah actually hopefully you're still watching here i just want to say i admit i was wrong about this one for the constant space solution i thought it was another type of problem where you do embed information into a matrix but or into another cell and then kind of like you know like a flag but not really so it's kind of weird but actually um what you wanted to do is um you know think about the solution i was like oh actually uh actually it's more like a because you're sending it to zero it's almost like a pre-calculation of like a pre-calculation of like a pre-calculation of um pre-cognitive pre-cognitive pre-cognitive uh like a premature um cascading type flag uh of what you were gonna do in the future anyway and basically what i came up with is um is that okay if an element is zero we actually set the first element to zero and the first uh first row of that uh cell 0 and first column of that um that's our first row and the first column of elements is zero and that's okay because we were going to change them to zeros anyway and then later um we will basically just adjust the rest of the left um the rest of the columns and the rows to zero um of course the tricky thing is the cell zero because on this at that corner um you don't well we process it last because you don't want to change order the first row and the first column is zero because then otherwise you will basically change the entire uh matrix to zero right so that's basically why we do it last and then in this case if you have zero then you don't know whether um you're saying that's the first row is zero uh zero or the first column is zero so that's why we keep track of first row independently so then we in this case matrix zero means first column is or um columns contain zero and should be zero so yeah so basically this is the solution i would have um it's actually not that bad but once the definition is a little bit different from the r plus c solution but this is now over one space again this is going to be linear because you do need to populate it and you do look at each cell at least once so that's going to be linear but in terms of space we only have three extra variables so it's all one space i do retract what i said earlier about this one being a little bit weird um or yeah because i think i was just thinking about a different solution but this is kind of clever actually but it's very limited and very um very specific and very tailored to this problems i don't know how helpful this is anyway that's all i have for this one for reals this time uh thanks for your support uh hit the like button the subscribe button join me on discord go 500 uh and 500 on a weird video but yeah stay good stay healthy take a mental health i'll see you later bye
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
710
hey what's up guys babybear4812 coming at you one more time problem 710 today random pick with blacklist that is uh it's currently being asked by two sigma if i remember correctly uh two sigma is a new york city kind of ai based hedge fund uh they do a lot of really cool work i'd check them out if i was you and uh this is one of the problems they've been asking recently it's a really good problem it came in as a request from one of our viewers so i figured we'd uh we'd cover it if you have any requests yourself my contact is down below as always now we're in this problem we're given a blacklist b containing unique integers from 0 to n 0 being inclusive and being not inclusive and we need to write a function to return a uniform random integer from o n which is not in b so return a number that's not in the blacklist uh optimizes such that call such optimizes such that it minimizes the call to systemsmath.random so call that call to systemsmath.random so call that call to systemsmath.random so call that function as little as possible um and you know they give us some sort of really high bounds i know this might be a billion or so i didn't count doesn't really matter we'll make it optimal and so the kind of the interesting thing about this problem is that there are a few ways to tackle it uh the one brute force one that might come to mind is just to create a white list that's what i did first and i kind of created a set um of all the numbers from zero to n and then just backed out the ones that are in the black though so i walk through it iteratively um that's okay conceptually it works with numbers this big though um and you know black lists of that size you'll run into memory issues so right off the bat that's something worth mentioning in your interview sorry but not something that would be worth pursuing as an option another example of how i found to tackle this was kind of sorting the blacklist and then using a modified binary search to kind of look through the numbers um i say that only in passing because the solution is out there i didn't quite understand it myself so it uh it would have been very dishonest to me to try to cover it for you guys uh there is a third solution though that's really clever and it involves an algorithm that quite frankly i haven't really applied anywhere else apart from this problem so i've done my best to kind of explain it in a way that makes it still transferable to other problems although it might to some extent kind of be localized to a problem such as this one quite uniquely but nevertheless we'll let's look through an example and see what we can do here um i do also apologize if you're hearing a bit of background noise today we have a pretty gnarly windstorm in toronto for whatever reason so it's uh you might hear that swishing around now in the example we're looking at we're going to take n is six meaning that we can have all the numbers from zero to five inclusive and let's say that our black list includes the numbers zero two and three in the form of a list and so what i've done is i've kind of colored those in black with my fine art skills and then you know written in the zero two and three in white ink the essence this how to solve this problem really efficiently is actually going to be in creating some form of a white list so we kind of mentioned that in the brute force approach it will still come in some form but maybe not in an obvious form in particular we're going to make the function such that we are only ever going to make one call to random every single time the pick function is called so maybe just to be clear here we need to initialize some object with a certain property with this blacklist and like whitelist maybe and every time pick is called we need to pick an item that's not on that blacklist the way we're going to do that is going to be through a pretty clever way of mapping numbers and in particular the way we're going to map these numbers is such that certain numbers on the blacklist if that number is rolled if that number is randomly generated will actually map to a number that's on the whitelist okay so this is where we're going to get where we're going to have to get a bit clever with this algorithm first thing that we're going to do is we're going to need to create so we're going to need to create a white list and what i'll do is i'm going to i'm just going to call it temporary white list and i'm going to make it a set and this set is going to include all of the numbers that are in the range uh from let me write this out here so it'll be from uh n minus length of b all the way until n so what do i mean by that i have six items here and i've got three items in the um excuse me in the actual uh blacklist so imagine kind of splitting this down here down the middle in this case it's down the middle it doesn't necessarily need to be i'm going to be looking at the upper half here so i'm only almost going to take one category one bucket of these numbers um and use them to start creating a white list and this temporary white list will come into play in just a bit after i loaded and manipulated a bit but what i want to do is want to say kind of from this upper group of numbers which go from um the total number of numbers n minus the length of the benchmark up until n i want to add all of those to a temporary white list and so what i'm going to do in this case those numbers are 3 4 and 5. now these numbers we just looking at this we understand that in our blacklist we've got 0 2 and 3 and so you know 3 in particular right here definitely can't be in our white list of numbers so what are we going to do about that well i need to now start so my first step is kind of create this temporary uh white list my second step is going to be to iterate through the blacklist and pick out all the numbers that are in the temporary wait list that shouldn't be there and the reason we can pick these out nicely here which is why i created this as a set is because we get that constant time lookup so i can iterate through here notice that zero is not in the white list two is not in the white list three is in the white list i'm gonna scrap it okay so once i scrap it our temporary white list will simply look like this it'll look like four n and five and so once i've got this temporary white list created here sorry i'm pulling up my notes kind of um as i speak the part where this is going to get a bit maybe unintuitive is now i'm going to create my formal white list and the way that i'm going to create this form of white list will be a using a dictionary and we're going to map uh map certain blacklist values to non-blacklist non-blacklist non-blacklist values and this is it's one of those questions like i really i sat around for a while to try to figure out what the most intuitive way to explain it would be um so kind of bear with me this might be one of those where you need to re-watch the of those where you need to re-watch the of those where you need to re-watch the video once or twice in order to kind of let it settle in because this is super non-intuitive non-intuitive non-intuitive the way i'm going to create this white list is that i'm going to say for every number within this um for every number within this blacklist if it's part of this kind of lower half this lower bucket of numbers namely if it's less than n minus length of b what i'm going to do is i'm going to add those to dictionary okay and what i'm going to do with that dictionary is i'm going to map it to a number that's on the white list which will actually be in the second half of these buckets so notice that kind of in this first and second half i've got you know in this in the second half i've got four and five which are white list numbers i'm going to need access to those somehow because i want to be able to generate them um and on the left hand side i have this one so fine okay we'll see where that comes into play i'm going to start again or once again iterating through my blacklist so i'm going to check the 0 and i'm going to say the zero fall in this first bucket meaning is it less than n minus length of b yes it does i'm going to add it to my dictionary as the key and as the value so i want to basically say if i roll a zero if i randomly generate a zero instead of returning zero because i can't it's in my blacklist i want to return another number that is in the white list and the numbers that we have so far are four and five again i will adjust this one afterwards so i haven't forgotten about it i'm only looking at the ones that are in that second half of the bucket or the yeah in the second half bucket so i'm using iteration and the code here in python we'll take a look at in a bit i'm going to say let me look at the first item in the set iteratively and that's going to be a 4. so if i roll a 0 i will instead return a 4. now i'm going to look at the two so i'm iterating through the next step of the blacklist is 2 in the first half here is it less than n minus length to be it is so i'm going to add that as a key and i'm going to map it to the next item in my iterable object here which is a set and that's going to map to 5. i'm going to check the 3. is 3 in the first half or is it less than a minus length of b right those two are synonymous uh it's not and so i'm not gonna do anything with it and it just so happens that at that point i'm done i've walked through all of these so what have i actually done here what does this allow me to do like why was this a clever thing to do in order to return the numbers we want why this was clever is because now when in my final step and really this is going to be in the pick function when i generate a random number i'm going to generate a random number between 0 and n minus the length of b non-inclusive right minus the length of non-inclusive right minus the length of non-inclusive right minus the length of b non-inclusive b non-inclusive b non-inclusive meaning i'm going to generate either a zero or a one or a two why if i generate a zero what am i going to return according to my white list here i'm going to return a 4. if i generate a 1 what am i going to return well what we're going to do when we generate this number is we're going to say if it's not the white list in this kind of modified white list we made then it must be legitimate and so maybe the verbiage here i want to make sure that it's not confusing but this white list actually comprises of keys which are on the blacklist and values which are on the white list so if i roll a one and it's not in this object here i'm cool with it means it was never in my blacklist the only items that are here are the items that were on the blacklist uh if i roll a 2 and notice now that 0 1 and 2 sorry 0 1 and 2 are the only numbers that can roll here they're the only numbers in this range then i will return a 5. okay why is this good let's think about what the problem asks we need to return with uniform probability uh any number that's not on the blacklist those numbers are one four and five if i roll a zero i'll return to four if i roll a one it'll return a one if i roll a two it'll return a five each of these has an equal likelihood of being rolled because i'm only rolling numbers from zero to two you may ask yourself then what about this three up here since three is kind of in that second half of the bucket i'm not even going to be generating numbers that are that big to rule right we're only going from zero to n minus length to b which is in this case six minus three which is three non-inclusive which is three non-inclusive which is three non-inclusive meaning zero to two de facto two being inclusive i'm only going to roll numbers from zero to two between zero to two i'm going to return every possible uh number that exists on the actual white list so that white list being one four and five um again i apologize if the verb maybe the nomenclature that i used here is a bit unintuitive i didn't know what else to name it excuse me my nose is itchy um i didn't know what else to name it but i called it whitelist for lack of a better name and what it contains again the keys are items that are in the blacklist and the values are numbers that are in a white list that we're going to map to in case these numbers are rolled so no matter what the kind of the space complexity of this thing will be o b in the worst case scenario the time complexity will also be ob because i'm never doing a longer walk through than a walk through of my um my blacklist and so we've got and kind of ob time ob space solution and when we're rolling this random number and we're deciding to kind of algorithmically roll it in this range we're always going to on our first roll get a number uh that is on the white list that is a permissible number and we're not going to need to call it multiple times over which was one of our criteria uh so i hope that algorithm makes sense if you if it's a little bit confusing watch the video over once or twice uh if it if you know if it's still confusing after that drop a comment down below i'm happy to answer any questions this one was really tricky thankfully the code won't be too difficult but you know nonetheless let's dive into it and see what it'll look like so the uh excuse me again the first thing i'm going to do is just grab this uh grab the end and grab the blacklist and add them to the object so that they're accessible because we will need them later so i'm going to add them as uh as parameters here and what i'll also do is i'm going to create that white list which is going to be a standard dictionary and oops wrong buttons uh that's gonna refer to this dictionary right over here so what i said was you know in our first step we created a bit of a temporary white list here so um i'll call it temp whitelist uh and that's gonna be equal to some set and what we needed to do in here was in the set we began by generating all the numbers from n minus the length of b up to n but not including okay so what i'll say is for some number n in the range of n minus the length of the blacklist all the way up to n again non-inclusive we're going to say again non-inclusive we're going to say again non-inclusive we're going to say temporarywhitelist.add temporarywhitelist.add temporarywhitelist.add that number so we're going to add all those numbers to the set and then the next step was to say let's iterate through the blacklist and take the numbers that shouldn't be in that whitelist and just pop them right out so we'll save for every n in the blacklist and notice i'm not using self here because we do have access to it um i could i don't need to so i did for no particular reason i will say if that number is in the temporary whitelist then we want to remove it so say temporarywhitelist.remove that so say temporarywhitelist.remove that so say temporarywhitelist.remove that number n and so that kind of takes care of the first two steps of our algorithm here if i was to walk through this example at this point our temporary whitelist looks like this and our temporary whitelist is ready to be appended kind of to that true white list where we want these numbers four and five to be mapped to by other numbers from the blacklist that uh that we don't want to return right we don't want to return the zero the two we want to return the four and the five the way we're going to do that is as follows and i'm going to set a variable that's called set iterator and what we're going to do is we're going to create an iterator i believe this is an object in python i believe it's considered an object and we'll create this iterator for the temporary white list now uh before this question i actually i haven't used this function before so i just i learned about it for the first time uh i would look it up if you're unfamiliar with it java's got the same c plus has something similar i believe every language should have something equivalent but what this will allow us to do is to be able to iterate through uh an iterable such as uh such as a set which we otherwise wouldn't really be able to do as it's not indexed and you'll see the reason why here kind of in the next step because what we want to say is again for every number that's in the actual blacklist uh what i'm interested in doing in this step here is to say if it's in the slower half right if it's in this lower app then i want to create a mapping for it so i'm going to see if n is less than n minus the length of the blacklist which has kind of been like our magic number so far i want to take that n number and it's going to be the key and then i want to map it to the next value of this set so right now our set looks like four and five maybe it might look like five and then four right because the numbers get hashed so we don't know what order they keep there we don't keep a strict order we can't index them and that's why the iterable is necessary so what i'm going to do is i'm going to say self.whitelist of n that's going to be self.whitelist of n that's going to be self.whitelist of n that's going to be my key we want to set that to next of set iterator what does this mean this means since we haven't called this next function yet on this iterator it will begin by saying set the key to you know 0 and the value to be four let's pretend that four is kind of the first number it finds in the iterable the next time i walk through this and i call it next on set iterator in the background it kind of has something like the equivalent to a pointer that points at let's say this four and now when i call next on this iterator it will simply jump to the next value that it finds in the set again i can't really walk uh walk through this like i can't keep a pointer on a certain index and then walk through the rest of the set that way in a you know kind of similar to how i would in an array because there's no inherent order that's why this iterator function here was necessary i'd look it up in the python documentation if you're unfamiliar with it because it might be quite useful in excuse me in other work that you'll do in the future and so at this point what we've done is we've actually created uh this white list over here and all we need to do is to say let's create a function that's going to generate a random number from zero to you know n minus the length of the blacklist and then either return that number itself if it's not in here so for example if we generated a one we want to return the one or if we generate a zero or a two we want to return the mapping from that zero or two to an equivalent number or two maybe a corresponding number in the white list the four and the five here could be switched it really doesn't matter um four and five just seem naturally the way to order them given how our brains think again i don't know when the computer hashes these and stores them in memory i don't know which one would come first but it really doesn't matter so i'm going to say that we'll generate some number rand and that'll be called using random.random and called using random.random and called using random.random and the number we want to generate is going between uh going to be between zero and we said uh n or self.n now because we need access n or self.n now because we need access n or self.n now because we need access to it minus the length of the blacklist so self.blacklist so self.blacklist so self.blacklist and now with this rand in function uh this is inclusive so i need to set -1 this is inclusive so i need to set -1 this is inclusive so i need to set -1 here to make sure that i'm grabbing only the numbers from 0 to 2 inclusive and not 0 to 3. okay now that i have this number i'm going to say let me just return uh self.whitelist self.whitelist self.whitelist of rand okay and i'm going to add one more thing here but you know if i get this number and i roll a zero or a two we have no problem here let's say i rolled a one so one isn't in there so if i roll a one and white isn't in that white list mapping i want to return the one so i'm only going to do this uh if brand is in self.whitelist is in self.whitelist is in self.whitelist otherwise i just want to return the number itself right and so just about running out of space here there we go uh you could very much just turn this into two lines so you could say something like if brand in self.whitelist you could if brand in self.whitelist you could if brand in self.whitelist you could return you know self.whitelist ran otherwise you know self.whitelist ran otherwise you know self.whitelist ran otherwise you could just return rand so this is perfectly fine i just for whatever reason i actually don't forget it here i like the ternary statements but in the videos i try to stick to something that's more legible so maybe we can do this like you could put this in an else statement um and maybe that way it'll be like really crystal clear and i'm gonna run this and just make sure i didn't make any silly mistakes and we're good all right so to recap this solution was an o b time and space complexity solution uh it was a toffee with a very specific algorithm that personally i haven't at least encountered in other questions i also this is my first time using this uh this iterable here uh really cool to know really good to learn uh tough problem don't kick yourself if you didn't get it the first time around this i've been sitting on this one for quite a few hours before it started to click and i was able to explain it so take the time view this video back check it over let me know down below if you have any questions and as always i'll see you guys in the next video peace
Random Pick with Blacklist
random-pick-with-blacklist
You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned. Optimize your algorithm such that it minimizes the number of calls to the **built-in** random function of your language. Implement the `Solution` class: * `Solution(int n, int[] blacklist)` Initializes the object with the integer `n` and the blacklisted integers `blacklist`. * `int pick()` Returns a random integer in the range `[0, n - 1]` and not in `blacklist`. **Example 1:** **Input** \[ "Solution ", "pick ", "pick ", "pick ", "pick ", "pick ", "pick ", "pick "\] \[\[7, \[2, 3, 5\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 0, 4, 1, 6, 1, 0, 4\] **Explanation** Solution solution = new Solution(7, \[2, 3, 5\]); solution.pick(); // return 0, any integer from \[0,1,4,6\] should be ok. Note that for every call of pick, // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4). solution.pick(); // return 4 solution.pick(); // return 1 solution.pick(); // return 6 solution.pick(); // return 1 solution.pick(); // return 0 solution.pick(); // return 4 **Constraints:** * `1 <= n <= 109` * `0 <= blacklist.length <= min(105, n - 1)` * `0 <= blacklist[i] < n` * All the values of `blacklist` are **unique**. * At most `2 * 104` calls will be made to `pick`.
null
null
Hard
null
95
hey what's up guys this is john here again so today's daily challenge problem number 95 unique binary search trees number two okay so you're giving like integer and return all this unique binary search trees right which has exactly unknowns for you of unique value from one to n return answer by any other right so this is another tree problem and so for example we have an e is equal to three here right so we have what we have one two three four five we have five unique binary search tree right so the binary search tree is a tree that all the left nodes it's smaller than the root and all the right nodes right sub right nodes right three sub three nodes are greater than root right yeah so i mean to solve the three problem you we always use dfs right and for this one this is another like uh like type of trip problem instead of uh given like a fixed tree it asks us to build some unique trees all the unique trees right so for this one you just remember like template you know we should always do something like this so we're going to be left trees right equals the dfs of some something and then we have right trees right equals the dfs of something and then we're going to do a an acid for loop going to be a four left and left right and then we have a four right in right okay i mean when we have a root right so for each root we have a root cell dot left equals this l equals root dot right equal to this right so that's the basic idea of building all the unique trees right because you know uh we i mean we'll always use this kind of uh like structure to build all the unique trees because you know let's see and since we're using the dfs right so let's say we have a left tree it's going to be like three uh possible left trees and we have uh two possible right trees right obviously we need to try all the combinations so that we can get all the possible trees right so that's why we have a nested photo here to try to combine each of them once right and so for this one you know we uh if we want to use this one and how should we uh divide right how should we do the recursion so we need to we want to build a binary search tree right so which means that you know for example we have one two three four where's four five six seven eight right so for example uh let's say we use this five as a root right so five is the root and we have left trees and we have right subtrees right so for this one the live sub trees will be this one two three and four right so the right subtree will be six seven and eight right so and this one is going to be a recursion right basically we pick one number from any of them right and then we recursively uh split this the remaining parts into left and right because in this case you know since you know let's say assuming at the beginning the list is sorted right so it doesn't really matter which one we pick you know we can guarantee that all the numbers or all the nodes on the left of the current one of the root is smaller than current one and all the nodes on the right side is greater than it so here we can we do the same thing right we so for example we pick three right as a root then we put one and two on the left and we put four on the right so here we can try let's pick six right let's pick six at the right then we have seven eight on the right there's nothing right on the left side right now as you guys can see so basically this is like a recursion plus a for loop right so basically for each of the recursion we try to pick each number as the root and then we will split this number into two parts right so we assign the left one to the left node we send the right one to the right notes and then in the end we're gonna we need to return all the possible trees that root that has this current number as a root right and then we're going to return this one to the upper level right so for example uh so for example we have five let's say this is the left right and this is right okay right so here on the left side we have a bunch of like possible uh sub binary surgery and then on the right side we have also have some bunch of binary surgery like i said then we can utilize that template where we're going to have a nested for loop for both for left and right and then we're going to try uh combine all the possible uh left and right subtree and then we assign this one to five and then we keep going forward until we have reached the very first level okay so that's the basic idea okay let's then start coding we're in the dfs uh dfs and then he we have a numbers right in this case our input is going to be the remaining numbers right that we want to build for uh so in the that's why you know the number is going to be a list of range of one to at the beginning it's n plus one right and then we return the alpha dfs of numbers okay because at the beginning we have all the numbers we're trying to build and here uh we have the answer it's going to be that you're going to be the empty and we try to loop basically we try to pick each number as a root right maybe a length of numbers okay and then we have a left trees right left tree is going to be a dfs of what and then we split this one in into two parts right so remember the left part will be the numbers of this i right and the right parts will be the numbers of i plus one right because we decide to use the i number as a root right and then after having this eleven and the right trees we do our like nasty for loop right in left trees and then for right are in the right trees right so we have current uh let's call it root i think root is better the root is going to be the current node right the numbers of i and then we have the root dot left equals to l root dot right equals to right so keep it uh keep in mind that you cannot move this one out because we need a separate tree for each of the knight that each of these uh nasa for loop that's why we need to create a new root node for each of the possible combination okay so after this one we have that what we have the we need to append this route to the answer right because that's one of the part this is one of the possible uh ways to build uh binary surgery given like these numbers right and in the end we return the answer right and how about the base case right so the base case is selected so basically if now if not num if there's number no numbers here will return none right so where the like for example if we have six seven eight right so for example if we pick six as the as a root right then six is the root and then we have seven and eight on the right side and here we have none right so how can we get none right because in that case you know this one will be empty right that's one that's the base case and we cannot return none why is that because uh the return type for this dfs is a list that's why we that's how we can do a loop here so we need to uh put this 9 into an array here right and that's it i think that's pretty much it is right so if i run it so this should work yeah okay yeah cool there you go right uh you know if you just look at the solution it's pretty straightforward right but if you haven't done similar problems you may have some difficulties uh figuring this out so keep in mind that the key part for all this kind of build all the possible trees problem is this part okay where you split the current uh conditions right or current conditions into two parts where you recursively build left and left trees and right trees and then once you have the left recent right trees you do a full cross join basically right and then for each of the possible combinations you create a new subject you just create a new tree uh respectfully right and then you assign this one to the current answer right and then you return that answer to the upper level so that upper level can use your the result to calculate his possible trees and then for this one i think it's a binary tree that's how we split this one into uh two parts okay 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
Unique Binary Search Trees II
unique-binary-search-trees-ii
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**. **Example 1:** **Input:** n = 3 **Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 8`
null
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
Medium
96,241
153
hello everyone so in this video let us talk about another problem from lead Cod the problem name is find minimum in rotated sorted a okay so if you haven't checked out my video on this problem that is finding out the peak element first please go and check out that particular video it is very helpful and it will make you understand this problem very easily it is in the binary search playlist so go check it out and try to watch the complete playlist it will be very helpful now coming down to this problem it is somewhat related to it but it requires a little much different logic okay uh the overall structure remains same but uh some different uh critical thing is required okay let's not move down to the problem statement first it says that you're supposed you given an array of length and sorted in an ascending order and is rotated Zer one or n times okay so it is rotated as well like initially it was sorted and then it was rotated I'll tell you with some examples as well now uh what rotated means I'll also show you with some example as well uh but you have to find out in that sorted nums array find out the it has all the unique elements that is also given to you have to find out the minimum element inside the array and you have to write down an algorithm that will find out and run it in login whenever I've told you in the previous example as well that whenever see login I generally try to think over in binary search Direction because uh over an array if you find out if you have to search something in login time is better use a b search uh like they can multiple but it's better to think in that particular direction first at least okay now uh let's take some example understand the prom statement and then we'll try to find out some solutions so let's take this example so the thing is that we are given some array uh the aray is let's say uh let's take some example that is let's say sorted it has unique so 1 2 3 four five okay now if I rotate it Rota like put this element to the very back but this element in the very back of the array so it will become like this 2 3 4 5 and 1 now if I rotate it one more time it will become 3 4 5 1 and two and this is the example that is given to you here so it is an array that is rotated two times okay that is given to you now you just have to find out the minimum element of this array if it is a binary search simple binary search problem then uh you could have done it in just login time because you can do B search in login time over a sorted array but it is rotated s it so uh like sorted and then rotate so how can you do that because you cannot directly use bind search here you have to do some technique here so binary search as I've told you always try to converge to a particular point so what you can do here is let's try to draw always try to draw B search and try to find out what is the local minimum maximum that you have to find out here so what you can see here that let's draw it out let's say if the first element is one the next two 3 four 5 six so it is like increasing like this okay like complete increasing but if in the problem that we are given to you that is like this are what it's like this let's say um okay let's draw it like this let's say this is three this is two this is one so it is increasing from three four five and then there's a drop to one and then it is increasing to let's say that's a graph you can see here so what you can see is that there's a graph there's a Minima like you can say that there's a point you are on this side okay there's a point that you have to find out this is the minimum point that you have to find out this the one okay you can easily spot out some points that you have to actually find out in binary search problems that you can use here so we can understand that okay we can try to use B search here now how can you find out this particular Point uh because both the sides are increasing if you have seen the previous problem that is the Peak element the peak element is such that it is increasing on one side and then decreasing so you can easily find out that whether I'm on the left side of the hill or the right hand side and we can go to the local Maxima Minima that you have to find out but here both of the sides are increasing like this is 345 this is 1 two like one to whatever you want so both of the are increasing you cannot understand that what which side I'm on I am like whether I'm going towards the local Minima or I'm going away from okay so how can you do that's the like little B critic critical thing that you have to do but if I use bin here what you have to understand here is that instead of comparing it to the neighbors in the previous problem we are comparing it to the neighbors but now we can see that if it is increasing like it has sorted it is increasing here the elements on this side because it is here it should be you can see it is down it is like below this line why I've drawn it here why I have drawn this line it makes you understand that if I'm on this side which like which is like increasing like here minimum it should be smaller than this extremity like the element that is in the very front why because the element in the very front should like it is a sorted Arena so it is like rotated so it has to be having some element then it will increase then it will decrease to a particular Minima point and then it will always increase to till this point you can say okay so what you can see here is that all the elements on this side like this side should be less than three and all the elements on this side should larger than three and that's it that you can do here to find out which side you are on and which side you have to go because in binary search you first go to the middle and then you have to understand whether I have to go to the right and left like which side is the actual Minima or Maxima that is actually lying so if I somehow lie this we just have to take this element and compare it with the first element and that will actually help me understand that I am going close to the Minima or I'm actually have to go on the right hand side or left hand side to find out the Min and that's that a complet logic that you have to find out that instead of comparing with the neighbors generally compar it with the neighbors to find out like Minima Maxima in this you have to compare it with the very extremity and using that and find out whether I have to go to the left hand side or right hand side that's it that's a compl logic that we have to use let's move on to the code part now if you still hav't you can the box we have find out the two extremities L and R of the you can say by search very simple standard thing do it completely till L is there an R find out the middle element now we have to understand that if I have reached the you can say point the minimum element how can you do that I am on the minimum element is such that so as you can see all the elements to the right of it for every element to the right of it is smaller but for the Minima element the right of it should be larger so for if I'm on this the previous element always a previous element because it is increasing the previous element should be smaller because it's increasing but if the previous element to any element is larger then which mean that this is the Min so that's what we are checking the previous element mid minus one exist and if it is smaller mid minus one is smaller so as you can see that like uh so mid minus one as you can see the nums I am on Mid yeah so as you can see sorry if this is larger sorry if the element I am on is larger the mid minus one is larger sorry if mid minus one is larger then the current element then we are on the mid element that is fine that we're looking for if not then we either have to go to right or left depending upon that if the element I am on as you can see if it is larger than the extremity then which means that I am on this side and if I'm on this side I have to go to the right hand side and if I go to right hand side I have to make my L equal to Mid plus if I go to the right hand you can left hand side I have to make my r equal to Mid pretty simple that's a very standard and I have to use the same technique of B search in the previous problems and all the rest problems that you have to make L equal to Mid plus one and r equal to Mid and you will keep on doing this y Loop until we find out the answer and we'll always find out the answer because there always exist because it is saying that it is a rotated sorted array so they will always WR a minimum answer and we will always get answer from there that's logical code part for this particular problem if you still have any doubts you can mention in the com for this particular video I will see you in the next one thank you cording and by
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
377
um hello so today we are going to do this problem called combination sum um so problem is part of um august challenge so what we are asked to do is we get an array of integers and the target number and we want to return the number of possible combinations that add up to target okay um and the answer fits a 32-bit integer and that's answer fits a 32-bit integer and that's answer fits a 32-bit integer and that's not really um important here but um let's see an example so we have this array and target four um they say combinations but like these two here you might say it's more permutation but anyway um you can see notice here with this example that numbers can repeat so you can see we can have four ones that are equal to four and we can have one twice we can have two twice right um and let's say the number if the target was six we can have three twice as well right so the numbers can repeat that's an important piece there um and if um let's say here target is three so it's not possible so we return zero right um yeah we have something here that says also what if negative numbers are allowed we can take a look at that uh if needed but how can we solve this problem um the first thing to think about is um let's just try recursion right and just keep trying to add try all the numbers right and all the permutations and then see if they sum up to target add that to the count um and at the end account so that's the most straightforward solution um we can actually start just coding it right away um so what would that look like um yeah so we need that recursion so what should we give as parameters so we have target right that we will subtract each number we take from so we can pass in just the reminder right whatever is left and what we want to call it initially with is the target and we want each call to return the count of the overall number of combinations that will make this value reach zero right because when it's ratio is zero that means we found uh a combination that sum up to target right um so if reminder is to zero that's our base case but if so here count which means we return one because that's a possible way to um a possible way to make a combination that equals target now what if rem reminder is smaller than zero right so that can happen let's say for example we have target of maybe just two right and we have first we subtract one so we have one left as a reminder then we subtract two now we have minus one right so there is no chance to find a combination with one and two that sum up to two so we should just exit at that point and not count it right so how to do that we can just return zero right so here we return 0. next we want to since the numbers can repeat right we want to go through each number in the array and try to consider it in the combinations because numbers can repeat um and so what we do is just recall let's consider we're taking this number right so each time we go through the numbers and we consider taking that number and seeing and doing the recursion to see what happens if we reach a target or not okay and so here what should we do we should reminder minus the number we've taken which is num here and whatever comes back let's say we found a combination um or we found even more with multiple like recursion paths we need to add this to our count and then at the end we need to return the overall count um and yeah that's pretty much it um so here the main important piece of this problem is to go through all the numbers each recursion call because numbers can repeat right okay so let's run this so seems like it works with the base cases let's see again okay so that works there but one thing to note is that if we run it like this we will get time limit exceeded because um a reminder here can repeat like let's say uh maybe we have um four right and then we subtract let's say we have six and then we subtract two we have four left and then we consider two again so we already considered two we know they count with two and then we consider um two again there is no need to do the recursive call um one more time we can just cache that and then return it um so to do that we can just have a map here that memorizes the result for us and then here we can say that the memo of the reminder is count basically which means that if you have only this number left then you can reach count because we already calculated here let's say maybe this is five and we were able to get three combinations then we save it so that next time we don't do the calculation again and so how do we check so we check if this number exists in the map that means we already calculated it and we've already set it here so we can just return um and this would be with the reminder all right so let's run this and let's submit and that passes test cases um okay so now that we solved it with recursion and memorization we can actually think about um dynamic programming here um so if we think about solving it with dynamic programming we need to determine a couple of things what is our state what is the goal that we want to return um what is our accuracy relation and that's pretty if we have that then and then the order of iteration um that we go through and if we have those then we should be able to solve it so what's this the state here so the state we can just deduct it from what we are asked to do which is return the number of possible combinations that add to target so we can have basically for our state dp of i it can be just the number of possible combinations that add up to i right what this would mean is that at the end what we want to return is dp of target because that would be exactly what we are asked which is the number of possible combinations that add up to target right and now what would be our recurrence relation okay so it would be it's actually the answer is right here right so it's just the sum of dp of i minus number for all number in their numbers in the array right and now what is the order of iterations we need to do um so basically okay let me just make sure we understand this so um for 5 let's say right if we have i equal to 5 then it would be the sum of all the possible combinations that add up to 5 minus 1 say number here so that add up to 4 because that would mean we can just take 4 take 1 and we have the combination take whatever and we have a combination right or it could be five minus two and so three whatever is the combinations we have already for three and for each of those combinations we can add two and we have a combination that sum up to i right so that's where this idea comes from um and now for the order of iteration we are looking for target right so we want to fill the p from zero to target right so we can just go through um and the order we need is ascending order because each time for i we need i minus num to be present in the dp array right and so what this would mean is that we just need to go in increasing order from zero to target so that we can fill this value and so that would be just um you can call it maybe i in range of target plus one uh we are doing plus one so that we can reach target and fill it um and that's pretty much it so we have everything we need we can just start writing it up here okay so first we need to initialize our gp table right we know that the size is target plus one because we need uh the value at target so we can just start out with zero in range of target plus one now one thing we need to think about is what is the dp of zero right so this is the number of possible combinations that add up to zero right and the answer there is just and i'm jealous you don't pick any number right and so the only combination is one which is the empty list and so the base case here is one which means we can initialize dp of zero to one and now we can just do our recursion here and we need the sum right so what this would mean basically is for dp of i we need to go through all the numbers right and we need since it's the sum each time let's just add um dp of i minus no right um one thing to note here is if we have let's say a number bigger let's say maybe i is four and the number we encountered here is six right then four minus this is negative so we don't want that right because then in python it will go in the negative order from right to left and we want to have what we are in what is our intention here so let's consider a number e only if it's valid which means this is bigger or equal to zero okay um and so this is here if i minus num is valid and then at the end we want to return our goal which is just dpf of target so this is uh just our recurrence relation and this is the dp iteration um yeah and that's pretty much it so let's run this okay submit and that passes this cases now in terms of time complexity this is of target right so let's call it t and this is o of n the number of elements in the array and so overall our time complexity here is o of nt um and target is constant so roughly oven um and in terms of space we are doing um just one dp array of like target um again target is a constant so you could say either of t or of one because it's constant space um yeah so that's pretty much i think it for this problem um thanks for watching and please like and subscribe and see you on the next one bye
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
1,386
hello everyone welcome again to my channel so today we will discuss one lead code problem 1386 that is cinema seat allocation so what is the problem statement here the problem statement is we have a cinema hall and there we have row wise seats one particular row have three seats then four seats then again three seats means in between three seats and four seats we have a gap okay so now what is the end result we want the end result is few suits will be blocked and that's its number will be given to us we have to adjust a family of four members here and how this member of four will adjust here the thing is either they can sit from four to seven continuously or two to three and then four to five like this way or six to seven and eight to nine so family of four can see it only in three combination one is from four to seven or from two to five or from six to nine so what you will get as input is number of rows suppose how many rows are there so here if you see three rows are there and what you will get is reserved seeds means which seed is already reserved so 1 comma 2 means for row 1 the seed 2 is blocked 1 comma 3 means in row 1 the seed 3 is blocked and similar fashion for the other one now you have to determine like how many families you can fit here so from the row one you can see only one family can fit in because they can't sit here or here and for row 2 they can only sit here they can't sit here or here for row 3 they can either occupy this part or this part means total 2 combination is possible so one thing is clear that three combinations we can use but at max two combinations only we can use means in a particular row max two family group can sit now just talk about few constraint here so the number of n means number of row can be from 1 to 10 to the 1 9 and this reserved set length also can be 1 to minimum of 10 to the 1 in or comma 10 to the power 4 so what we can see from here is the number of row or the reserved sheet array can be a big length array or the big length number so we have to keep that thing in mind now what is the first brute force approach we can take to solve this problem so the first thing is we can define a variable called count family that will be your final result then and we can initialize it to 0 then we can traverse from 1 to n means from 1 to number of rows and for a particular row if we have to talk about the result then what we need all the booked sheet in that particular row so we already have a reserved sheets array so from there for this particular row we can take all the booked seats so we have to scan entire reserve sheets array and we have to get the book sheet for that particular row one thing to mention here is this reserved sheets array is not sorted means one comma two then the next input can also we can get at the end of the array maybe one comma five so we have to scan through the entire array to get all the sheets booked for row 1 so now in this case if we scan through the result sheet array then for row 1 we will get 1 comma two one comma three and one comma eight these three sheets are already occupied so you can see from this picture also two three and eight is plot so then what we have to do is this is the seed and we have to book this two here then three here then eight here and after that we have to apply some logic what logic we can apply is if this seats are booked then what is the possibility so from here what we can see is 2 and 3 is blocked that means here we can't adjust from 2 to 5 there is no chance of adjusting 8 is blocked that means from 6 to 9 one family can't occupy four to seven there is a chance so that's why for this combination only one family can sit so we have to apply logic to get the count and add it with the count family because we are traversing row wise so for that particular row whatever result we are getting we will add that thing with the main count family variable so here we got this one as a result so we will update the count as one so what we noticed here is what will be the time complexity here so we are first traversing rows from one to n then for that particular row we are fetching all the reserved seeds for that purpose we have to traverse to the entire area because it is not sorted then when we are getting the booked sheet we are applying some logic on this to get the exact number and then we are updating so it is taking o n square of time or you can say o n into the length of this without sheet sharing so now we will check if we can do something better but before that what we noticed that i will go through the thing we noticed here is if no sheets are blocked suppose we got a row and for there no entry is present in the reserved sheets array that means no seeds are booked for that row so for that row we can consider two family because at max two family can occupy or else if sheet number one and seat number ten is blocked and apart from that all the seats are empty then also maximum two family can sit because either one non-blocked row because either one non-blocked row because either one non-blocked row or one and ten blocked both are similar because one and ten is not playing any role here so if no sheets are blocked for a row or seats one and ten are blocked then two family can accommodate so this thing we have to consider so before moving to the better solution one thing to consider here is if you do it in one square time using brute force approach and if you submit the code in lead code you will get a time limit exceeded error so we have to try to do it in on time now we have to check is it necessary to traverse every row and then for that row every reserve sits so what is preventing us here because for a particular row we don't know all the reserved sheets that's why for that row we can't get into a decision but instead of that if we reserved shifts array if we completely traverse and for a seat if we can come up with some decision then and there we can block to unblock that particular area suppose scan entire reserved sheets array and then think from that background suppose if you see here other than taking consideration all the seeds if you think that three combination is possible one is left side one is the middle one or the right side so here take one example suppose whenever i am traversing this reserves array suppose i traverse this one then my row number is 1 here so for that row create one map kind of thing where the map key will be an integer that is the row number and the value will be a boolean array of three fields left middle and right so the map will be of integer boolean type okay now what we got the first value as one so if one is already not present there in the map then just put one here and by default left middle and right will be true here so what we will consider here is we will check which set is blocked so here set number 2 is blocked now we have to tell here that if sheet number 2 is blocked then which of the following i can't access so if c2 is blocked that means left side part this part i can't access it will not affect the middle or right part right so to for because of two this particular thing will be false then if we consider about the second one comma three means this three is blocked so which suit or which family group it can affect as three is blocked it can affect only the left part right because four to seven anyone can sit or maybe six to nine also anyone can sit so as it is already false nothing we have to do then we will check for one to eight what we can see is eight is this seat so this seat if it is booked then where i can't consider the family members that is only the right part right like from here to here no one can sit so only this part i will make it as false now we will proceed so the fourth number is 2 comma 6 so as 2 is a new row then we will create a new entry in the map and we will maintain here as 2 then which set is blocked in the row 2 that is 6 is blocked as 6 is blocked that means which among this i can't access obviously the middle one because middle one no one can sit so this is false and from here to here the right part also no one can sit so this part is also false next we will go for three to one so here one thing to consider is if sheet number one is blocked there is no effect of this right so we'll skip as i have mentioned in the earlier slide next is 3 comma 10 so set number 10 is blocked but for set number 10 also there is no effect right so we will skip so if you see here for three no entry only we created okay if for the later point of time we got an entry called 3 comma 5 then we can consider but if we get seat number one seat number 10 is blocked straight away we will skip that part and for row number four there is no entry itself present here and it is true also because for four no seeds are blocked so we will not consider that one so i just formed the map now iterated over the reserved sheet completely and formed this map now we have to calculate the result so now if we go and calculate the result what we can see from here is for this row as left and right is blocked then only middle is free so here i can get only one family member for two middle and right is blocked so here also we can get only one family member now is our total result is 2 1 plus 1 no total result will be so in the map the size of the map is 2 that means for this 2 row we have blockage of sheets and we are calculating but total number of rows are 4 and 4 minus 2 means the length of the map that is 2 so 4 minus 2 is 2 so for that 2 we can straight away consider 2 sheet each because for three and four no seeds created any effect right so maximum two family can sit there so straight away for three and four you can consider two sheets each okay so here you can see one member here also one family member here statewide is two here also two so total number of seats will be two plus two four five and six so six family member can sit here so the formula to consider here is the total number of family member which can accumulate here is the result from the map first you have to calculate the result from this map which is 1 plus 1 2 then in minus map size into 2 to calculate the rest of the part so i hope this part is clear now and here in this case what you saw is we are just traversing one once in the reserved sheet array and then only we are getting the result so the time complexity reduced to o now we will see the coding now coming to the solution part so first we have to define one count variable where we can keep track of the counts and then the boolean sheet array and the map will actually be a integer and boolean type of map now we have to iterate over this reserved sheet array so it will be reserved sheet dot length plus so here what we have to first consider is what is the row number so the row number will be this reserved sets position of i comma 0 so this will be our row number the trunk and s will be our blocked sheet you can see so this will be our blocked seat now as we mentioned if we check that the block seat so this block set if it is 1 or 10 then we will just continue if s equal to 1 or 10 then we will continue no need to do anything or else what we can do is we can create one map for that row and so what we can do is if that map already contains the row then we will just simply take the seeds map array okay or else we can create a seeds map array and we can initialize all the left right and middle as true now we can apply one simple logic here if s means the block seat is 2 or 3 then we can simply tell that the lift seat you can take it's the left part you can take else if you check that s equal to 8 or s equal to 9 that time we can say that the rightmost seat in sits right will be false means that's it we can't take or else if like 4 and 5 is there then g means left side also we can't take the middle one also we can take if it is 6 or 7 then right also we can't take and middle also we can take so we will write that also okay so if it is like four or five then left side or middle one we can take if it is six or seven then the middle one or the right side also we can't take now as our logic is over which will just uh tell that this particular sheet can be given or not then that result we can simply put it in the map row comma sets okay so now we will completely iterate over this reserve sheet so adding and according to the logic it will check like if left side right side or middle one which one to block and it will complete its part then next what we can do is we can write the logic for counting means we have to iterate over this map okay we have to iterate about this map and this will be our seed available boolean array so if we can say that the left side is also available the middle one is also available on the right side also or left side and the right side is available only then we can simply say two family can sit together so we will increase the count as count plus two or if zero and two is uh like available or only zero or only one is available that case also you can increase just the count to one and same is for uh if the one and two both are available and only one or two is available that time also will do a countless plus okay so you can also in your own way also you can write this logic and maybe you can simplify this also the counting logic then we are just iterating over the whole map and at last what we will do is we have to get the final count that will be count equal to count plus we have to check like for which row there is no seed blocked or 1 and 10 is only blocked so that time the size of the map we have to minus from the number of rows and we have to multiply it with two so this particular thing we have to add then we have to return the count yeah so now if we submit this so that's it about this seat allocation problem so one thing to talk here is this problem you can solve using bitwise operator also so that is a better approach of solution you can say so i will try to make a separate video where i will talk about bitwise operator then how to solve this problem using b twice operator also so as of now you can go with this problem and this solution and i hope you enjoyed the video and if you have any comment you can mention that thing in the comment section and the github link for this code also i'll put it in the description box thanks for watching
Cinema Seat Allocation
shift-2d-grid
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved. _Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side. **Example 1:** **Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\] **Output:** 4 **Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group. **Example 2:** **Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\] **Output:** 2 **Example 3:** **Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\] **Output:** 4 **Constraints:** * `1 <= n <= 10^9` * `1 <= reservedSeats.length <= min(10*n, 10^4)` * `reservedSeats[i].length == 2` * `1 <= reservedSeats[i][0] <= n` * `1 <= reservedSeats[i][1] <= 10` * All `reservedSeats[i]` are distinct.
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
Array,Matrix,Simulation
Easy
null
54
hey guys today we're going to solve litika number 54 spiral matrix so we're given a matrix of m times and elements and we need to return all elements of the matrix in spiral order so we want to take like the first row then the last column and then the last row in reverse and then the first column in reverse okay so there are many ways to do this one way given by stefan bachmann which is a great competitive programmer is to always take the first row and then rotate the matrix counterclockwise so that's a great solution like it's very creative however we're going to go for the more for the simpler version the simple solution which is optimal in a time complexity and space complexity analysis so to do this what we're going to do is we're going to keep track of which rows and columns we have consumed like we want to think of them as being now out of bounds right so for example if we take the first row and we put those elements in the array then we want to say that now we have an upper bound that is one like we can't go any further upwards than one is our first row now we can't access this zeroth row now okay so yeah we're going to need some variables to keep track of those bounds and then we're just going to use four loops to take the first row that is in our bounds and then the last column which is in our bounds then the last row which is in our bounds and then the first column which is in our bounds so that will clockwise will go around in the matrix clockwise okay so let's jump right into the coding so first of all this is a line for a edge case where you don't have basically any elements so in that case you just want to return an empty array but then here starts the real coding so here you have the bounds for the left side so this starting column and the ending column so these are the bounds for the left and right bounds and initially they are zero so you can start with the zeroth column and another valid column is for example here it's the column with index two so it's the third column then you have the same thing for rows so the zeroth row the first row so the one with index zero is valid and the last row that is valid is the row with index two so the third row okay so these are our four bounds that will tell us if we can move any further in that direction now we need the result array this is going to be our output and now what we're going to do is we're going to use a while loop so while our result length is less than the amount of elements in our matrix which is just a kind of like n squared it's like the base length times the height so yeah what i was saying is while our result length is less than the amount of elements in the matrix we're going to run four loops to take the first row the last column the last row and the first column so the first loop here is going to loop through from the bound from our left bound to our right bound is going to take all of the elements in our upper bound row so like our upper bound row initially is zero so it's going to take all of those elements but then it's going to move further down right so yeah we're going to use our upper bound as a row index so you can see i'm using my upper bound as a row index my matrix and then i'm using the column bounded by the start and end column as a column index i'm just pushing it into the result and now like here essentially we've consumed the matrix row so we can push we can add one to the start row because we don't ever want to touch this row ever again or we will have duplicates right so it's very important that here we do start row plus and then like the remaining three four loops are going to be very similar to this one so i'm going to go very quickly with them so start with your upper bound and go down to your lower bound and use that as a row index and push to the result the element in that row at index and column so that's your right bound right so we're traversing down the last column which is in our bounds and at the end decrement your end column because you want to move it closer to the center of the matrix right you want to close in on the center and yeah so it's basically the same thing for the last two for loops you can kind of see they're the same thing here we're moving from the end column down to the start column so we're moving in reverse order and we just push the element like before and the same thing here we start from the last row and we go up to the initial row to the upper bound and we push the element again and don't forget to update the bounds because you're using up the elements you don't want to use them again or you'll have duplicates okay so now we can just return our result array and you know since we're doing this in this way with for loops you might actually end up with more elements in your result array than there are elements in the matrix and so what you want to do is you want to trim down the result so that it doesn't have any more than this amount of elements and so to do that i use the slice method so i take the all array and i don't want to take any elements that are above this right so i'm going to show you that this works and the time complexity here is o of n squared or like o of n if you take n as the amount of elements in the matrix and the space complexity is o of n where n is the amount of elements in the matrix because we're storing them in the output and if you don't consider the input and the output as the space complexity then the space complexity here is o of one because we only have these four variables and they don't occupy more memory based on how many elements the matrix has so yeah that's it for me today thank you for watching and bye
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
1,019
hello everyone and welcome to coding card so in this tutorial we are going to solve one lead code problem from the topic linked list and you can see here the problem name is next greater node in a linked list so in this column we will be given one linked list and what we have to do here is for each node we have to find the next greater node so let me explain you here with one example for example the linked list is having value 215 suppose here we are given one linked list having value to 2 1 and 5. so what we have to do here is for each node we have to find the next greater node so here for 2 the next greater node is 5. for 1 the next greater node is again 5. or 5 we don't have any index greater node so for this we have to return 0. so you can see here the output 550 let us take this example two seven four three five link list having value to seven four three and five so for these two the next greater element is 7. so we will place 7 for these two for seven you can see here in the whole node we don't have any next greater element so we'll simply put 0 over here for 4 the next greater element is 5 here so we'll put here 5 or 3 again we have five and for 5 we don't have any next greater node so we'll simply put here 0 and at the end we have to return this one as our answer sensor is seven zero five zero so you can see here seven zero five zero so this is the problem here means here we will be given one link list and what we have to do here is for each node we have to find the next greater node and if next Creator node is not present for any element then we have to Simply put 0 over there so how to solve this problem so let me explain you here with the second example link list having value 2 7 4 3 and 5. so for this problem we have to Simply use one stack you have to use one stack and we know stack has two operation one is push operation and another is pop operation and I will explain you how this stack is useful here in this problem and here for push operation we have two things when we can push element into stack the very first criteria is either the stacks would be empty Stacks will be empty or second criteria is this is or second criteria is the next upcoming element should be less than the element which is at the top of the stack means upcoming element let me first write the criteria then I will explain you with the example upcoming element should be less than topmost element top element in this tag and for pop operation we have again two things when we can pop elements from the stack we have two criteria first one is stack should not be empty Stacks would not be empty and the second criteria is the upcoming element should be greater than stack topmost element top element from the stack so for stack we have two Operation Push and pop and when we can push the element either stack is empty or the upcoming element in this tag should be less than the topmost stack element and for pop condition either the stack should not be empty and at the same time here and at the same time the upcoming elements should be greater than the topmost element which is present in this tag so let me explain here the same example our list is having value 2 7 or 4 3 and 5. now let us take one stack now you can see here currently our stack is empty since the stack is empty we can simply push the value 2 here 2 is done next is 7. now the upcoming element is 7 and the stack topmost element is 2. so whether we can push seven or not so for which operation you can see stack should be empty or your currently stack is not empty so it will go in or condition here the upcoming elements should be less than the stack topmost element means this upcoming element should be less than the stack topmost element so here you can see here 7 is not less than the topmost element so it want to go for the whose operation we will go for the pop operation now for the pop operation you can see here stack is not MTS or stack is not empty and at the same time what is the criteria upcoming element which is 7 should be greater than the topmost element in the stack the topmost element is 2 yes this criteria is satisfied so for these two we'll simply pop out these two and for these two the next greater value is 7. so whenever this upcoming element value is greater than the stack topmost element then that upcoming element is the next greater element for this stack topmost element so previously towards the stack topmost element so its next generator element is 7. so 7 is the element which made this value 2 just pop out now our stack is empty we'll simply push this in our stack now we are done we will move forward seven is done we will move forward next is 4 now you can see here the upcoming element is here 4. now here my stack is not empty it will go for or condition and we will check whether the upcoming element is less than the stack topmost element yes it is true then go for the push operation for now we'll go next is three again our stack is not empty it will check this condition a coming element which is three it is less than the stack topmost element here topmost element is 4. yes it is true so it will again go for the push operation it will go in the stack and stack topmost element will be now three now we go to the next element which is 5. now again my stack is not empty it will check the next criteria which is upcoming element 5 is less than stack topmost element 3 no this is wrong so it will go for the pop operation now for the population it is checking whether stack is not empty yes my stack is not empty and at the same time it is checking whether my upcoming element is greater than stack topmost element yes a coming element is greater than the stack topmost element so what we will do here is we will assign 5 as the next greater element for this stack topmost element so for these three the next greater element is 5 and what we will do is simply pop out this element now my stack topmost element is 4. now again it will check whether this stack is empty no my stack is not empty and at the same time upcoming element which is 5 greater in the stack topmost element yes 5 is greater than 4 so what we will do this 5 will be the next letter element for the stack topmost element so stack topmost element is 4 and its next reactor element will be 5. and we will simply pop out this element of all this element now again my stack is not empty and at the same time we are checking upcoming element 5 is greater than stack topmost element stacked up most element is 7. so this criteria is false so if it is false what we will do we will simply push this into stack so 5 will be here so here we are done we are at the end of the linked list we are done here now when everything is over we are simply going to assign 0 for the element which we are not able to find the next greater element so at the end we'll simply return this as our answer so this is the problem here we are simply using one stack data structure to perform this operation so now in this problem we have to take care of two things one is the stack data structure and another is the indexing I will explain this one here like whenever we are getting a next greater element we have to assign that next greater element to the stack topmost element so how to find the location of that stack topmost element where is that stack topmost element present so for that we'll save the value as well as the index part both in this stack while doing the push operation so let me explain you here with the same example again let us take the same example to 7 4 3 and 5. suppose this is our linked list and we will take our resultant list to save our next greater element so if you see here just think this is a array having index 0 1 2 3 and 4. suppose this is 0 1 2 3 and 4. now we'll take one I equal to 0 as a counter so whenever we are moving one by one node we'll simply increase this by plus one now currently we are at the very first node so what we will do will assign 0 for its index whenever you are moving node by node we'll simply go and assign 0 to its corresponding position and with the help of this stack operation what we will do we will place the correct next letter element to its corresponding position so I'll explain you here so currently we are adding node 2 so we will place here 0 at index 0 here current I is 0. now my stack is empty so what we will do we'll place the value 2 and the index value 0 in my stack now we'll move forward we'll place here 0 first now here the upcoming value is 7 and the stack topmost value is 2. so for push operation the upcoming value should be less than the stack topmost element but here the criteria is not true for the push operation so it will go for the pop operation so for the pop operation what we are going to do here is here 7 will be my next greater element for which one this value 2 and 2 indexes were at zero position so go to the zero position and place value 7. correct it is working fine now what we will do we'll pop this from the stack my stack is empty so what we will do is simply press 7 and its corresponding index which is one seven comma 1 will move forward next is 4 so first place here 0 now upcoming element is here 4. so 4 and the stack topmost value is 7 so is 4 less than the stack topmost element yes it is less then go for the push operation so we'll simply add here 4 comma and its index is 2. we are done here now here stack topmost element will be for now we'll go for the next node which is three first we'll put here zero now here the upcoming element is 3 and the stack topmost element is 4 so we'll check is 3 less than the stack topmost element yes it is less then go for the push operation here so here we will simply push this 3 with its index 3. now the next element is 5. so go to five first we'll place here 0 at its index so whenever we are going node by node we are simply increasing this I by I plus 1 by plus one I'll write the code you will able to understand easily over there now here stack topmost element is 3. and the upcoming element is 5 less than the stack topmost Element no now here it will go for the pop operation and for the pop operation my stack is not empty and here my upcoming element is 5 so 5 will be the next greater element for this value 3 so go to the index three this is my index part and this is my value part so go to the index 3 and place 5. this upcoming value over here now this will be popped out now my next greater element is 4 again my stack is not empty and the upcoming value is greater than the stack topmost element this 5 is greater than 4 so again what we will do go to index 2 and place this 5. so for the stack topmost element my next relator element is the upcoming element which is 5 so we are going to the corresponding index and placing 5. and after that this was 5 after that we are simply popping out that element now my stack topmost element is 7 again my stack is not empty and we are checking for the pop operation we are checking the upcoming value is greater than the stack topmost element so this is not true so what we will do it will simply push this element here so 5 comma and this index is 4. 5 comma 4. now we are done we are 5 comma 4. now we are done with the linked list so at the end if you see here we have got our result here we'll simply return this result you can see the answer is 70550 we are getting the correct so in this problem we have to use two things one is the stack and another is the index part so that we can place the next letter element to its corresponding index so let me write the code and explain you again line by line over there so here what we have to do here is you have to take two things one is the resultant list to return the result another is you have to take one stack and one is the I value so whenever you are moving from node to node this I value will be increased by 1 and let us take one pointer PTR to iterate in the linked list not by node so PTR equal to 8. so till here everything is okay so what we will do we will iterate in the link list from start to end so for that let us use one while loop while PTR is not none we are going to iterate one by one now whenever we are reaching to the very first node or second node or any node our first task is to place 0 in our resultant list means we are standing at means if you are standing here our very first task is to place 0 at its corresponding index in their resultant list so what we will do we'll simply press res dot append zero over here now next Target is to write the logic for the push operation so what we'll do here Logic for push operation okay so what is our very first task we have to check whether this stack is empty or not we will check if length of Stack we will check length of Stack equal to 0 for empty or at the same time what we are going to check you can see here the criteria stack is empty this one stack is empty and at the same time upcoming element so upcoming element is PTR Dot PTR dot well it should be less than the stack topmost element it should be less than stack topmost element will be minus 1 it will give the topmost element and we have to consider the value part so you can see here in the stack we are pushing two things here we are pushing two things value part as well as the index part in a stack so suppose we are here suppose this is my stack topmost so we can simply get by Stack minus one it will give this value and from this one how to get the value part this 5 we'll simply get by bracket zero okay it will give the value part if you put here one it will give the index part so zero if this criteria is satisfied what we will do will simply push the value into the stack so stack dot append two things one is the value part so PTR dot well and at the same time we are passing the index part and index is calculated with the I so you'll pass here I so this is the logic for the push operation now if the stack is not empty or the upcoming value is also not less than the stack topmost element so it will go for the pop operation so we write here logic else here we'll write the logic for operation correct in else part we have to do the pop operation so for the pop operation we have to perform till the stack is not empty and at the same time the upcoming value is greater than the stack topmost element so for that we will write simply while loop while length of Stack is greater than 0 and at the same time the upcoming value VTR dot well ETR dot well it should be greater than the Stacked of most element stack of minus 1 will give me the topmost and topmost element is containing two things so we have to first check the value part so zero so till this condition is satisfied we are doing pop operation for every stack topmost element so what we have to do here is whenever this criteria is satisfied so what we have to do we have to get the index part from the stack topmost element so how to get the index part so for that we have to write stack of minus one to get the stack topmost element now from the stack topmost element it is containing two part one is the value and another is the index part so index part is at 1. so this will give us the index so this will give the corresponding index where we have to fit that next greater element which was the upcoming element so we have to go in res we have to go to this index and assign the value the upcoming element which is PTR dot well okay so let me explain you this line here it means suppose in the stack topmost element here suppose we are having value 3 comma 3 this is my stack topmost element so this is my stack so if I write here stack of minus 1. it will give 3 comma 3 like this now here I have to access this index part so what I will write a stack of minus 1 and 1 it will give this total value will give me 3. so we have to use this index in our res of 3. so it will go in this res at index 0 1 2 3 it will go here at index 3 and we are assigning PTR dot well the upcoming value here suppose the upcoming value is here 10 so it will go at index 3 and assign 10. so we are writing the same over here so after assigning this value our next Target is to pop the stack topmost element so we'll simply use stack dot pop stack Dot Bob so this operation will be done till this y criteria is satisfied so once these criteria is fail what we will do we will go down and write our next Target is whenever this criteria is fail our Target is to push that upcoming element into this tag so stack dot append the upcoming value which was PTR dot well at the same time its index part I okay so we are done so till here our logic is over okay so till here our logic is done now next Target is we have to move to the next node so let us write the logic for this while loop for the PTR so PTR will be PTR equal to PTR dot next so whenever this if condition if an else are done we are moving forward to the next node so that's why you are writing here PTR equal to PTR dot next and I value will be increased by 1 I plus equal to one so our this I value will be also increased by 1 whenever we are moving to the next node so we are done and at the end whenever this criteria is satisfy we have to return the head so we are done so let us run this code oh here we have made one mistake we have to return here result res not the head so you can see here it got accepted so you can try for the next sample input which is 2 1 2 7 4 3 and 5. let us run and check so you can see at the output 70550 so it is working fine let us submit this code so you can see that it got accepted so that's all for this problem so basically here two things were used one is the stack operation and another is the index part means we have to place the next letter element to its corresponding position so that's all for this problem so I hope you have understood this logic and the explanation so if you have learned something new please do like our videos and subscribe to our Channel coding card and stay tuned for the next videos thanks for watching
Next Greater Node In Linked List
squares-of-a-sorted-array
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Array,Two Pointers,Sorting
Easy
88,360
268
for today's algorithm we're gonna be discussing the Leech code question missing number so what is the question missing number the question is you're a given an array with the following properties we're going to call this array a the array a has the property one that the arrays of size n minus 1 for some integer n for some non-negative some integer n for some non-negative some integer n for some non-negative integer n to every member of a belongs to the set 0 and inclusive and three every member of 0 and only exists once in a right so from these three properties your goal is to find the missing number in this array now why is there a missing number well if the array is of size n minus 1 and exists members of 0 to the N 0 to n inclusive in this array only once then there must be one number in that set that is not in the array so your goal of course is to find that missing number that is not in the array so for example given an array as input 9 6 4 2 3 5 7 0 1 if we look at this array we know that it contains elements in the set 0 to 9 inclusive and a quick scan reveals that 8 is missing from this array so the output for this would be 8 now it's key to notice here that the array does not have to be sorted so you have to come up with a solution it doesn't care whether or not this array is sorted okay so let's quickly point out before we begin with the intuition that throughout this discussion we are going to be indexing this array at zero okay so first intuition how do we want to solve this problem well we need to notice right away that since every value of a only appears once we want to consider a as a set so we're first going to think of a in our heads as a set more than really an array we also know that the members of a have a unique sum that distinguishes this particular version of the array from any other version of the array that might be passed in and why do we know that it's because a is a set of members of zero to the zero to n where it's missing one that means there's only a finite number of versions of this set that can be present in the array and each one of them is going to have a different song because there are no duplicates so we notice at this point that given the sum alone without the array we can actually derive what version of the array we are given the sum so from the sum we know what array we have but we can actually take this intuition of the uniqueness of the sum of a to derive a solution to the problem that we're actually given which is not to take a sum and find the array but have the array and find its missing number but we're going to use its sum as a proxy so we know that the completed array or sat right with elements in 0 to n sums to a unique value therefore if we have the sum of a we can also compare it to the sum of a complete version of a where it is missing no numbers right so if we create this complete a from 0 to n that contains all of the members of 0 and inclusive then we can compare the two sums to find which number we're missing right to find the missing number ok so now let's try to build an algorithm for this so let's call our algorithm missing number and it's to take as a parameter an array which we'll call ARR and it will output an integer that integer being the missing number in this array so the first thing we're gonna want to do here is denote and be the array size so the arrays size of course is going to be one bigger than the number of elements in the array so we're also going to denote another element result which will initialize at zero so now we have the size of the array and we have a variable in which to store how dissimilar we are from a perfect array that contained all the elements so the next thing we have to do is loop from I equals 0 up to n minus 1 right we're gonna loop over the entire array we're given and we're going to append two results we're gonna add two results our current index I right because if we imagined a perfect array that contained all the elements we could also imagine it was in sorted order and it had the same unique values so we're going to pretend that we have a sorted array of all the elements so we're going to add I its first or it's AI element right in this situation its first element which in this case is 0 and then we're gonna subtract the value at index I from our array right because addition and subtraction do not care about the order of the elements we can do this and we can pretend that we have a sorted or unsorted array doesn't really matter but for our sakes we're pretending it's sorted and we're taking the element from our original array and we're subtracting the amount from our actual array right so we're taking the element for our perfect array and subtracting the element from our original array and we're going to find out after that where how far we are from where we need to be and to do that at the very end we want to return result which now has this difference class and now n is that one perfect element in the are that one element the perfect array that exists in our situation because it's that does not exist in the original array but the actual element that doesn't exist or the missing number is going to be derived from the sum of this new n plus the result which in this situation will be negative okay so let's trace this code here we're actually going to trace this on the original input that we started with at the very top which is the array nine six four two three five seven zero one already know what the output is going to be but we're gonna trace over this anyway just to show how the code is working so we passed this array a into our function and the first thing we need to do is set n to its size and its size in this case is 8 size 9 just kidding 1 2 3 4 5 6 7 8 9 yeah sizes 9 and we're gonna set initialized results as well to 0 next we're going to do is going to loop so we'll set a initialize new variable new local variable I starting at 0 we're going to loop until we'll say I until n minus 1 which is in this case is 8 and now we're going to add two results so we'll start at the zero we're going to add I as it's incrementing and then we're going to subtract our value at array at index I so we're gonna get 0 plus 1 minus 9 plus 2 minus 6 plus 3 minus 4 plus 4 minus 2 plus 5 minus 3 plus 6 7 plus 7 minus 0 plus 8 minus 1 now we take this big number here and can strike any pairs like 7 minus 7 plus 7 minus 6 and plus 6 minus 3 and plus 3 minus 1 plus 4 etc so we're left with our value and at that point we're just going to add n which is the size of the array in this case the size is 9 so we just add 9 and once we add 9 we can even strike minus 9 and plus 9 which we exist with eight is the only member left unstruck so this is one way to solve this problem but just for fun let's look at a second way so this is the iterative solution but let's take a look at the recursive solution to the same problem so we start with the same method declaration missing number taking an array a and returning an integer now missing number is going to call a helper method here right because we know that are not enough parameters in this current method in order to do this recursively well not an easy way so make our lives a little easier we're gonna make this call a helper method just going to take initial parameters 0 a dot length it out length minus 1 and a so our intuition is gonna be very similar here but what we're basically thinking about in these four parameters are four values that we're storing now the first value so let's make this missing helper method declaration is going to be an integer which we'll call target now target is going to be the actual result that we're getting from the array that's passed in as we sum over our second parameter is going to be called an integer again we're going to call it real now real is the expected some of the perfect full array that contains every member of the set so we're just going to be adding our index or our I which is gonna be the next parameter into I which is just going to trace the index of the array a as we loop over it so I is just going to be added to real and that's how we're gonna count what the perfect sum should look like and lastly we need to pass in the array a so our last parameter and this is going to output an int so our first thing we need to do when we're considering a recursive implementation is consider what our base case is now our base case in this situation so when our index is below zero because we're zero based index once we're below zero we know that we've looped over the entire array so if I is less than zero we want to return real - target why because real is the sum of - target why because real is the sum of - target why because real is the sum of the full array and target is going to be the sum of our version of the array so real - target is gonna give us the real - target is gonna give us the real - target is gonna give us the leftover number that's missing from target and lastly we're going to return as our recursive case missing helper with the parameters target plus a tie right because we're gonna sum to target so we can get this first sum is imperfect sum we're gonna get add real plus sign so this is going to build our perfect zone we've got to decrement I by one so that we can loop over the array backwards and we're gonna pass in our array once again because we need to keep the reference to it now I should make a quick note that the reason that we pass in a dot length as the second parameter of the initial recursive recall in missing numbers method is because we want to start at we want to be able to make sure we get every member of the perfect array and we wouldn't get every member of the perfect array because we are only looping over the size of the imperfect array which is smaller so to make up for that you pass in the length as its first element initially okay so these are the two methods two ways to solve this problem well let's analyze the run time and complexity of both of these methods and consider you know which one is the better way to solve this problem so for the first thing we want to consider is the iterative solution which pretty easily we can figure out that we only loop through the entire array once so our run time is only of the order of the size of the array and so we can simply say that this is a linear runtime solution now we don't use any additional data structures here so we don't have to worry about that restriction either now in terms of readability the code is very clear as to what it does we're simply going to add and subtract the integers inside the video right and instead of the perfect array as we loop over it because that's a plus so it's clear it's linear and doesn't require extra data structures let's take a look at the recursive solution another recursive solution we also go over each number once right so until you're in debt zero so it's also of the order of n in terms of runtime this we can say is also linear however the recursive solution requires the use of a stack in order to store the recursive calls so it actually is not really in place so already this is a con of the rehearsal solution that is not present in the iterative solution as the iterative solution is in place and additionally it might depend on your taste but the recursive solution is not as clear or it's obvious as to what it does as the iterative solution is in this situation now there are some problems that are very clearly written recursively and are meant to be solved recursively but this is not one of those problems so this solution is not obvious just by looking at the method and what it does so in conclusion our opinion here is that the iterative solution is the better solution for this problem I hope you enjoyed this video if you did don't forget to Like comment subscribe hit the little bell icon down below don't forget you can also watch either of these two videos if you want to see more of sharps yes and as always I'll see you in the next video
Missing Number
missing-number
Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._ **Example 1:** **Input:** nums = \[3,0,1\] **Output:** 2 **Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums. **Example 2:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums. **Example 3:** **Input:** nums = \[9,6,4,2,3,5,7,0,1\] **Output:** 8 **Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums. **Constraints:** * `n == nums.length` * `1 <= n <= 104` * `0 <= nums[i] <= n` * All the numbers of `nums` are **unique**. **Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity?
null
Array,Hash Table,Math,Bit Manipulation,Sorting
Easy
41,136,287,770,2107
1,834
so you are given n task level from 0 to n minus 1 which is represented as 2D array and the task is uh this is known as task okay I so task of I is equal to NQ time and the processing I it means that uh the ith task will be available to process at in queue time and will take processing time to finish processing okay so it is saying some statement has given you have a single threaded CPU and can process at most one task at a time and will act in the following way if the CPU is Idle there are no available tasks to process the CPU remains idle if the CPU is idle and there are available tasks the CPU will choose the one shortest processing time if multiple tasks have the same processing storage for this shortest processing time right so it will choose the task with the smallest index okay once a task is started the CPU will process the entire task without stopping so the CPU can finish a task then start a new instant and then we have to return the order in which the CPU will process the task okay so let's understand this one okay and give you a pen and then yeah okay this one okay so this is example first we have given here so in the example first it is saying that what we have here uh task right we have task and task is given one two four three two four one and input output this is the input task given so the event go how it will go so this is explanation saying that at time one task zero is available to process this available task is zero so also at time one the ideal start processing task is zero so available task is nothing then time to Avail task is one right and the available task is we will put into one and similarly we'll put at the time three level task is what one to write at time three it will be like that and so on it is giving okay so let's understand why we are choosing like this okay yeah so example two have you understood okay so here I am going to show you some uh overview okay so what the problem is saying right so this you can see the map here right uh process and processes in time right so this is the task for available task for CPU so the problem statement asks us to create a schedule policy that the product that product is the shortest available task right means this problem asks us to create a schedule policy right and that will protice the shortest available task so this is known as what shortest job first right this is called shortest job first now in short you know that s j if you can say that right sjf CPU correct scheduling sjf's CPU as scheduling right you can say that so shortest job first SJ app that is known as CPU scheduling right so in the in this sjfcp scheduling right if the CPU is Idle there are available tasks right the CPU will choose one with the shortest processing time right so there will be some processing timeline light like this it is given right so if the CPU is Idle there are available tasks so the CPU will choose the one with the shortest processing time like this is the shortest processing time right and uh if the multiple tasks have the same processing time same shortest processing time right so it will choose with the smallest index it will check the index of this one so if this is the index is 0 and is this is the index of what three you can say so it will choose then this one if this is not 21 it is same as 2 then it will choose this index okay this is the uh you can say two concepts are there right first it will check this shortest if there is only one but if there is multiple tasks have the shortest processing time so it will choose based on the index right based on the index now if it will choose the task with a small smallest Index right the task which arrived first right which task will come first once the CPU starts to execute a task it will process the entire task without stopping right and it is nothing but what it is non-primitive right what it is non-primitive right what it is non-primitive right non-premitive non-premitive non-premitive so you can see here we have our available task force CPU the process multiple processes are here process one process two process three process four and these are their what processing time these are their processing time so these are available tasks for CPU so if we'll talk about order of execution meta by CPU in the shortest job first test schedulite what we will do we'll first check with the processing exam what is the processing time right so first which one will come this uh P4 will come because it has a two processing time right so pp4 will come first right in the array next if you'll see that processing time next is what this time this one P3 right and sorry P2 because it is 3 right this is three not six so it will come what P2 similarly it will come 3 p 3 now it will come P3 and the last it is as 21 so it will come P1 so if we'll talk about the time right time it is the keyword to now for P2 it is 3 so now we have to add the time what is the time now 2 plus 3 is now 5 here okay next time uh P3 whatever the time six have right so 5 plus 6 is what eleven correct next P1 will come that time 11 plus 21 is what 32 like this it will uh make the order of uh what we can say order of execution right and this should be written as the output correct so let's understand some more examples overview right and this is the thing that I have already noted okay you can pause this and you can read it okay next it is saying what approaches we can go through right we have the shortest minimum Heap so sometimes are they given task given sort of tasks given right so let's understand so here the CPU can only pick a task for execution after it is enqueued right and thus we need to keep track of current time to see which tasks are available for the CPU and sort the task in increasing order of the in queue time right we have task right what we have task here correct we have task here and we have in queue time and processing right this is in queue time uh this is processing time right in queue and processing time okay and so on we have here like that so now what we have to do now we can create a list of tasks right after sorting the task right now we can create a list of tasks available at the current time and that we can send task whose in queue time is less than or equal to the current time so from the list what we can do we will select the task with the shortest processing name and so we can think of sorting all the available tasks in increasing order with the processing time we can take like increasing order correct we can take okay so from the list we will select the task with the shortest processing time and so we think sorting all the available tasks increasing order of their processing time and then after selecting the task the CPU will run that task until it is complete and the current time will increase by the processing time by selected task so after increasing current time some more task might become available for the execution so we would then add their task to order list and again we'll sort the list in increasing order of the processing name right so this processing this approach will work but sorting our available task list every time we will update it by cost right by some cost right it will be costly in terms of runtime so this it will give us a hint of using a mean Heap correct we will use a mean hip that concept come here mean hip right so because this gives us a hint of using a mean Heap data structure so what you can do if you are a new with the data structure right hip data structure you can search the Hebrew data structure okay you will see the mean hepatitis structure like that we will see that so what is mean hip right so mean Heap is a tree data structure that always store minimum value element at the top using some comparison like we have processity time here or a task in index in case of ties right so we will insert and remove all the task are logarithmic time okay so what we will do we will use mean Heap and will retrieve us from the repeated sorting of list okay since we can insert new task and retrieve the shortest task from the Heap correct we will do that right and logarithmic time okay so what we will do the flow of our approach is something like we will insert what we'll do we'll insert all the currently available tasks in the mean Heap we will add here okay all the uh all the currently available tasks in the mean hip okay and then we will pick the task with the shortest processing name and then we will pick the shortest time and then increase the current time by processing time of selective task right so what we will do now one point we have to note that what let's say that our current time is zero right we will take current time as a zero okay and the Heap is empty hip is empty correct and so the next task is we will enqueue at some value will take 10 20 will take okay so the CPU will sit idle until current time reaches 10. so instead of increasing current time by 1 increasing Time by plus 1 right we will update by directly 10. okay which will reduce the number of iteration in our approach and will improve the runtime so let's understand how I am telling right so if we'll talk about this is the task we have right if we have task one two four ten one nine two and so on right so this is our current time right after the Sorting of this one after sorting this is our sorted task right so now it will one you have to have this is not 10 here right we have to we have step now so now 9 will come here right and then 10 then 11 and then 12 right we have shift after Set uh sorting this position will get changed right then minimum current task is what 0 we are taking task index equating is 0 answer don't have anything we are empty so minimum is MPT and no tasks are available for the CPU okay what I'm saying minimum Heap is empty and no task available for CPU and current time is less than what in Q10 current time 0 in due time less than 1. so minimum Heap is empty no Tasker available for the CPU and then we can say current time is less than NQ time so we have to update our current time by 1. right next time what happened current time we have updated right so this is one right current time we have updated right and then this will come to here right so what I will do we will push all the tasks in queue time less than equal to what one and into the mean Heap so what we have to push we have to post this one right so we are going to push into the mean Heap here we'll push that and the increment task index is what by one we have to increase the task index here by 1. okay and so it will be look like here so we have moved from here to what here now current time is one task index is one right so and one top element here arrive as 2 0 correct so only one task in is in the mean hand we have correct that is this one now he will talk about the next right here from here right so what is happening we have inserted here correct now we will pop the element task with minimum processing time from the minhip but we have only one here right so we will increase the current time by time required to process the task right and then we will push the index of the task into the answer here right how like this we will do that so next time what happened we will push all the tasks with the enqueue time less than 3. and then into the mean HEB and then we have to increase task by one so what we have to do we have to push the word four and one this one 4 and 1 we have to push into the mean half right so we have inserted now we have to pop the top element right we have to pop the top element this one and then because this is the task with minimum processing right from the mean Heap then we have to add the processes time of the current time we have to update it right by one and then push in push index of the task into the current right then we have to push here okay sorry next what happened this is updated current time is 7 tasking is to answer is what 0 1 now both indexes com came here 0 and 1. now what happened we have updated these three right current time task index and answer index 0 and 1. the mean Heap is empty and no tasks are available for the current CPU right so we will check if current time that is 7 is less than in queue time that is 9 right so we will check with this one now we have to update the current time correct so current time is now updated with 9 because that is less than 7 is less than 9 so we have to update that right similarly task is remains same this one remains same now we have to push 2 3 this two three were into the mean Heap right and then we have to increase the task okay so let's see now you can see that we have updated the mean Heap by pushing two and three that is processing time 2 and index time 3 we have updated answer is still remain same now we will pop the top element and then we will add the processing time to the current task right and then we will push the task into the answer right so what we have did we have operated up current time task we have incremented and then we will post what on already I have added so now 0 1 3 will remain now we have to push all the time which is less than equal to 11 into the mean Heap and then we will push 1 2 into the mean Heap and we have to increment by one that will be happy here we have added top element of the mean Heap is one two now its current time is what 11 task now we have 4 and similarly we have to push again the mean Heap right here which is less than equal to 11 into the mean here and then we will push the mean Heap on mean Heap a 2 4 right and then we have to increment the task so this process Will Go On by updating the current time and the uh the array right so finally and finally it will look like we have the order now like that so the order in which the Tasker perform is 0 1 3 2 5 4 right so this is the answer we'll have and then we have we will return that now if we'll talk about the algorithm right if you have any doubt there please uh let me know now we have to initialize some data structure right for the algorithm right so the data structure we have to initialize next task sorted task and task processing order so next tasks will be used for mean Heap to store the task with the minimum processing time onto the hype sorted task we will use to array to store the task in the sorted order on the basis of the in queue time and the task processing order we will use to array to store the order in which the CPU will process the task then we will come to the Step 2 in which we will add all the tasks with your index to sort task and sort the array using the built-in order built-in using the built-in order built-in using the built-in order built-in function then we will initialize current time to 0 and while there are tasks in the sorted task we will uh while we these are the tasks in the sorted task that have no not been added to the minimum Heap or there are tasks remaining in the minimum view so what we will do we will check if the minimum is empty then we will enqueue the time of the next task is greater than the current time and so if then we will update the current time to the task in queue time so next we will do insert all the available tasks and then we will put into the mean Heap and if the task if we will pick the task on the top of the mean Heap we will increment current time by processing rhyme and then we will add into the uh task processing order right and finally we know that we will return the processing order right so what the things first we will initialize next task sorted task then processing order after that we will do we will add all the tasks to the sorted task and then we will sort the array using the built-in will sort the array using the built-in will sort the array using the built-in sort of function any function we will use next we will do we will initialize the current time to zero and while there are a tasks in the sorted task right till that is not empty right what we will do we'll add we will move to all the tasks right and we will do some uh update updation right in the other field first we'll check the mean Heap is empty right what we will put we will check the greater task right from the current time and we will insert all the tasks and then we will pick and then it will do that finally we'll come to here as you can see that what we have priority we have taken first priority key right why we have taken the private key here because this is our work as a next task right and so we have to sort based on the mean task right processing time or main task based on what mean task processing and then we have to store in queue time and processing time right so we have to take the priority queue then we will take like a b right like that we have to do sorting in build functionality of the Sorting we have to make it then int sorted task we have to use the task length we have to use right this is the input we have right so we have to take task dot length and then we'll make a loop here right for all the tasks right then we will take sorted task I zero and we will update from i 0 right and then eyes I and one then we will use task of I and 1. and then sort of task is what I have to and then that is I like that we have to update our sorted task right and then what we have to do we have to use array.sort in which we will pass what array.sort in which we will pass what array.sort in which we will pass what sorted task and then AV it will compare the value and it will sort all the sorted tasks right then we will do we will take a task processing order and this is the same as the length so now almost all the initialization we have done here right now we will take initialization for current Step 2 we'll use this one this is our step one right now we have at step two now we have to update current time task index or answer index 0 right now we'll come to this uh what we can say step three and then we will uh update what we will uh we will use we have initialized right initialize current time to zero task index 0 and this so after that we will come to step three this one and here while there are tasks in the sorted task array that have not been added to the mean Heap there are tasks remaining in the mean hip right so what we will do we will check if the minimum is MPT if the input time of the next task is greater than the current time so if so what we will do then we will update the current time to the next task in queue right so what we see first we are checking here right we are checking here if that is empty if this is empty right then we will check current time is less than sorted task right if that's the case we will update the current time if current time is less than the sorted task right index at 0 then we will update this one right and then what we have to do and we have to update the next task right insert all the tasks here those tasks in Q term is less than or equal to current time right and then we have to pick up the topmost minimum Heap increment the current time by its processing time and then we will add it into the task processing time right so we'll pick the top element here right we have to pick uh pick the task on the top of the mean Heap and then we have to increment right so what we will do we'll take the index next task pick 2 then we will remove next tasks that remove then we will update the current time by its processing time right we have updating here and then what we will do we will add its next index we are updating right next we are adding its next adding its index to the task processing order right and then if that is done this Loop is done means the 4 is done the fourth is done right the first previously watched here to here then we have did sorting right this was the Sorting we used to do sorting here too this was third this was about four and this is our fifth step okay because we have just sorting also here and then finally we will return the five this is our complete fourth step and this is number five okay let me explain again foreign we have to summarize once again right see what we are doing here first we will first what we have to do we have to take uh we have realized some data structuralized so we have to initialize data structure like what next task we will do then we have to sort a task right and the task processing right so we have taken next task that is to mean Heap to restore the task with the minimum processing time onto the Heap on to the top right and then we will do sorted task we will take and sorted task is used we'll use to array to store the task into the sorted order on the basis of year in queue time right then we will take the processing time right we will take a task processing order and this array is to store the order in which the CPU will process the task then in Step 2 we will update our current time is equal to what 0 right so after sorting this is our step one in which we will take priority next task sorted task and task processing order three things we will take and this is the Sorting sorting we have to do sorting right and the Sorting will do uh this Step 2 right coming to um line number 14 the current time equal to zero that we in a slice current time to zero that is our step three next what we will do we will come to while loop right we will come to while loop and then while there are tasks in the sorted order while there is a task in the sorted order task right sorted.task sorted order task right sorted.task sorted order task right sorted.task right what we will do we have not been added the mean he and there are tasks remaining to the mean Heap right so we will check if the what we will check if the mean is empty right so next class does dot is simply will check right and then if the input time of the next task is greater than the current time right so first we'll what we'll do we will update the current time right if that is not the case right current time if our uh if the in queue time this is our in queue time right in queue time is greater than current time so then we will update the current time here we are updating and then we will and the next task will be enqueue and then we will insert all the available tasks right we will update all the available tasks on the next task right how we'll pick the task on the top of the mean Heap and then we will increment the current time right and then finally see next test of peak we will do and we'll pick the task on the top of the mean here right and this is our processing time similarly build will do what will do for its uh we will remove from the next class then we will update our current time by processing and then finally the processing is updated right then we will return the processing task order next if we'll talk about the complexity right so n is the number of tasks so time complexity is will be what o of n log n and then the space complexity of n so why we are taking time complexity is o n log n right because see time complexity we have created one sorted task right which is a deep copy of task array and that is taking what of O of n right o of n and we are doing sorting the task array and that sorting will take n log n time correct so we will push the pop we will push and pop task once in the mean Heap and both operation will take o log n correct or log n and for each time thus it will take n log n time in its total how o of n plus n log n and that is equal to what give me one minute huh so I was saying for this one right we have to do what we have to do sum right that we have o n when we create the sorted task and which is a deep copy of task array right that is come of n time it will take then we have what we are doing sorting sorted task we have to do certain right and that will take part o of n log n correct and we used to push and pop the each task once its minimum Heap and both operation takes what of log n for that one and if we and what word for it will take over o log n right time for each element so it will take total what n log n sign right so if we calculate this one then what happened we have n Plus n log n M plus n log n this is for one element so an element which what this one so if we'll talk about the summation which is equal to what o and log n right this is the time complexity and the space complex Implement of n because we are taking one array to store all the uh n task and that is our sorted task right sorted task array right we are taking and the mean Heap will also remain at the end task right so if we'll talk about plus mean Heap right sorry m i n mean here then it will be what o n plus n and that is what or n right so this is the extra space we are talking and we are taking thank you guys if you have any doubt please bring me the comment box thank you so much
Single-Threaded CPU
minimum-number-of-people-to-teach
You are given `n`​​​​​​ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `i​​​​​​th`​​​​ task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing. You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way: * If the CPU is idle and there are no available tasks to process, the CPU remains idle. * If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index. * Once a task is started, the CPU will **process the entire task** without stopping. * The CPU can finish a task then start a new one instantly. Return _the order in which the CPU will process the tasks._ **Example 1:** **Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\] **Output:** \[0,2,3,1\] **Explanation:** The events go as follows: - At time = 1, task 0 is available to process. Available tasks = {0}. - Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}. - At time = 2, task 1 is available to process. Available tasks = {1}. - At time = 3, task 2 is available to process. Available tasks = {1, 2}. - Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}. - At time = 4, task 3 is available to process. Available tasks = {1, 3}. - At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}. - At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}. - At time = 10, the CPU finishes task 1 and becomes idle. **Example 2:** **Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\] **Output:** \[4,3,2,0,1\] **Explanation****:** The events go as follows: - At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}. - Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}. - At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}. - At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}. - At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}. - At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}. - At time = 40, the CPU finishes task 1 and becomes idle. **Constraints:** * `tasks.length == n` * `1 <= n <= 105` * `1 <= enqueueTimei, processingTimei <= 109`
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
Array,Greedy
Medium
null
1,008
okay today's li coding challenge custon is constructing a binary search tree from pre-order traversal we have a from pre-order traversal we have a from pre-order traversal we have a binary search tree and we have wrong pre-order traversal on top of that tree pre-order traversal on top of that tree pre-order traversal on top of that tree to obtain a sequence of note values and maybe that's a cereal that serialization we have done so now we need to reconstruct the binary tree and return reference to the room note so basically looking at the example here we have a binary search tree 8 5 10 1 7 12 so the property of a binary search tree is that all the left descendants of a node it's the value is going to be smaller than the node value and all the right descendants value is going to be larger than the notes value and that applies to every node in the tree for pre-order travel so it's basically we'll pre-order travel so it's basically we'll pre-order travel so it's basically we'll visit but no first then we visit all the left of descendants and after that we go back to visit all right descendants of the node and that applies to recursively on the river you know throughout the traversal so taking example here the this is a binary search tree because for every node like 8 here all the nodes descendants towards the left is gonna be smaller than it and all the values that's larger than 8 it's gonna be part of the right road right children's here so that's binary search tree and the ordering here is preorder traversal because it's a 8 5 1 7 so it's a finishing the rest left part first and then go to the right side it's 10 and 12 so that's a pre-order traversal order so that's a pre-order traversal order so that's a pre-order traversal order here so since that the solution to this question is pretty much gonna based on the 2 to 2 concepts that combine right when you look at the sequence of values here since it's a pre-order traversal pre-order traversal pre-order traversal if we process the nodes from left to right whenever we see a new node here one last seven or ten it's guaranteed that the child of the parents node has already been processed because the parents are towards the left of that so whatever we process and accepted the very first one which is the route we're going to try to figure out to which of the node we have already processed to which node we assign this node this new node to be the either the left child or the right child of the node that we have already processed so that's based on the preorder traversal property we're gonna always handle the parents first before we do the children's then to also utilize the property of binary search tree I guess when we whenever we see a decline in value since that the second one is going to be a child towards the nodes from the left and for the property of binary search fee the smaller value are gonna be the left children towards the larger value so in the case that we see something like a fight five one the last of no that way process has a value that's just larger than the current node immediately next node the next node is going to be a left child for that previous node and just to keep scanning through this example here whenever we see an oh that's a larger than the previous node it has to be a right child into to that node or to the parent node of that node or even going back further so to determine to where which node we assign node seven to be all right children off is to is determined by looking even further so the seven cannot be a parent for one because if seven is a seven cannot be a right child to one even though you satisfy that seven is larger than one so it's not that it can be it can possibly be a right child for one if the if we don't care about the parents but if that's the case seven if we attach seven to the right side of one then the seven is larger than the five here so it violates that the left dependents are smaller than the note so we go back and check is seven smaller than eight that's the case then we can safely attach seven towards the right children of five so basically whenever we see a value that's larger than the previous node we have processed that suggests we should check which parent node we should select from the previously processed node and just attach that no that's the right child to that node it's determined by the body was kind of a sandwiched in between like the case five eight seven here another special case for how to handling the right children is also depicted in this picture example here so once we done with the left child we pop all those notes out of the stack we are left it is a stack with a one note here 8 then we encounter the value 10 since 8 has no parent node meaning that it's the root node pretty much the root node here then we find a larger value it has to be a child towards that node even though that doesn't have any kind of parent anymore but that's the only place we can plug this node all to so that's pretty much the strategy it's gonna be a linear time scanning through the pre-order time scanning through the pre-order time scanning through the pre-order traversal orderings and we're gonna use a stack to keep track of them know that we have already processed for every new node we try to assign it to be either a left child or right child of the correct a parent node so there for left child is easy once we see immediately decline the values we know where to assign it other otherwise the value might go up then we have to you know pop out some processing node and go back to the right for apparent location and establish the right children connection so that's pretty much the strategy the yeah let's start CODIS so initially we just initialize some variables to how the root node which we only need to retire and we have a star to keep part of nodes which initially is empty because we haven't process anything yet for the values in the pre order traversal result we're gonna construct a new node with that value and then if we haven't assigned handle the rule note yet we should just let the route be this particular node and for each iteration in this four loop we're going to handle one note and after we handle that we should push it back to the push it onto the stack here and if this note is not the arundo then we have to assign it to be a child of some note that we have already processed the check for left charging is easy if this current value is smaller than the previous note that we have processed which is on top of the stack I'm skipping my hair and skipping my sod otherwise we will do a justement of the parent to find the place where we actually savage this higher value here so after this we're basically going from 1 to 5 and then the top of the stack we also plop out to 5 and we find that the top parent top 8 is larger than 7 5 is the one that we popped out we establish a right link to it and we can safely discard the rest you know and in any of the three things here because we have already processed them entirely so that's pretty much it let's try to run destroyed examples to see there is a valid comparison problem right looks okay so let's try submitted okay so that's the question for today
Construct Binary Search Tree from Preorder Traversal
binary-tree-cameras
Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_. It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases. A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`. A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`. **Example 1:** **Input:** preorder = \[8,5,1,7,10,12\] **Output:** \[8,5,10,1,7,null,12\] **Example 2:** **Input:** preorder = \[1,3\] **Output:** \[1,null,3\] **Constraints:** * `1 <= preorder.length <= 100` * `1 <= preorder[i] <= 1000` * All the values of `preorder` are **unique**.
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
1021
225
hello everyone welcome back uh here's van damson and today we got a really interesting coding problem that's going to deepen your understanding of basic data structure so stack and cues so we will be implementing a stack using just cues Yes you heard it right so let's quickly go over the problem we have to implement a stack using just cues so the stack should suppose uh four basic operations so it will be push pop top and empty and first glance you might think wait stack and queue are entirely different so how can one mimic the order well that's the beauty of this problem and I will show you exactly how to do this all right so let's dive into python coding and also I will provide code in under programming languages in the description below so first we will start with init a function so Q will be our DQ then what we will do is Implement push so self queue append X and four in range of land surf Q minus one self-q append self queue pop left self-q append self queue pop left self-q append self queue pop left so in it we just importing uh and initializing a DQ so mtq and then we implemented push and the push message is where the magic happens so after appending new element we rotate Q to make sure the last element and up at the front why because we want to mimic a stack and the last element pushed should be the first one to be popped so now let's Implement pop so return self queue pop left yeah so we have implemented uh pop meters so the pop method is straightforward since we have rotated the queue in the push method the element to pop is right at the front so now with top so top will be return self Hue 0 . so again top is simple method because . so again top is simple method because . so again top is simple method because of the work we did in push it just returned the front element of our queue and now empty method so return then self Q equal zero so lastly empty checks if the queue is empty so signifying that the stack is empty so if it's equal zero it's empty so now let's run test to verify it's working so yeah for test cases all is good and we created a object my stack and then we tested some particular method like push one push two top pop and empty so now we can submit it for and synthesis cases to verify it so yes our implementation with 63 with respect to uh runtime and the time complexity is o n so it's linear and yeah so next run and it's 36 millisecond and complexity is O and so linear because of the rotation but pop top and empty are o one space complexity uh so o and interval and there we have it a stack implemented using just a Q and this exercise is a great way to understand the underlying operation of the basic data structure and remember the codes for other languages are in the description and yeah I think my first run was even faster you can see that this is exactly the same implementation and yeah it took just 24 milliseconds so probably there is some standard deviation on uh test cases so yeah we think 99 and 74. so if you found this video helpful and know how to implement stack using queue don't forget to hit the like button subscribe for more awesome uh coding adventure and uh yeah so see you in the next one keep practicing and happy coding
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
518
everyone welcome back and let's write some more neat code today so today let's solve the problem coin change2 we already solved the first one and i'll link that somewhere on the top right of the screen or somewhere in the description if you want to watch that video you don't have to solve it before solving this problem but it'll probably be easier to solve this problem if you do so similarly we're given a list of coins each representing a different amount right a different denomination and we're given a second parameter an integer amount and this is the amount that we want to sum up to it's a total amount of money that we want to sum up to given these coins and specifically we want to know with these coins and this particular amount how many different combinations are there that we can sum up to this amount of course if we can't ever sum up to that amount we can just return zero and we can assume that we have an infinite number of each type of coin so that kind of hints to you that this is an unbounded knapsack problem which i talk about that category of problem in one of my videos i think it's called top five dynamic programming patterns if you want to watch that video and so this is kind of one example that they give us and you can go ahead and read it if you want there's four different ways to sum up to the amount five if we're given three coins one two and five now when we say number of combinations we can't reuse the same combination right so if we get two to one uh two one these three coins sum up to five we can't just change the order and then call that a different combination the order doesn't really matter so now let's kind of get into the explanation let's talk about the brute force explanation which is going to be exponential with uh c to the power of n whereas c is let's say the number of coins that we have and n is the total amount that we want to sum up to that's the exponential solution we can uh use memoization on that decision tree to actually get the time complexity to be big o of uh c times n i'm actually just gonna replace the variable c with m so let's call it m to the power of n that can be reduced to m times n uh this time complexity that's the best time complexity we can do but there is one optimization with memory complexity that's pretty difficult to come up with but i'll kind of explain it to you so let's get into that so same example we're trying to get the amount five with these three coins let's just think about the brute force so initially we have a sum of zero right we'll put that in a node and we have decisions we can make right we're just gonna make three decisions right we could either choose a coin of one that would give our sum to be one uh we can either choose a coin of two that would give our sum to be two we could choose another coin to be five that would put our sum to be five right and then we can continue this approach the only thing is how do we guarantee that we don't have duplicates right because if i go down this path and i choose another two and then i choose another two right here we have a one two that gives us a sum of five so that gives us the amount that we wanted here we could do the same thing couldn't we could get a one and then we could get a two this is the same uh combination of coins just a different order right we don't want to get into this case so how can we guarantee with this decision tree that we won't ever get something like that well how about every time we make a decision right we made three decisions in this case we put some rules on that decision how about when we go down this path we are allowed to choose we chose a one right we chose the coin one and we're allowed to choose any coin that we want right down this path we can continue to choose a one we can choose a two we can choose a five if we want but we want to make sure that this never gets any duplicates as this one so how can we guarantee that how about this path can never choose a one how about we just don't let us choose ones anymore down this path to make sure that we never have duplicates on the other side of the decision tree right we're free to choose any twos and any fives that we want but we just can't choose once hopefully it makes sense why that guarantees that we won't have duplicates right because this path has at least one right and this path will never have any one so obviously neither both of these paths will never have the same combination i hope that makes sense and similarly over here when we choose a five we're gonna say that okay we're not allowed to choose anything except fives right we can't choose ones or two that'll guarantee that these two are not the same right because we have a two here and we'll never have any twos down this path so they'll never be the same so that's the main idea of how i'm going to eliminate duplicates so now we've gotten to the point where we have the m to the power of n solution right the base case is going to be if we get to the amount so you can see on this path we already reached the amount right we have a total of five that's exactly the target that we're trying to get to now let's say we chose a five over here right we chose a coin of five that would put our total at seven if we go over the total amount then we're going to stop right then we're just going to return 0 and then stop going down that decision so those are the main base cases and by the way how are we going to implement that idea of if we chose a 1 or chose a 2 we're not allowed to choose any other certain coins right we're gonna be maintaining a pointer uh let's call it i it's gonna point at some index of coins right so if we chose a coin of one then our index is going to be here right at the coin one and if we chose a coin of two then our index i is gonna be at this coin two and what when our index is at a coin then it basically means that we're not allowed to choose any coins with an index less than it so basically anything on the left side of this coins array on the left side of our pointer i we're not allowed to choose those coins right so that's how i'm going to implement it in the code and this is important because now that we actually move into the memoization solution where we're going to be caching the repeated work because when you look at this decision tree it's going to be pretty inefficient right like i said it's going to be m to the power of n where m is the number of decisions we can make in other words it's the number of coins that we have n is the total amount right because the amount is what's going to determine the height of the tree so when we implement this recursively let's call it dfs we're going to pass in two parameters one parameter is going to be i which is going to tell us what index we're at in coins it could be you know any of these uh positions and we're going to pass in a second parameter let's call it a which is whatever the current amount happens to be remember if the amount ever goes over five which is you know the target that we're trying to do then we're going to stop right so basically the total number of about possible values a could be is going to be whatever that target value is so when you look at this right how many different combinations could this dfs be called basically the total number of coins that we have right let's call that m and the total amount that we're trying to sum up to let's call that n so the total possible number of ways this dfs could be called is m times n so if we cache the repeated work right if we call it with the same values we don't wanna have to recalculate the same thing if we call dfs let's say uh on index one and let's say our amount happens to be two and we call this multiple times we don't wanna have to recalculate all that work so we can do caching with that so that's basically memorization we're going to be putting that in memory and then we won't have to redo that work so at this point we've gotten to a solution that will pass on leak code the time complexity will be m times n and the memory complexity will be the same but now i'm going to show you the dynamic programming solution which will actually have the exact same time and space complexity and then i'm going to show you a slightly more advanced dynamic programming solution which will actually reduce the memory to instead of being o of m times n it'll actually be o of n this is one of the reasons why dynamic programming is important because sometimes the dynamic programming solution can actually be more efficient than the recursive memorization solution so if you want to check that out continue so now let's do the dynamic programming solution you can see i drew a 2d grid where we have one dimension being the amount the you know zero from zero all the way to up to five and one dimension being the coin we had three different coins one two three and we know the base case is if the amount is zero right and what value are we gonna put in here when the amount is zero how many different combinations is it that we can sum up to zero well the base cases let's just put it as one right because that's what's gonna make the math work out and it kind of makes sense right how many ways can you sum up to zero just one right regardless of which coin we start at so what does this position mean it means that if we could only choose from this single coin five how many different ways could we sum up to zero it's going to be one different way right and this position is going to mean if we had two coins available to us two and five how many ways could we sum up to the amount zero it's going to be one right and so on for an arbitrary position like this the question is uh how many different ways can we sum up to the amount three using these two coins from here it would be using these three coins right so what order would it make sense to uh compute these values probably bottom up right that's why they call this bottom-up that's why they call this bottom-up that's why they call this bottom-up dynamic programming we're going to start here and compute the value that goes here then we're going to compute the value that goes here and then start from here and then do the same and looking at it since we're doing it in this order you're probably thinking i probably should have you know rotated this instead i should have put the amount over here and the coins over here because then we can actually compute it like this and you're right but there's actually a way that we can compute it like this that i'm going to show you and actually this way if we do it in this order is going to be better memory complexity let me show you why that's the case though so let's say starting from this position right we're trying to sum up to the amount one if we use a coin we can only choose one coin that's available to us right we can choose a five coin what happens if we use a five coin uh then our amount that we're trying to sum up to is gonna be one minus five right that's going to put us at negative four so from here i'm gonna go to negative four now that's out of bounds right so that kind of tells us that there's zero ways to sum up to the amount one if we only have a single five coin available to us next let's compute the value that would go here so we have two choices in this case actually because now we have two coins available to us so we can choose to use the two coin what happens if we use the two coin well then our amount one is going to be one minus two which is going to be negative one right so you know if we're trying to get the value here then you know our arrow is going to go over here out of bounds which is negative right so that doesn't work and that's if we choose the two coin if we choose the five coin what are we going to do well then we're just going to look directly below us because we're still solving the same problem amount equals one but in this case we're choosing not to use the two coin we're just gonna use the five coin but we see that's a zero value down here so in the end we'll also end up putting a zero here and from here we're going to do the same thing we in this case we have three coins available to us if we use a one coin what is that going to put us well we started at we're trying to get to the amount one if we use a one coin we'll do one minus one equals zero so okay then from here we're gonna you know go to the spot that has a value of zero right that's directly to the right of us right that's where zero is so then we're gonna take this value add it to this position right so one is gonna be added here but we don't have to choose this one coin right we could actually choose the two coin we could ask okay instead of choosing one what happens if we try to sum up to the value one with two coins available to us in that case we look directly below us and we see that there's a zero there and we add zero to this position one plus zero will just be one so we can leave a one in this spot so and then you can kind of just continue doing the dynamic programming just like this one thing you might notice though let's assume for an arbitrary position like this one if we use the two coin that'll put us amount is four we'll move two spots to the right where amount is two right so we're looking all the way to the right we could also say okay we're not going to use the two coin right we're gonna use all the other coins in that case we'd have to look directly below us right that's perfectly fine this perfectly works but one thing you're noticing for a arbitrary position like this one we have to look both to the right and we have to look below what does that mean that means potentially we have to have the entire uh two-dimensional array in memory because two-dimensional array in memory because two-dimensional array in memory because when we're looking directly to the right of us we're not just looking one spot we could be looking two spots three spots five spots right depending on what coin value we have so in that case we're going to have this entire two-dimensional grid in memory there's two-dimensional grid in memory there's two-dimensional grid in memory there's actually a different way we can do this problem if we uh compute this in this order right from here in that way we won't have to have the entire grid in memory we will only have to have up to two rows uh two rows like these we'll only have to have up to two rows in memory and a row will only be as large as whatever the max amount happens to be which means the overall memory complexity in that case will be big o of n now you probably don't need this solution to pass your interview unless it's like a super hard interview and your interviewer is looking for it but i'll show you both of the solutions anyway i'll show you the code for this solution and the code for the memory solution of o of m by n okay so in this spot we're asking the same question if we only have one coin available to us can we sum up to the amount one we can't write because then we go out of bounds so in this case let's just put a zero okay ask the next question if we're summing up to amount two with just one coin available to us can we sum up to that amount no of course we can't right so and that's gonna be true for this position right can't sum up to three can't sum up to four either but once we finally get to five with a single coin of five well what's going to happen okay we use our coin of five right so that means we look five spots all the way to the right and over here in this spot we find a one is waiting for us right that's our base case that's where amount is equal to zero so we take that one and then we add it in this spot right so now we've done that so there's one way to compute the amount of five if we only have a single coin available to us but remember the actual problem that we're trying to solve is all the way in the top left corner if we had all three coins available to us because we do we have an unlimited supply of all three coins available to us so how many combinations can we do to get to this amount five well let's continue row by row just like i mentioned right so now we will need to keep this row in memory for us to be able to compute this row but once we're computing this row we actually won't need this bottom row in memory anymore and i'll show you why that's the case so now if we had two coins available to us how many ways could we sum up to the amount one well if we use a two coin we'll go two spots to the right which is out of bounds so we don't put anything right so far it's we're at zero so if we choose not to use the two coin and we say okay we're just going to use all the remaining coins then we look directly below us again we find a zero so in this spot we say that there are zero ways to sum up to the amount one if we have these two coins available to us which makes sense right there's no way you can get a one if you have a two and a five available to you now let's do it in this spot so if we use the two coin in this spot we'll move two spots to the right which will we find a one here right so we can add a one here uh if we choose not to use the two coin we look directly below us which is a zero so we don't do anything in that case right so we leave a one here there's one way to sum up to the amount two with uh these two coins available to us in now i'm going to start going fast because i don't want to waste too much your time so in this spot we're gonna look directly two spots to the right which is a zero or we're going to look directly down and that's a zero so we'll still put zero here notice how we're looking multiple spots to the right but that's okay because we have this row in memory but when we look down we're never going to look multiple spots down that's the key that's why we only need o of n extra memory so let's continue so from amount four uh we're going to look two spots to the right there's a one or we'll look down that's a zero so we put one plus zero one here again two spots to the right that's a zero or one spot down that's a one so one plus zero we get a one let's continue so from here we'll look once uh spot directly to the right that's one we'll look down that's zero so we'll put a 1 here again from here we'll look one spot to the right that's a 1 we'll look one spot down now we get a 2 right because we're adding these two values together that makes sense right because amount 2 how many different ways could we sum up to this amount too if we had all three coins available to us there are two ways right and from here we'll look directly to the right by one two plus directly below that's zero so we'll put a two here from here again directly to the right directly below 1 plus 2 that's going to be 3 and from here again directly to the right and directly below that's going to be 4. so we get a solution of 4. is that correct well when you come back and look at the problem description with that example yeah that's what the amount was that's good now we're ready to dive into the code okay so now let's jump into the code and since this video is probably already too long i don't want to spend too much time coding it up so let me just show you the code and it will be in the description this time if you want to copy and paste it or take a look at it so this is the recursive solution the time and space complexity is big o of n times m just like i mentioned in the explanation you can see that we have a cache in this case the cache is the hash map the base case is just as i mentioned right so one is if we actually get to the target amount that we're looking for remember we're passing in two variables the index and the amount a if we get to the target amount then we're going to return one if we go over the target amount that's that means we cannot possibly sum up to the amount we return zero if we go out of bounds meaning i is out of bounds right that basically means now we decided that we don't have any coins available to us uh that's going to be we're going to return zero as well in that case uh and the fourth base case is if we've already computed this if we've already computed it we can take it directly from our cache and then return it the other case is now this is the base case or not the base case this is the recursive case right you can see i'm calling dfs twice one is where i'm calling dfs is where we are choosing the coin that is at index i in that case we leave i just as it is and then we say okay the new amount that we have is a whatever the amount that we previously had plus whatever coin happens to be at index i right so we're choosing the coin at index i that's one decision the second decision is if we skip the coin at index i in that case the amount stays the same right we skipped a coin so we don't change the amount but we do have to increment our index i because we're skipping this coin right now we're going to choose the next coin so that's the main logic behind this and then whatever the result of this happens to be we're going to go ahead and throw it into our cache and then return the value from the cache and so that's the entire dfs all you have to do is call the dfs starting at index zero starting with our amount being zero and then we can just return that result right up above now i've copy and pasted the dynamic programming solution where we had to use two dimensions of memory so this is the same memory complexity big o of n multiplied by m right this is the one that was sub-optimal for dynamic programming so sub-optimal for dynamic programming so sub-optimal for dynamic programming so you can see i'm using two dimensions for the dp cache and then the logic of this is pretty much the same as i showed right we're going to be going from starting at amount equals one uh we're going to see how many different ways can we sum up to that amount right and then our index i is uh going to be at the last coin so length of the coins -1 where we only length of the coins -1 where we only length of the coins -1 where we only have one coin available to us right i is gonna be uh decremented each time because we're gonna be adding more and more available coins each time but so suppose we had uh this many coins available to us that's what i says and a we're trying to sum up to this particular amount what is that going to be well one decision is if we skip the coin at index i which is just going to be dp of a uh with i plus one you can see that this line of code is the exact same if you look below this dfs is the exact same as this line of code right you can see the parameters are the exact same right all i'm doing is passing in a i plus 1 here same thing here right a i plus 1. now the other case is going to be with if we actually do use the coin at index i right so we're going to take a minus uh coins of i why are we doing minus here instead of plus down here well you could do it you can implement it how you want i did it like this because a is the target amount if we use this coin then we have a certain amount left over now we're confirming that whatever that amount left over is greater than or equal to zero because if it's negative that means we went over right that means we use too many coins so if this is greater than or equal to zero then this line of code is just is completely analogous to this dfs down here if you can see it this dfs where we pass in i uh a plus coins of i you can see that instead of passing a plus coins of i'm doing a minus coins of i right but this is uh if you get confused by this i would recommend going back to that two-dimensional grid that i was that two-dimensional grid that i was that two-dimensional grid that i was showing you because this is exactly the same as that now last but not least i have went ahead and copy and pasted my code for the solution where the memory complexity is actually just big o of n the time complexity is the same as the above solution but the memory complexity is less you can see that's exactly what i'm doing here right we're not actually using the full memory we're not using two dimensions of memory we just have one dimension and you can see just like in the two-dimensional matrix that i showed the two-dimensional matrix that i showed the two-dimensional matrix that i showed the main difference between the above solution and the below solution is just the order that we're computing the uh the two-dimensional grid right you can the two-dimensional grid right you can the two-dimensional grid right you can see in this case the outer loop is we're iterating through the amount and the inner loop is where we're iterating through the coins in the other case the outer loop is iterating through the coins and the inner loop is iterating through the amount but other than that the entire solution is pretty similar right like here you can see i'm pretty much just i have one row that i'm maintaining out here and then i'm using next dp to be the next row that we're computing and then at the end i'm just reassigning dp to be next dp right at any given point we're only going to have two rows in memory we're not going to have an entire two-dimensional grid to have an entire two-dimensional grid to have an entire two-dimensional grid so i know this was really confusing and this is probably a long video i wasn't able to spend as much time on the code as i would like but i hope that the drawing explanation was able to help you out this code will be in the description if you want to take a look i guess let me just run it and prove to you that it works so i'll run the code that is below which is the most optimal solution that i was able to come up with the time complexity is n by m and the memory complexity is of n you can see on the left that it does work and it's pretty efficient 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
Coin Change II
coin-change-2
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`. You may assume that you have an infinite number of each kind of coin. The answer is **guaranteed** to fit into a signed **32-bit** integer. **Example 1:** **Input:** amount = 5, coins = \[1,2,5\] **Output:** 4 **Explanation:** there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 **Example 2:** **Input:** amount = 3, coins = \[2\] **Output:** 0 **Explanation:** the amount of 3 cannot be made up just with coins of 2. **Example 3:** **Input:** amount = 10, coins = \[10\] **Output:** 1 **Constraints:** * `1 <= coins.length <= 300` * `1 <= coins[i] <= 5000` * All the values of `coins` are **unique**. * `0 <= amount <= 5000`
null
Array,Dynamic Programming
Medium
1393
416
all right let's talk about partitioning called subsystem so giving a num empty array nums containing only positive integer so final array can be partitioned into two subsets such that the sum of an element in both subset is equal so this is the array and then you can partition to you one by five and eleven so they just stop holding and i'm going to use uh 2d array and for every um for every step i'm i go through right i will memorize it and this is called memorizing dp or you can say memorize the recursion so this is going to be boolean since we return boolean so in and i'm going to say in and go to num problem and also i need to um sum every element up in the in array so when i add everything up right if this number if the sum is all right then you cannot divide two to subset this is because if a number is all right this is only be the one subset only you cannot have two subsets so um and then if some mod 2 is not equal to zero then you just compose and then if that is true right if some mod 2 is an even number then you can actually divide into the half divide your number into a half and then and when you uh when you initial your dp you can reduce a lot of memory because when you cut into half right you only need to know the maximum for the dp will be 11 not 22 right so i would say some will divide by 2 right now and then let me show my dt so my dt boolean the sorting the rule will be n plus one you need to include the index zero and the column will be sum plus one right and this also includes the in this indexes zero right so later i will just use my hover function so can position and what do i need to plus i need to pass the num i don't need the plus 50 if it's global variable i need to pass the current sum and i also need a pilot index which is starting from zero okay so i need to initialize the hyper function so i'm going to say in some index so if the sum is actually equal to 0 this is true right you don't need to worry about like if because we need to reduce from this number to zero right and then if that's true just written true so if the index is equal to the number of lengths equal and also sum is less than zero this is the transpose uh this is all a bomb and this is how you did not too much and this will be right and also it's a dp that index as sound it's not normal which means we'll traverse already so just return dp in next time and the last one the last return will be easy so i'm going to return so you still have to initialize i mean you still have to assign your dp index and sum equal to something right and this is the last scenario you have to think about it so um so you know what you either move your index um you either move your index uh one union right or you all the dealer numbs right so if you want to delete fire right and we can actually choose uh index plus one and then some minus nums index and if you don't want to delete it for uh for example if you don't want the daily level right then you can just move on your next index you don't delete your nums index at this point at this position right so this will be a little bit tricky so let me just quote it and you'll be able to understand so it's either norms so this is i want to delete this current uh value in this num and sum will minus now and if i delete it i need to move on the next one and also if this uh in this scenario i don't want to use this value but i still have to move on right so some index first one and this will be it and let me just double check and here we go so i hope i don't make a mistake and i do like koe will be another scenario to talk about it but in this case i'm not controlled so this will be a little bit um i would say it's pretty much like it's either you jump or you don't jump but if you do jump right and you want to know like you don't want to deduct your current value but if you uh don't jump right you need to uh dedicate your current um current value and move on so this will be like the scenario you have to think about it and let's just talk about the premise based complexity for the space this will be easy your initial your n times x and s represent the sum and definitely you need to traverse 10 times s the length of the nums array and then the sum so the final solution i will just copy and paste my unknown so this will be the solution and if you feel helpful subscribe like if you want it and then leave a comment if you have any questions and i will see you next time bye
Partition Equal Subset Sum
partition-equal-subset-sum
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,5,11,5\] **Output:** true **Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\]. **Example 2:** **Input:** nums = \[1,2,3,5\] **Output:** false **Explanation:** The array cannot be partitioned into equal sum subsets. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 100`
null
Array,Dynamic Programming
Medium
698,2108,2135,2162
673
A higher oil welcome to learn to repeat today will be looking at death eighth playlist change the name of problems number of longest in giving subsidies reduced to find the problem only bracelet given and different forms return the number of longest increasing subsequent where to find the number Off will be this 135 476 subscribe to subscribe the 1234 7 the subscribe to within into the two will be true sub sequence member jaipur district in the example this provide all the number to two to whose subscribe similar to draw subscribe example2 subscribe 30 ok Dada Boss 134 And Sun Alarm Set 992 Toofan Lauteng Sabse Images By Using Dynamic Programming For A Dynamic Programming Concepts Point Which Can Check What Is The Longest Subsequences Point From Here I Longest Subsequence We Createine ​​Are Right Createine ​​Are Right Createine ​​Are Right That Sainik Sharif And Hadith Number Give The Number Itself Can Be Long Subscribe So Let's Abhinished With Awal Elements That After All Now Like And Travels From Left To Right From Pintu Points 69 2012 0 Point 818 Decoration Is Greater Than Ji Check The Number As It Is Right And These Awards Is Great Dhung Hi Dhund subscribe and subscribe the Channel Please subscribe and subscribe pe click on hua tha agle nischay Ismail hum sab je is aham subscribe school life with subscribe plus hai tu main pehle subject one two aur swanand 52 length dars correct nagaland mit Jaay ajna hai check norms in terms of absolute truth against pimple bomb labs that i will be id for this subscribe checking amazon check-in amazon check-in amazon check-in to is magic not go power than anything element amazon reset my ji time when lagna reset-2 000 Name in this subscribe to the ring imagine you without this check this woman jewish istri so birth white choice norms of i will be plus one witch woman login element messages hai har chakra in this name jab ji so birth jo pada did not the k Jain increment in Sainik Tourist I question Shraddha Ji-20 I question Shraddha Ji-20 I question Shraddha Ji-20 Increment right to 10 particular number check per norms of witch 7:00 Subscribe I will be subscribed norms of witch 7:00 Subscribe I will be subscribed to again Abhishek name when display birth successful yes first all I will be F Z plus one witch Tuk place in the year in 3D included in increment jamshed check slums so born javid sprite i first clean z plus one witch place for the 12500 wipro and increment judgment channel subscribe like and subscribe button solid 4000 GN andher subscribe The Channel and subscribe the rate of devotees' most special friend rate of devotees' most special friend rate of devotees' most special friend big question is not too long a substance painter question is the number of subscribe school subscribe now to the condition of the members of the condition barfi use to calculate the site exams of a greater Namaje And Also Spicy Schezwan Sauce Here That Operation Read They Know Need To Find The Account Of Subsidies For The Weekend Programming Same Account Is Account Remove This And Beginning In Logic With The Countries With Account It Is The Longest River In Web Counter The Work In Both Cases in which a little too one person having the best long sequence and long subscribe before white similarly for the account the best will be and the correct number at only will be the best ones ok should be treated well who it well check dams after Idea Music Yes IDFI is this lesson you are ok and share it to you can check the account of ideal to counter widget that if deposit is part of the same subsequent show the account which I am and twitter account go again a guy next Par increase the counter ka nazara ka game e sanam jab jis din hum safai surajgarh as if we are vegetable so jab hum safed singh cases of missiles pen provided for selection in more subscribe to hai aise mila li changes patoda SIM subsequent subject math account of i Will be town top should improve should e contact department recruitment jobs in you again dashrath name subscribe i will be plus one two three subscribe kar were royal increment account gallery set me counter on ki ghanshyam das bile for juice garlic under a greater noida delhi subscribe the Video then subscribe to the Page if you liked The Video then subscribe to Previous Song Again Will Increment Ji L Aur Sunao This Lesson For His Sole Safai Job Lashman Singh Rathod MP3 Ki Main Account Will Be Account Object Which One Part To The Scene Sequence Ki Hogi And Increment Chahiye The Sofa Is Lesson For No Swar Increment Iron And Steel Reset Use This Point Is To Again 11117 Sonam Sabzi So Janam Safai Interested Let Safai Equal To Z Plus One How To Withdraw Its Object Laxman Is Greater Than Yourself In This South Asian Region Bittu bhaiya loot increment ji ki nine this lesson 7 shy bluetooth free k against subscribe sim a significant jai siyaram ki newbies first vegetable woman grind envelope 100 swati plus one president vikram thakur new song a subsequent snowfall in account still buried top gear which part Of This 1357 Phase Bank Account This Foundation President What Happens In Vway John Cena Prevented To 4 9 4 Lesson 7 Plus I First Fennel Z Plus One Is It Great Essentials Of I Dowse Replacement Share Plus One Is It Lesson 4 9 Do Subscribe 1357 Nuvve 341 342 That Show The Sri Leathers 300 Tourist Places Vikram 400 Veer and 376 Already Subscribe To Ko Shuddh Spite of Another Sequel Dhund Hi Dhund Ifir - 121 Smell of Eye - 1m Hi Dhund Ifir - 121 Smell of Eye - 1m Hi Dhund Ifir - 121 Smell of Eye - 1m and these awards are Voice Mail Sabzi This Plus One of the Rebel of Difficulty Kullu Valley of I in that is the different subsequent right in that case how to increment discount of subsidized rates water is account of J 's juice me to the counter FIR 's juice me to the counter FIR 's juice me to the counter FIR ki facility spot boy doing in balance condition hair few days ago cleaning which is this is Equal to A to Z Plus One Sooji Screen Adheen Patience Subscribe Hai In That Case Enter Can Be Another Subscribe Button Subah To Increment The Counter How Can That To Counter For The To subscribe The Channel and subscribe the Video then subscribe to the world will be a 800th Urs Share Manju Sahai in Subedar in Preventing the Value of Account of Idle 2 Sunao Account Welcome to And They Can Attend for Returned Test Will You Can't Talk to You Can Gain for Returning to Enter into Which Can Directly Check What is the Match Off the Left Leg After Say Z2 and Something Right The Secrets to the Value of the Writer of the Last Value One and This to Back 210 Will Be Late Do Jai Hind Sir Marriage Account of Defiance of Yesterday Morning Not Go with Lord S Well s after 10 back to one more luteum 10 inch 11 what is the current account it andheri so let's look at the court for the year and subscribe to the channel now subscribe to the Video then subscribe to the Page if that this vinegar you fruits and ing Point Swaha is first one and misses always imagine if placid in the same condition rate features Norms of a Greater Noida and also Spicy Schezwan The Amazing Preventing the length of the attachment and lag that and with the same condition exists but at the same Time EFI is equal to late for jobless 180 Zodiac is doing a branch of tobacco and subscribe and that model and current long subscribe in the case and from obscurity subscribe and subscribe the Channel subscribe is lineage against max value day is need to check the Connect In The Amazing Call I Can Just Have FD Account Member Sample Edition Hota Account Tube Find How Many Account Regards And Written Test Result Navodaya Complexity of Defiance of Cancer Due to Behavior Two for Rule 10 Complexity of Beneficiaries in Size and What is the Language of The day is so let's submit 10 inch one network point soon assigned to college sector like this video various questions page to right then comment section thank you
Number of Longest Increasing Subsequence
number-of-longest-increasing-subsequence
Given an integer array `nums`, return _the number of longest increasing subsequences._ **Notice** that the sequence has to be **strictly** increasing. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 2 **Explanation:** The two longest increasing subsequences are \[1, 3, 4, 7\] and \[1, 3, 5, 7\]. **Example 2:** **Input:** nums = \[2,2,2,2,2\] **Output:** 5 **Explanation:** The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5. **Constraints:** * `1 <= nums.length <= 2000` * `-106 <= nums[i] <= 106`
null
Array,Dynamic Programming,Binary Indexed Tree,Segment Tree
Medium
300,674
1,793
hey guys this is CD and today's lead code challenge is maximum score of a good subarray so they have given you an array of integers nums and they have given you an integer you have to find the maximum score of a good sub array so for a good subar they have given you a condition and I'll explain you with an example so this is the example they have given you in this uh in this array you will be taking a sub array and you have to find the minimum element of that subarray for example they have given you an explanation here from 1 to five so when we take from 1 to five the minimum element you can find will be three so it is equal to three and you have to multiply this with the J minus I difference + 1 so here the J will be difference + 1 so here the J will be difference + 1 so here the J will be five and the I will be 1 plus one so when you multiply both the uh when you multiply both you'll be getting 15 so when you iterate through all the options in the array the maximum score will be the maximum possible score that you can get from that good array so it works like that so make sure you understood that uh condition and now uh we'll be implementing a two-pointer we'll be implementing a two-pointer we'll be implementing a two-pointer approach to solve this problem so let's start first I'll initialize the left por where uh k uh for K also they have given you a condition where the I should be less than or equal to K and J should be greater than or equal to K so since the K uh for I the left portion will be lesser than K I am making a pivote kind of point for the left pointer where left is equal to K minus one for example I'll show you in this subarray we can take K will be the middle element and this side will be left and this side will be right so for left sub array I'm having a initial portion like K minus one so I'll be iterating the left pointer this side and the right pointer will be iterating this side okay this is the TWP pointer approach we'll be using now and for right side as I said it will be starting from k + 1 portion I'll be starting from k + 1 portion I'll be starting from k + 1 portion I'll be hydrating this side and that side now after initializing both we have to find the minimum uh value for the subar and we have to find the maximum score so I'll be initializing that also so minimum value for that and the maximum score that we'll be getting both I have initialized with nums of K and we'll be getting the length will be the length of t initializing everything now we can start the iteration so when it comes to two pointer approach we'll be always using a while loop so that uh it will not uh move out of the bounds so I'm using a y Loop for this where left should be greater than or equal to zero since the left will be moving this side this uh when we keep on uh reducing it should not go less than zero so I'm having a condition left should be always greater than or equal to Z or right should be less than length now I'll be using four conditions here so first condition is left should be inside its bound also right should have its bound so here we are checking whether the left and right are within the bounds and the left value if it is greater or equal to the right value then we will we'll be updating the minimum value with the smaller one since it is smaller we'll be uh updating it with the minimum value so here the minimum value will be which is the smaller one so next we'll be updating the maximum score so we'll be updating the maximum score with that um condition where right minus left into minimum value the condition we earlier saw so after that we'll be iterating the I pointer which is uh which is the left we'll be iterating this with the left pointer next we'll be having our next condition which is else if so else if also same Works same as this so we'll be checking whether it is in the bounds and here you'll be having the right value is greater than or equal to the left value so as the same condition left is greater than or equal to Z and uh right should be less than length and nums of left here it will be will'll be checking whether it is less than or equal to the right one so according to it again I'll be updating the minimum value and maximum score and I'll be hydrating okay so minimum value let yeah after that again I'll be increasing the right pointer next other condition is um now I have to check if the left pointer is out of bounds okay so if the left is less than zero I have to update the minimum value with the right value so with the right value I'll be updating it with the right value and after that I'll be also updating the maximum score for it so maximum score will be math. Max of um maximum score again with the same condition where you'll be having the difference into the minimum value whenever you have conditions make sure you update the values so after update this again I'll be moving the right pointer here yeah then other one is else condition where the right pointer will be out of bounds so for that again I'll be having the minimum value and maximum score so after it again moving the left pointer yeah now you can uh return the Max uh maximum score here second yeah just a syntax error yeah now it should work yeah test cases have been passed thank you
Maximum Score of a Good Subarray
minimum-moves-to-make-array-complementary
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Array,Hash Table,Prefix Sum
Medium
null
292
uh today we're gonna be working on a lead code question number 292 Name Game oh you are playing the following name game with your friend initially there is a heap of stones on the table you and your friend uh will alternate taking turns and you go first so it's gonna be us who's gonna be taking the first turn uh on each turn the person whose turn it is will remove one to three stones one two or three stones from the Heap the one who removes the last stone is the winner okay given n the number of stones in the Heap return true if you can win the game assuming both you and your friend play optimally otherwise return false so as an example if n is equal to 4 the answer is going to be false because if I take one stone and the friend is gonna take the three stones and he's gonna win if I take two stones it's gonna take two other Stones then he's gonna win if I take three stones it's gonna take the last Stone and he is still gonna be the winner but if we have n is equal to 1 n is equal to 2 or n is equal to 3 if we are gonna be the winners that is basically the logic we're going to be using that if we have a number which is uh which can be completely be divided or divisible by four and the remind the remainder is going to be zero uh that number is always going to be false otherwise it's the answer is going to be true so basically we're gonna say that if the N modulus 4 uh is not equal to zero right if it is not equal to 0 that means it's going to be a true otherwise if it is completely divisible by 4 it's always going to be equal to zero like it's always we're going to be returning false 4 8 12 16 all of them are false the rest is true okay looking good and it works
Nim Game
nim-game
You are playing the following Nim Game with your friend: * Initially, there is a heap of stones on the table. * You and your friend will alternate taking turns, and **you go first**. * On each turn, the person whose turn it is will remove 1 to 3 stones from the heap. * The one who removes the last stone is the winner. Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`. **Example 1:** **Input:** n = 4 **Output:** false **Explanation:** These are the possible outcomes: 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins. 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins. 3. You remove 3 stones. Your friend removes the last stone. Your friend wins. In all outcomes, your friend wins. **Example 2:** **Input:** n = 1 **Output:** true **Example 3:** **Input:** n = 2 **Output:** true **Constraints:** * `1 <= n <= 231 - 1`
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
Math,Brainteaser,Game Theory
Easy
294
968
hello everyone welcome to quartus camp we are at 16th day of may elite foot challenge and the problem we are going to cover is binary tree cameras so the input given here is a binary tree and we have to return the number of cameras we have to keep in the binary tree and the rooms given are each camera at node can monitor its parent itself and its immediate children so we have to calculate the minimum number of cameras needed to monitor all the nodes of the tree so let's understand this problem with an example so consider this is a binary tree the rule said that if we place a camera in this node it will monitor itself and its parent and its children so now if we are trying to place a camera on the root mode then it will cover itself and its children so we still have two more notes left so if we are planning to keep the camera in our second node in this case it will cover its parent as well as the children so placing one camera at this position is what we needed so this is the one is the minimum number of camera needed for this particular binary tree to monitor all these nodes so we are going to return one other output so how are we going to approach this so let us go greedy about it so what would be the particular node where we have to keep cameras that we are sure about so we are going to search and find the nodes where we are going to keep the cameras for sure and then start our solution from that point for example consider root node of any binary tree if suppose you want to cover the root node what are the options you either have to keep camera on that root node or you keep camera in its left child or right child all these three options if you keep camera in any of these three options then it is going to cover our root node so consider this nodes between the root node and the leaf node that is the level after root and before leaf so if you want to monitor these nodes in between you either have to keep a camera on that particular note or you have to keep the camera on its parent or you have to keep the camera on its left side or the right side so in this case you have four options to monitor any node which is in between so now moving on to a leaf node so if we are moving on to our leaf nodes we have only two options either we have to keep cameras on the leaf nodes or its parent so we are sure that we either have to keep cameras on all the leaf nodes or its parent to cover the leaf nodes that is the one thing we can be sure about so in this case if you are trying to keep cameras in all the leaf nodes in this case you will be having a more number of cameras in your binary tree because as the level goes down the nodes increases at each level at the last level it will be having the more children than the previous level so in this case also you have more children so in this case we are trying to keep camera on all the leaf nodes so you will be not having the optimal solution or optimal number of cameras you will end up having many cameras than needed so out of these two options we have tried keeping cameras in the leaf nodes if it is not the optimal way let's keep cameras on its parent mode so in this case you will definitely cover your leaf nodes so this is the first step we are going to implement so we are always going to keep a camera of parent node to the leaf node so that is the first step based on this step that is where we kept the camera we are going to fill the cameras to the previous step so basically we are going to do a bottom-up approach that is going to do a bottom-up approach that is going to do a bottom-up approach that is starting from the leaf node we are going to complete filling the camera towards the top of the binary tree so consider this example as i said we are going to keep a camera to the parent of our leaf node so here is our leaf node the parent of the leaf node is going to have a camera so based on this camera we are going to further check which are the notes needed the camera if there is a camera here it parent doesn't need a camera because it will be covered so we are going to go one step before and place cameras as needed so before understanding what actually we are going to implement in algorithm we clearly now know we need a tree traversal technique in order to traverse the trees and let us understand the status so which traversal technique we are going to use is dfs as we are going to go deep in a binary tree but out of dfs which technique we are going to use in order pre-order or post order pre-order or post order pre-order or post order definitely it is going to be post order because we are going to fill the cameras based on the values of his children as we are moving from leaf node to root node that is from children to parent we need the status of both left and right children in order to predict whether we have to keep the camera on the parent or not so in this case we first need the status of left and right children before knowing the status of the parent so our post order traversal is the only technique which visits both left and right side first and then come back to the root node so hope you all understand what is a dfs and post order dfs and how does it work and we are going to use the basic recursive function which visit the left node first and write node next and then do the rest of the operation so in the basic dfs we will be visiting the node and printing the values but here we are going to assign a status to each node and our df is going to help us let us know the status of our children that is left and right children so that will decide what should be the status of our parent so what does the status mean here so consider this tree if we are trying to keep a camera in this particular node in that case that camera where it kept has been in the status having a camera so we are going to have three status and the first status is having the camera hope this itself defines and if you keep the camera there it is going to cover its parent and its children in that case they are going to in the covered status so whenever we keep a camera we are going to make its parent and children to covered status and the risk that this camera will not cover is going to be in uncovered status so these are the three statuses that our nodes are going to have and based on these statuses we are going to fill our nodes with cameras going upward so yes this is a simple technique let's go for a very quick dry run before getting into our implementation so let me take the same example as given in the problem statement as i said we are going to always keep a camera to the parent of the leaf node so as our dfs is always going down deep till the leaf node first is gonna check whether it reached the leaf node so when it is in this node it is going to check whether leaf node is there and then it fix the camera here so now the status of our leaf node is going to be covered and where we kept the camera is going to be having camera so once this is done we are going to go one node upward that is parent of this node and check its status so it is going to check either of its children is having a camera then it is covered which means if it is having a left child and a right child it is going to check both of its status if either of them having a camera which means it will monitor its parent which means it is covered so we are having a camera in its left child so it is going to be covered so now moving one level upward to its parent we are exactly at this node and we are going to check either of its children are having a camera no it doesn't have a right side it is having a left child it is covered but not having the camera which means we need an extra camera which monitor this node so let us keep one more camera here so once we keep the camera this status is gonna have been changed to having cam and its parent is going to be updated to covered as it is going to check the parent of it in next iteration and it is going to check either of the children are having a camera yes it is having a camera then it is going to be covered so overall we are going to keep track of the number of cameras we keep with a variable result and every time we keep a camera and set the status to having camera we are going to increment its count and finally return the result as an output as we have kept two cameras here we are going to return to other output so hope you are understanding the solution and this is going to do a basic dfs and iterate by number of nodes present into the binary tree so it is overall going to take big o of n time complexity to run this algorithm so let us go to implementation now so let us first write our dfs function before getting back to our main function so i am going to return a string which is nothing but the status strings i have told you can also implement this using the status numbers like having 0 1 2 for the statuses but here i'm implementing using string for the easier understanding so first we are going to check if the root is equal to null then return the status covered so this is nothing but if you reach the leaf node and it doesn't have any children then the children will be null in that case the leaf node will be already covered as we are going to keep the parent camera so next i'm going to call and call my dfs to get the status of my left and right child so string left is equal to dfs of group dot left so now once we get the status we are going to check if any of our children is not covered which means we need a camera to monitor them so we are going to check if left is equal to not covered or right is equal to not covered if either of its children are not covered in that case we have to keep a camera on that node so what are we going to do as we are going to keep a camera we are going to update our result so before that let me declare a global variable result here and once we keep the camera we are going to update result plus and return its status is having a camera because we have placed a camera in that node if not the other status is if it is having a camera so if it is having a camera which means we have to set the status to covered as i explained if either of its children is having a camera then the parent is covered so return if left is equal to having camera or right is equal to having camera then in that case the parent is covered if not none of them are having the camera which means the status is not covered once it takes all the left and right children and go up to root node then in our main method we are going to call dfs of root so here this dfs of root will actually return the status of its left and right shell so in this case we are going to finally check if the route is covered or not covered if it is covered we can simply return the result what we have that is how many cameras so far we have kept simply if the root is not covered then finally it need one more camera at the root of the binary tree so we are checking the status if root is not covered then we are going to add one if not we are going to add zero with the result so yes that's it let me run so yes let's submit yes a solution is accepted hope i made it simple this time so if you like the video hit like subscribe and let me know in comments thank you
Binary Tree Cameras
beautiful-array
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return _the minimum number of cameras needed to monitor all nodes of the tree_. **Example 1:** **Input:** root = \[0,0,null,0,0\] **Output:** 1 **Explanation:** One camera is enough to monitor all nodes if placed as shown. **Example 2:** **Input:** root = \[0,0,null,0,null,0,null,null,0\] **Output:** 2 **Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val == 0`
null
Array,Math,Divide and Conquer
Medium
null